ctypes.Structure: bitfield of underaligned type can cause read of unrelated memory
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 77.2k
- 派生
- 35.9k
- 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
贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
在 32 位 x86 上重现 ctypes.Structure 位域示例,并检查报告中描述的位域存储单元处理方式。完成标准是在不读取或写入包含该结构体之外的内存的情况下,保持与 GCC 兼容的结构体大小。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- c, python
- 领域
- backend
- Issue 类型
- 缺陷
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 活跃度
- 停滞
- 描述清晰度
- 需要澄清
- 新手友好度
- 25/100