python / python/cpython

`defaultdict` reads `default_factory` as a borrowed reference in `defdict_repr` / `defdict_missing` under free-threading

未关闭
#154,527 3 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

extension-modules topic-free-threading type-crash
主要语言
Python
星标
77.2k
派生
35.9k
PR 合并指标
PR 指标待抓取

描述

Crash report

What happened?

In the free-threaded build, collections.defaultdict reads its default_factory slot as a plain, borrowed reference and then uses the pointed-to object (reprs it, or calls it) without holding a strong reference or taking the object's critical section.

defdict_repr reads dd->default_factory directly and passes it to PyObject_Repr (and Py_ReprEnter/Py_ReprLeave) with no incref and no critical section.

https://github.com/python/cpython/blob/a2a846678e54b1b5defdccd451c573679094ff02/Modules/_collectionsmodule.c#L2373-L2410

defdict_missing (the __missing__ path taken by dd[key] for an absent key) loads dd->default_factory into a local borrowed pointer and calls it.

https://github.com/python/cpython/blob/a2a846678e54b1b5defdccd451c573679094ff02/Modules/_collectionsmodule.c#L2233-L2256

The writer side is already free-threading-correct. Assigning dd.default_factory goes through PyMember_SetOne (Py_T_OBJECT_EX), which publishes the new value under a critical section with an atomic release store and then decrefs the old value.

https://github.com/python/cpython/blob/a2a846678e54b1b5defdccd451c573679094ff02/Python/structmember.c#L322-L327

So the defect is entirely on the reader side. The plain borrowed load races the writer's atomic store (a data race on the field), and the borrowed pointer is then used after the writer's Py_XDECREF has already freed the old factory.

When the old factory is referenced only by the defaultdict, a concurrent assignment drops its refcount to zero and func_dealloc runs while a reader is mid-repr or mid-call on it. The reader then reprs or calls a freed object, a use-after-free that crashes(segfault) or corrupts memory.

Reproducer:

import collections
from threading import Thread

dd = collections.defaultdict(lambda: 0)
KEY = "k"

def setter():
    for _ in range(500000):
        dd.default_factory = lambda: 1 

def reprer():
    for _ in range(20000):
        try:
            repr(dd)
        except Exception:
            pass

def getter():
    for _ in range(20000):
        try:
            dd.pop(KEY, None)
            dd[KEY] 
        except Exception:
            pass

threads  = [Thread(target=setter) for _ in range(4)]
threads += [Thread(target=reprer) for _ in range(6)]
threads += [Thread(target=getter) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()

TSAN Report:

==================
WARNING: ThreadSanitizer: data race (pid=1525801)
  Atomic write of size 8 at 0x7fffb66a4370 by thread T1:
    #0 _Py_atomic_store_ptr_release cpython/./Include/cpython/pyatomic_gcc.h:565:3 
    #1 PyMember_SetOne cpython/Python/structmember.c:326:9
    #2 member_set cpython/Objects/descrobject.c:239:12
    #3 _PyObject_GenericSetAttrWithDict cpython/Objects/object.c:2049:19 
    #4 PyObject_GenericSetAttr cpython/Objects/object.c:2120:12
    #5 PyObject_SetAttr cpython/Objects/object.c:1533:15
    #6 _PyEval_EvalFrameDefault cpython/Python/generated_cases.c.h:12146:27 

  Previous read of size 8 at 0x7fffb66a4370 by thread T5:
    #0 defdict_repr cpython/./Modules/_collectionsmodule.c:2384:13 
    #1 PyObject_Repr cpython/Objects/object.c:784:11
    #2 builtin_repr cpython/Python/bltinmodule.c:2677:12
    #3 _PyEval_EvalFrameDefault cpython/Python/generated_cases.c.h:2712:35

SUMMARY: ThreadSanitizer: data race cpython/./Include/cpython/pyatomic_gcc.h:565:3 in _Py_atomic_store_ptr_release
==================
==================
WARNING: ThreadSanitizer: data race (pid=1525801)
  Read of size 8 at 0x7fffb66a4370 by thread T11:
    #0 defdict_missing cpython/./Modules/_collectionsmodule.c:2238:29 
    #1 cfunction_vectorcall_O cpython/Objects/methodobject.c:536:24 
    #2 _PyObject_VectorcallTstate cpython/./Include/internal/pycore_call.h:144:11 
    #3 PyObject_CallOneArg cpython/Objects/call.c:395:12 
    #4 _PyDict_SubscriptKnownHash cpython/Objects/dictobject.c:3722:23 
    #5 _PyDict_Subscript cpython/Objects/dictobject.c:3743:12 
    #6 _PyEval_EvalFrameDefault cpython/Python/generated_cases.c.h:686:35

  Previous atomic write of size 8 at 0x7fffb66a4370 by thread T4:
    #0 _Py_atomic_store_ptr_release cpython/./Include/cpython/pyatomic_gcc.h:565:3 
    #1 PyMember_SetOne cpython/Python/structmember.c:326:9 
    #2 member_set cpython/Objects/descrobject.c:239:12 
    #3 _PyObject_GenericSetAttrWithDict cpython/Objects/object.c:2049:19 
    #4 PyObject_GenericSetAttr cpython/Objects/object.c:2120:12 
    #5 PyObject_SetAttr cpython/Objects/object.c:1533:15
    #6 _PyEval_EvalFrameDefault cpython/Python/generated_cases.c.h:12146:27

SUMMARY: ThreadSanitizer: data race cpython/./Modules/_collectionsmodule.c:2238:29 in defdict_missing
==================
...
==================
WARNING: ThreadSanitizer: data race (pid=1525801)
  Read of size 8 at 0x7fffc00f0d98 by thread T7:
    #0 PyObject_Repr cpython/Objects/object.c:766:9 
    #1 defdict_repr cpython/./Modules/_collectionsmodule.c:2397:23
    #2 PyObject_Repr cpython/Objects/object.c:784:11
    #3 builtin_repr cpython/Python/bltinmodule.c:2677:12 
    #4 _PyEval_EvalFrameDefault cpython/Python/generated_cases.c.h:2712:35

  Previous write of size 8 at 0x7fffc00f0d98 by thread T3:
    #0 Py_SET_TYPE cpython/./Include/object.h:207:17
    #1 _PyObject_Init cpython/./Include/internal/pycore_object.h:482:5 
    #2 _PyObject_GC_New cpython/Python/gc_free_threading.c:2752:5
    #3 PyFunction_NewWithQualName cpython/Objects/funcobject.c:202:28
    #4 PyFunction_New cpython/Objects/funcobject.c:392:12
    #5 _PyEval_EvalFrameDefault cpython/Python/generated_cases.c.h:10844:17 

SUMMARY: ThreadSanitizer: data race cpython/Objects/object.c:766:9 in PyObject_Repr
==================
...
==================
WARNING: ThreadSanitizer: data race (pid=1525801)
  Read of size 8 at 0x7fffb80f0f98 by thread T11:
    #0 _PyVectorcall_FunctionInline cpython/./Include/internal/pycore_call.h:105:5 
    #1 _PyObject_VectorcallTstate cpython/./Include/internal/pycore_call.h:139:12
    #2 _PyObject_CallNoArgs cpython/./Include/internal/pycore_call.h:160:12 
    #3 defdict_missing cpython/./Modules/_collectionsmodule.c:2249:13
    #4 cfunction_vectorcall_O cpython/Objects/methodobject.c:536:24
    #5 _PyObject_VectorcallTstate cpython/./Include/internal/pycore_call.h:144:11
    #6 PyObject_CallOneArg cpython/Objects/call.c:395:12 
    #7 _PyDict_SubscriptKnownHash cpython/Objects/dictobject.c:3722:23
    #8 _PyDict_Subscript cpython/Objects/dictobject.c:3743:12
    #9 PyObject_GetItem cpython/Objects/abstract.c:163:26
    #10 _PyEval_EvalFrameDefault cpython/Python/generated_cases.c.h:67:35

  Previous write of size 8 at 0x7fffb80f0f98 by thread T1:
    #0 PyFunction_NewWithQualName cpython/Objects/funcobject.c:224:20
    #1 PyFunction_New cpython/Objects/funcobject.c:392:12
    #2 _PyEval_EvalFrameDefault cpython/Python/generated_cases.c.h:10844:17

SUMMARY: ThreadSanitizer: data race cpython/./Include/internal/pycore_call.h:105:5 in _PyVectorcall_FunctionInline
==================
...
==================
ThreadSanitizer:DEADLYSIGNAL
==1525801==ERROR: ThreadSanitizer: SEGV on unknown address (pc 0x5555556b79ac bp 0x7fffaf3f98b0 sp 0x7fffaf3f9858 T1525807)
==1525801==The signal is caused by a READ memory access.
==1525801==Hint: this fault was caused by a dereference of a high value address (see register values below).  Disassemble the provided pc to learn which register was used.
ThreadSanitizer:DEADLYSIGNA

(or this happened)

SUMMARY: ThreadSanitizer: data race /cpython/Objects/object.c:477:40 in _Py_ExplicitMergeRefcount
==================
SystemError: Objects/weakrefobject.c:1023: bad argument to internal function

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/cpython/cpython-tsan/lib/python3.16t/threading.py", line 1218, in _bootstrap_inner
    self._context.run(self.run)
    ~~~~~~~~~~~~~~~~~^^^^^^^^^^
  File "/cpython/cpython-tsan/lib/python3.16t/threading.py", line 1164, in run
    del self._target, self._args, self._kwargs
        ^^^^^^^^^^^^
SystemError: PyObject_SetAttr() must not be called with NULL value and an exception set
SystemError: Objects/weakrefobject.c:1023: bad argument to internal function

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/cpython/cpython-tsan/lib/python3.16t/threading.py", line 1218, in _bootstrap_inner
    self._context.run(self.run)
    ~~~~~~~~~~~~~~~~~^^^^^^^^^^
  File "/cpython/cpython-tsan/lib/python3.16t/threading.py", line 1164, in run
    del self._target, self._args, self._kwargs
        ^^^^^^^^^^^^
SystemError: PyObject_SetAttr() must not be called with NULL value and an exception set
ThreadSanitizer: reported 36 warnings
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 free-threading build (tags/v3.15.0b1-614-g7928a8b730b:7928a8b730b, Jul 22 2026, 10:44:15) [Clang 18.1.3 (1ubuntu1)]

Linked PRs
  • gh-154560

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

阅读 Modules/_collectionsmodule.c 中的 defdict_repr 和 defdict_missing,然后将读取器行为与 Python/structmember.c:322-327 进行比较。在 ThreadSanitizer 下运行提供的 free-threaded reproducer,并检查关联的 PR gh-154560;当报告的 race、use-after-free 崩溃和相关故障不再发生时,即表示完成。

由索引模型根据 Issue 内容生成。

评估

技术栈
c, python
领域
backend
Issue 类型
缺陷
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
描述清楚
新手友好度
25/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。