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
派生
35.9k
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 摘要。