From ded235a4ae184f5a4b1009cd9d369ec32f8b0d10 Mon Sep 17 00:00:00 2001 From: sobolevn Date: Thu, 5 Nov 2026 13:23:30 +0300 Subject: [PATCH] gh-161389: Fix crash when passing invalid `flags` and `traps` to `decimal.Context` (GH-161393) (cherry picked from commit 7054b71e1547fa575fd243916dad5a5fbc65b238) Co-authored-by: sobolevn --- Lib/test/test_decimal.py | 14 ++++++++++++++ .../2026-11-05-11-56-50.gh-issue-161389.EIl2E6.rst | 2 ++ Modules/_decimal/_decimal.c | 6 ++++++ 3 files changed, 22 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2026-11-05-11-56-50.gh-issue-161389.EIl2E6.rst diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py index 24980a34c7490ed..96cfae7d4b838bf 100644 --- a/Lib/test/test_decimal.py +++ b/Lib/test/test_decimal.py @@ -3727,6 +3727,20 @@ def test_to_integral_value(self): self.assertRaises(TypeError, c.to_integral_value, '10') self.assertRaises(TypeError, c.to_integral_value, 10, 'x') + def test_crashing_signal_dict_traps(self): + # gh-161389 + Context = self.decimal.Context + SignalDict = type(Context().traps) + with self.assertRaisesRegex((KeyError, ValueError), "signal dict"): + Context(traps=SignalDict()) + + def test_crashing_signal_dict_flags(self): + # gh-161389 + Context = self.decimal.Context + SignalDict = type(Context().flags) + with self.assertRaisesRegex((KeyError, ValueError), "signal dict"): + Context(flags=SignalDict()) + @requires_cdecimal class CContextAPItests(ContextAPItests, unittest.TestCase): decimal = C diff --git a/Misc/NEWS.d/next/Library/2026-11-05-11-56-50.gh-issue-161389.EIl2E6.rst b/Misc/NEWS.d/next/Library/2026-11-05-11-56-50.gh-issue-161389.EIl2E6.rst new file mode 100644 index 000000000000000..62fd6fe712f6dfc --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-05-11-56-50.gh-issue-161389.EIl2E6.rst @@ -0,0 +1,2 @@ +Fixes a crash in :class:`decimal.Context` when passing invalid signaling +dicts as *flags* and *traps*. diff --git a/Modules/_decimal/_decimal.c b/Modules/_decimal/_decimal.c index 01caedee08a8eb2..7f9aa24b960a940 100644 --- a/Modules/_decimal/_decimal.c +++ b/Modules/_decimal/_decimal.c @@ -1168,6 +1168,9 @@ context_settraps_dict(PyObject *self, PyObject *value) decimal_state *state = get_module_state_from_ctx(self); if (PyDecSignalDict_Check(state, value)) { + if (SdFlagAddr(value) == NULL) { + return value_error_int(INVALID_SIGNALDICT_ERROR_MSG); + } flags = SdFlags(value); } else { @@ -1234,6 +1237,9 @@ context_setstatus_dict(PyObject *self, PyObject *value) decimal_state *state = get_module_state_from_ctx(self); if (PyDecSignalDict_Check(state, value)) { + if (SdFlagAddr(value) == NULL) { + return value_error_int(INVALID_SIGNALDICT_ERROR_MSG); + } flags = SdFlags(value); } else {