python / python/cpython

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

オープン
#130,410 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

extension-modules topic-ctypes type-bug
主要言語
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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

32 ビット x86 で ctypes.Structure のビットフィールド例を再現し、レポートで説明されているビットフィールドの格納単位の扱いを調査します。包含する構造体の外部のメモリを読み書きせずに、GCC 互換の構造体サイズを維持できれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
c, python
領域
backend
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
25/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。