python / python/cpython

ctypes.Structure: bitfield of underaligned type can cause read of unrelated memory

未關閉
#130,410 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

extension-modules topic-ctypes type-bug
主要語言
Python
星號
77.2k
分支
36k
PR 合併指標
PR 指標待擷取

描述

Bug report

Bug description:

(This is an exotic edge case found by tests that are perhaps too stringent, but, we prefer issues over XXX comments in the code, so, here goes.)

A bitfield of an “underaligned” type (one whose alignment is smaller than its size) can cause the “storage unit” that ctypes uses for handling the bitfield to extend past the containing Structure.

For example, on 32-bit x86 architecture, where int64_t is 8 bytes long but only aligned to 4 bytes, we have:

>>> import ctypes
>>> class S(ctypes.Structure):
...     _fields_ = [('f', ctypes.c_int64, 1)]
>>> ctypes.sizeof(S)
4
>>> ctypes.sizeof(ctypes.c_int64)
8

This matches GCC struct layout:

#include <stdio.h>
#include <stdint.h>

struct S {
    int64_t f: 1;
};

int main() {
    printf("%zd\n", sizeof(struct S));  // -> 4
}

ctypes handles bitfield reads/writes by reading the entire storage unit, masking/shifting, and (for writes) writing the entire unit back. So, in this case it can read/write memory that doesn't belong to the struct.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

在 32 位元 x86 上重現 ctypes.Structure 位元欄位範例,並檢查報告中描述的位元欄位儲存單位處理方式。完成標準是在不讀取或寫入包含該結構之外的記憶體的情況下,維持與 GCC 相容的結構大小。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
c, python
領域
backend
Issue 類型
缺陷
難度
4/5
預估耗時
3-5 天
活躍度
停滯
描述清晰度
需要釐清
新手友好度
25/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。