python / python/cpython

Allocated size miscalculated in ASDL sequence constructor

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

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

interpreter-core topic-parser type-bug
主要言語
Python
スター
77.2k
フォーク
35.9k
PR マージ指標
PR 指標を取得中

説明

In the macro generating ASDL sequence constructor in pycore_asdl.h, the extra allocated size is miscalculated as sizeof(TYPE *) * (size - 1), while the correct one should be sizeof(TYPE) * (size - 1):

#define GENERATE_ASDL_SEQ_CONSTRUCTOR(NAME, TYPE) \
asdl_ ## NAME ## _seq *_Py_asdl_ ## NAME ## _seq_new(Py_ssize_t size, PyArena *arena) \
{ \
    asdl_ ## NAME ## _seq *seq = NULL; \
    size_t n; \
    /* check size is sane */ \
    if (size < 0 || \
        (size && (((size_t)size - 1) > (SIZE_MAX / sizeof(void *))))) { \
        PyErr_NoMemory(); \
        return NULL; \
    } \
    n = (size ? (sizeof(TYPE *) * (size - 1)) : 0); \                       // <----------------------------- this line
    /* check if size can be added safely */ \
    if (n > SIZE_MAX - sizeof(asdl_ ## NAME ## _seq)) { \
        PyErr_NoMemory(); \
        return NULL; \
    } \
    n += sizeof(asdl_ ## NAME ## _seq); \
    seq = (asdl_ ## NAME ## _seq *)_PyArena_Malloc(arena, n); \
    if (!seq) { \
        PyErr_NoMemory(); \
        return NULL; \
    } \
    memset(seq, 0, n); \
    seq->size = size; \
    seq->elements = (void**)seq->typed_elements; \
    return seq; \
}

A sample struct definition and usage taken from the source code:

// pycore_asdl.h
#define asdl_seq_GET(S, I) _Py_RVALUE((S)->typed_elements[(I)])

// pycore_ast.h
typedef struct {
    _ASDL_SEQ_HEAD
    expr_ty typed_elements[1];
} asdl_expr_seq;

// Python-ast.c
GENERATE_ASDL_SEQ_CONSTRUCTOR(expr, expr_ty)

// ast.c - validate_exprs
asdl_expr_seq *exprs
expr_ty expr = asdl_seq_GET(exprs, i);

This shows that the stored elements have type TYPE (i.e. expr_ty), not TYPE *. So the extra allocated memory should be sizeof(TYPE) * (size - 1) instead of sizeof(TYPE *) * (size - 1).

This hasn't cause problem yet because in every uses of GENERATE_ASDL_SEQ_CONSTRUCTOR, TYPE is either int or some pointer, so sizeof(TYPE*)'s are not smaller than sizeof(TYPE). But it can cause confusion and potential bug in the future.

Linked PRs
  • gh-129934

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

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

はじめの一歩

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

調査の方向性

Include/internal/pycore_asdl.h の GENERATE_ASDL_SEQ_CONSTRUCTOR から始め、PR gh-129934 にリンクされている作業を確認してください。割り当て計算が型付き要素のストレージと一致することを検証し、その後、関連する CPython テストスイートまたは ASDL/AST テストを実行して、コンストラクターが引き続き正しいことを確認してください。

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

評価

技術スタック
c
領域
backend
issue の種類
バグ
難易度
1/5
見積もり時間
1時間未満
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
25/100

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

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