python / python/cpython

decimal: crash when a re-entrant __bool__ deallocates the Context during Context.flags assignment or comparison

Open
#155,493 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

extension-modules type-crash
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Context.flags (and traps) is a SignalDict that borrows a pointer to
flags owned by its Context. signaldict_setitem and
signaldict_richcompare read that pointer after calling back into Python
(PyObject_IsTrue, i.e. the value's __bool__), which can deallocate the
Context. gh-146011 cleared the borrowed pointer on Context teardown and
guarded signaldict_repr, but these two methods were left unguarded, so the
same teardown leaves them dereferencing a NULL pointer and crashing.

Assignment:

import decimal, gc
ctx = decimal.Context()
flags = ctx.flags
class Evil:
    def __bool__(self):
        global ctx; del ctx; gc.collect()
        return True
flags[decimal.InvalidOperation] = Evil()   # segfault

Comparison:

import decimal, gc
ctx = decimal.Context()
other = ctx.flags.copy()
class Evil:
    def __bool__(self):
        global ctx; del ctx; gc.collect()
        return True
other[decimal.InvalidOperation] = Evil()
ctx.flags == other                          # segfault

Both crash with SIGSEGV on current main; the affected code exists on 3.13+.

Linked PRs
  • gh-155494

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the decimal module entry points signaldict_setitem and signaldict_richcompare, then reproduce the assignment and comparison examples from the issue on Python 3.13+. Done means both re-entrant bool cases no longer crash after Context teardown; note that linked PR gh-155494 already covers this work.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.