Skip to content

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

Description

@tonghuaroot

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions