Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Lib/test/test_decimal.py
Original file line number Diff line number Diff line change
Expand Up @@ -2988,6 +2988,34 @@ def test_none_args(self):
assert_signals(self, c, 'traps', [InvalidOperation, DivisionByZero,
Overflow])

def test_signaldict_reentrant_dealloc(self):
# A __bool__ that deallocates the owning context while assigning to or
# comparing Context.flags must raise, not crash.
if self.decimal is not C:
self.skipTest("SignalDict only exists in the C implementation")
Context = self.decimal.Context
InvalidOperation = self.decimal.InvalidOperation

class Evil:
def __init__(self, box):
self.box = box
def __bool__(self):
import gc
self.box.clear()
gc.collect()
return True

box = [Context()]
flags = box[0].flags
with self.assertRaises(ValueError):
flags[InvalidOperation] = Evil(box)

box = [Context()]
other = box[0].flags.copy()
other[InvalidOperation] = Evil(box)
with self.assertRaises(ValueError):
box[0].flags == other

def test_pickle(self):

for proto in range(pickle.HIGHEST_PROTOCOL + 1):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a crash in the C implementation of :mod:`decimal` when a value's
``__bool__`` deallocates the owning context while it is assigned to, or
compared against, ``Context.flags``. Patch by tonghuaroot.
9 changes: 9 additions & 0 deletions Modules/_decimal/_decimal.c
Original file line number Diff line number Diff line change
Expand Up @@ -740,6 +740,11 @@ signaldict_setitem(PyObject *self, PyObject *key, PyObject *value)
return -1;
}

if (SdFlagAddr(self) == NULL) {
/* value.__bool__() may have deallocated the owning context. */
return value_error_int(INVALID_SIGNALDICT_ERROR_MSG);
}

if (x == 1) {
SdFlags(self) |= flag;
}
Expand Down Expand Up @@ -814,6 +819,10 @@ signaldict_richcompare(PyObject *v, PyObject *w, int op)
return NULL;
}
}
else if (SdFlagAddr(v) == NULL) {
/* w's __bool__() may have deallocated v's context. */
return value_error_ptr(INVALID_SIGNALDICT_ERROR_MSG);
}
else {
res = (SdFlags(v)==flags) ^ (op==Py_NE) ? Py_True : Py_False;
}
Expand Down
Loading