ctypes.Structure: bitfield of underaligned type can cause read of unrelated memory
Chưa có ai nhận issue này.
- Ngôn ngữ chính
- Python
- Star
- 77.2k
- Fork
- 35.9k
- Chỉ số merge pull request
- Chỉ số pull request đang chờ
Mô tả
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
Hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Hướng nghiên cứu
Tái hiện ví dụ bitfield của ctypes.Structure trên x86 32-bit và kiểm tra cách xử lý đơn vị lưu trữ bitfield được mô tả trong báo cáo. Hoàn thành khi giữ nguyên kích thước cấu trúc tương thích với GCC mà không đọc hoặc ghi bộ nhớ bên ngoài cấu trúc chứa nó.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Đánh giá
- Công nghệ
- c, python
- Lĩnh vực
- backend
- Loại issue
- Lỗi
- Độ khó
- 4/5
- Thời gian dự kiến
- 3-5 ngày
- Mức độ hoạt động
- Đình trệ
- Độ rõ ràng
- Cần làm rõ
- Mức phù hợp với người mới
- 25/100