Skip to content

gh-163185: Fix use-after-free in functools.cmp_to_key - #163212

Open
abedalawieh wants to merge 1 commit into
python:mainfrom
abedalawieh:gh-163185-cmp-to-key-borrowed-refs
Open

abedalawieh wants to merge 1 commit into
python:mainfrom
abedalawieh:gh-163185-cmp-to-key-borrowed-refs

Conversation

@abedalawieh

Copy link
Copy Markdown

keyobject_richcompare() passed the borrowed lhs->object and rhs->object to PyObject_Vectorcall(). If the comparison replaces the obj attribute of a key, the wrapped object can be freed while it is still in use. With operator.lt as the comparison function, the reflected check in do_richcompare() then reads freed memory.

The fix takes strong references to both objects for the duration of the call. The reads are done inside Py_BEGIN_CRITICAL_SECTION2(self, other), because the obj member setter stores under a critical section on free-threaded builds. On default builds the critical section compiles to nothing.

The new test in test_functools (it runs for both the C and Python implementations) reports a heap-use-after-free under ASan without the fix. test_functools and test_itertools pass on a --with-pydebug --with-address-sanitizer build.

The same code is on 3.14 and 3.15, so this probably needs backports there.

@python-cla-bot

python-cla-bot Bot commented Dec 5, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant