Skip to content

OrderedDict: Use-after-free on _ODictNode and unowned node->key in _odict_resize() under re-entrant __eq__ #163182

Backlog

Description

@nevercodecorrect

Bug Description

_odict_resize() in Objects/odictobject.c walks od's doubly-linked list via _odict_FOREACH(od, node) and calls _odict_get_index_raw(od, _odictnode_KEY(node), _odictnode_HASH(node)) without holding a strong reference to node->key or checking whether od was mutated during key comparison.

When dict.update(od, ...) resizes the underlying dict hash table without updating od->od_resize_sentinel and inserts a hash-colliding key ahead of an existing OrderedDict key, a subsequent OrderedDict method (such as od.move_to_end(...)) triggers _odict_resize(). During _Py_dict_lookup, the colliding key's __eq__ method can call od.clear(), deallocating all _ODictNode structs (_odictnode_DEALLOC) and dropping node->key while _Py_dict_lookup and _odict_resize() continue reading node->key, storing freed node into fast_nodes[i], and dereferencing node->next in _odict_FOREACH.

Reproduction

from collections import OrderedDict

od = OrderedDict()
armed = False


class CollideKey:
    def __init__(self, v):
        self.v = v

    def __hash__(self):
        return 42

    def __eq__(self, other):
        if armed:
            od.clear()
            for j in range(10):
                od[f"x{j}"] = j
        return isinstance(other, CollideKey) and self.v == other.v


for i in range(10):
    od[CollideKey(i)] = i

# Resize underlying dict ma_keys without updating od_resize_sentinel
dict.update(od, {f"pad_{i}": i for i in range(100)})
armed = True
try:
    od.move_to_end(CollideKey(0))
except KeyError:
    pass
print("FINISHED_WITHOUT_TRAP")

At lines 579-587:

  • _odictnode_KEY(node) is passed as an unowned borrowed pointer into _odict_get_index_raw().
  • After _odict_get_index_raw() returns, fast_nodes[i] = node (L586) and node = _odictnode_NEXT(node) (L533 / L579) dereference node even if od.clear() freed all _ODictNode allocations during __eq__, and i is not checked against size if ma_keys changed.
./configure --with-address-sanitizer --with-pydebug
make -j"$(nproc)"
PYTHONMALLOC=malloc ASAN_OPTIONS="detect_leaks=0:symbolize=1" ./python reproduce.py

It also affects --disable-gil builds; on --disable-gil --with-address-sanitizer.

==77==ERROR: AddressSanitizer: heap-use-after-free on address 0x512000052fe8 at pc 0x55eba14957be bp 0x7ffc54bd2bc0 sp 0x7ffc54bd2bb8
READ of size 8 at 0x512000052fe8 thread T0
    #0 0x55eba14957bd in _Py_TYPE_impl third_party/cpython-stock/Include/object.h:234:16
    #1 0x55eba14957bd in _Py_IS_TYPE_impl third_party/cpython-stock/Include/object.h:249:12
    #2 0x55eba14957bd in _Py_dict_lookup third_party/cpython-stock/Objects/dictobject.c:1375:13
    #3 0x55eba14c9561 in _odict_get_index_raw third_party/cpython-stock/Objects/odictobject.c:547:10
    #4 0x55eba14c9561 in _odict_resize third_party/cpython-stock/Objects/odictobject.c:580:13
    #5 0x55eba14c9561 in _odict_get_index third_party/cpython-stock/Objects/odictobject.c:610:26
    ...

0x512000052fe8 is located 40 bytes inside of 320-byte region [0x512000052fc0,0x512000053100)
freed by thread T0 here:
    #0 0x55eba1195706 in free (/home/meng/PyTagSan/third_party/cpython/build-host-gil-asan/python+0x3d9706) (BuildId: 1b9373ee70b51e37802bb03b5997c608c39484aa)
    #1 0x55eba15a511d in subtype_deallocthird_party/cpython-stock/Objects/typeobject.c:2924:5
    #2 0x55eba1500b63 in py_dealloc third_party/cpython-stock/Objects/object.c:3348:5
    #3 0x55eba17bea5f in _PyFrame_ClearLocals third_party/cpython-stock/Python/frame.c:108:9
    #4 0x55eba17beec7 in _PyFrame_ClearExceptCode third_party/cpython-stock/Python/frame.c:133:5
    #5 0x55eba1726f3a in clear_thread_frame third_party/cpython-stock/Python/ceval.c:2045:5
    ...

previously allocated by thread T0 here:
    #0 0x55eba119599f in malloc (/home/meng/PyTagSan/third_party/cpython/build-host-gil-asan/python+0x3d999f) (BuildId: 1b9373ee70b51e37802bb03b5997c608c39484aa)
    #1 0x55eba1581523 in _PyObject_MallocWithType third_party/cpython-stock/Include/internal/pycore_object_alloc.h:46:17
    #2 0x55eba1581523 in _PyType_AllocNoTrack third_party/cpython-stock/Objects/typeobject.c:2572:19
    #3 0x55eba1581071 in PyType_GenericAlloc third_party/cpython-stock/Objects/typeobject.c:2603:21
    #4 0x55eba10c7325 in _PyEval_EvalFrameDefault third_party/cpython-stock/Python/generated_cases.c.h:2017:36
    #5 0x55eba1714ce8 in _PyEval_EvalFramethird_party/cpython-stock/Include/internal/pycore_ceval.h:122:16
    ...

SUMMARY: AddressSanitizer: heap-use-after-free third_party/cpython-stock/Include/object.h:234:16 in _Py_TYPE_impl

Pls let me know if you have any questions.

Activity

  1. added
    extension-modules
    type-crash
    on Dec 5, 2026
  2. kingMayurg commented on Dec 5, 2026

    @kingMayurg

    Hi, I'd like to work on this.

    Proposed approach:

    • Hold strong references to node keys across the rich comparison in _odict_resize(), and detect mutation of the OrderedDict afterward (raising RuntimeError, consistent with other mutation-during-operation cases).
    • Audit the other places in Objects/odictobject.c that compare node->key the same way, and fix them too.

    Tests:
    Add regression tests in Lib/test/test_ordered_dict.py covering the different mutation paths from a re-entrant __eq__ (clear(), pop(), popitem(), move_to_end(), re-entrant resize) through each affected public method. I'll also check for refleaks and test a free-threaded build.

    Does this approach sound reasonable?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulestype-crash

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions