Skip to content

Commit 1598ab1

Browse files
pythongh-130230: Fix crash in pow() with only Decimal third argument
1 parent 395335d commit 1598ab1

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

Lib/test/test_decimal.py

+9
Original file line numberDiff line numberDiff line change
@@ -4481,6 +4481,15 @@ def test_implicit_context(self):
44814481
self.assertIs(Decimal("NaN").fma(7, 1).is_nan(), True)
44824482
# three arg power
44834483
self.assertEqual(pow(Decimal(10), 2, 7), 2)
4484+
if self.decimal == C:
4485+
self.assertEqual(pow(10, Decimal(2), 7), 2)
4486+
self.assertEqual(pow(10, 2, Decimal(7)), 2)
4487+
else:
4488+
# XXX: Three-arg power doesn't use __rpow__.
4489+
self.assertRaises(TypeError, pow, 10, Decimal(2), 7)
4490+
# XXX: There is no special method to dispatch on the
4491+
# third arg of three-arg power.
4492+
self.assertRaises(TypeError, pow, 10, 2, Decimal(7))
44844493
# exp
44854494
self.assertEqual(Decimal("1.01").exp(), 3)
44864495
# is_normal
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix crash in :func:`pow` with only :class:`~decimal.Decimal` third argument.

Modules/_decimal/_decimal.c

+19-1
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,24 @@ find_state_left_or_right(PyObject *left, PyObject *right)
147147
return (decimal_state *)state;
148148
}
149149

150+
static inline decimal_state *
151+
find_state_ternary(PyObject *left, PyObject *right, PyObject *modulus)
152+
{
153+
PyTypeObject *base;
154+
if (PyType_GetBaseByToken(Py_TYPE(left), &dec_spec, &base) != 1) {
155+
assert(!PyErr_Occurred());
156+
if (PyType_GetBaseByToken(Py_TYPE(right), &dec_spec, &base) != 1) {
157+
assert(!PyErr_Occurred());
158+
PyType_GetBaseByToken(Py_TYPE(modulus), &dec_spec, &base);
159+
}
160+
}
161+
assert(base != NULL);
162+
void *state = _PyType_GetModuleState(base);
163+
assert(state != NULL);
164+
Py_DECREF(base);
165+
return (decimal_state *)state;
166+
}
167+
150168

151169
#if !defined(MPD_VERSION_HEX) || MPD_VERSION_HEX < 0x02050000
152170
#error "libmpdec version >= 2.5.0 required"
@@ -4407,7 +4425,7 @@ nm_mpd_qpow(PyObject *base, PyObject *exp, PyObject *mod)
44074425
PyObject *context;
44084426
uint32_t status = 0;
44094427

4410-
decimal_state *state = find_state_left_or_right(base, exp);
4428+
decimal_state *state = find_state_ternary(base, exp, mod);
44114429
CURRENT_CONTEXT(state, context);
44124430
CONVERT_BINOP(&a, &b, base, exp, context);
44134431

0 commit comments

Comments
 (0)