python / python/cpython

dir() can crash with cyclic __bases__

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

還沒有人認領這個 Issue。

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

描述

Crash report

What happened?

dir() can cause a native stack overflow when an object's __class__
provides a cyclic __bases__ attribute.

Minimal reproducer:

class Fake:
    pass

a = Fake()
a.__bases__ = (a,)

class C:
    @property
    def __class__(self):
        return a

print("entering", flush=True)
dir(C())
print("survived", flush=True)
Observed Result

On CPython 3.16.0a0 built from commit 5107fd700d7:

entering
timeout: the monitored command dumped core
Segmentation fault
rc=139

The crash occurs because object.__dir__() obtains the object's __class__ and merge_class_dict() recursively traverses __bases__ without a recursion guard. A cyclic __bases__ therefore causes unbounded native recursion and eventually a SIGSEGV.

The analogous __bases__ traversal in abstract_issubclass() already uses _Py_EnterRecursiveCall().

I also verified that adding a recursion guard to merge_class_dict() changes the failure from a native crash to a catchable exception:

RecursionError: Stack overflow (used 8120 kB) in __bases__

A regression test covering the cyclic __bases__ case was also added to Lib/test/test_builtin.py and passes with:

./python -m test test_builtin -m test_dir
== Tests result: SUCCESS ==
1 test OK.
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/investigate-0071-dir-cyclic-bases-dirty:5107fd700d7, Aug 9 2026, 21:10:20) [GCC 13.3.0]

Linked PRs
  • gh-155453

貢獻指南

開啟貢獻指南

從這裡開始

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

研究方向

先從 merge_class_dict() 和 issue 中描述的循環 bases 重現案例開始,然後閱讀 Lib/test/test_builtin.py 中的回歸測試。執行 ./python -m test test_builtin -m test_dir;當該案例引發可捕捉的 RecursionError,而不是造成原生堆疊溢位時,即表示完成。

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

評估

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

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

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