python / python/cpython

Mutable heap PyStructSequence types can segfault after modifying n_fields

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

還沒有人認領這個 Issue。

interpreter-core type-crash
主要語言
Python
星號
77.2k
分支
36k
PR 合併指標
PR 指標待擷取

描述

Crash report

What happened?

Several heap PyStructSequence types can be crashed from pure Python by modifying the writable n_fields attribute on the type and then constructing a new instance.

The issue reproduces with at least:

  • os.terminal_size
  • os.stat_result
  • time.struct_time
  • resource.struct_rusage

Minimal reproducer:

import os

os.terminal_size.n_fields = 100000
os.terminal_size((1, 2))

This consistently terminates the interpreter with:

Segmentation fault (core dumped)

The crash also reproduces for other mutable heap PyStructSequence types by assigning a large value to n_fields before construction.

The backtrace shows the crash occurring in structseq_new_impl():

#0  __strlen_avx2()
#1  PyUnicode_FromString()
#2  PyDict_GetItemStringRef()
#3  structseq_new_impl() at Objects/structseq.c:243

At the point of failure:

max_len = 100000
i = 2
n_unnamed_fields = 0

From inspecting Objects/structseq.c, structseq_new_impl() uses the type's n_fields value to determine how many member names to process. After modifying n_fields from Python, the constructor eventually reaches a NULL member name, leading to a crash through PyDict_GetItemStringRef() and PyUnicode_FromString().

During investigation I also verified that immutable builtin structseq types such as sys.version_info are not affected because their type attributes cannot be modified and new instances cannot be created.

I searched the existing issue tracker using keywords including:

  • structseq_new_impl
  • PyStructSequence_NewType
  • n_fields
  • Objects/structseq.c
  • PyDict_GetItemStringRef
  • tp_members

but could not find an existing report describing this behavior.

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Output from running 'python -VV' on the command line:

Python 3.16.0a0 (heads/main:e469fa9c807, Aug 7 2026, 09:37:12) [GCC 13.3.0]

Linked PRs
  • gh-155361

貢獻指南

開啟貢獻指南

從這裡開始

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

研究方向

從 Objects/structseq.c 和 structseq_new_impl() 開始,然後執行 issue 中描述的 os.terminal_size 最小重現程式。比較可寫入的 n_fields 值與可用成員名稱的處理方式;完成標準是建構受影響的型別不再當機,且回歸涵蓋範圍證明了此行為。

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

評估

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

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

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