Skip to content

Commit 062e82a

Browse files
jeplerdpgeorge
authored andcommitted
py/objint_mpz: Fix pow3 where third argument is zero.
This finding is based on fuzzing MicroPython. I manually minimized the test case it provided. Signed-off-by: Jeff Epler <[email protected]>
1 parent ebc9525 commit 062e82a

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

py/objint_mpz.c

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -356,9 +356,10 @@ static mpz_t *mp_mpz_for_int(mp_obj_t arg, mpz_t *temp) {
356356
mp_obj_t mp_obj_int_pow3(mp_obj_t base, mp_obj_t exponent, mp_obj_t modulus) {
357357
if (!mp_obj_is_int(base) || !mp_obj_is_int(exponent) || !mp_obj_is_int(modulus)) {
358358
mp_raise_TypeError(MP_ERROR_TEXT("pow() with 3 arguments requires integers"));
359+
} else if (modulus == MP_OBJ_NEW_SMALL_INT(0)) {
360+
mp_raise_ValueError(MP_ERROR_TEXT("divide by zero"));
359361
} else {
360-
mp_obj_t result = mp_obj_new_int_from_ull(0); // Use the _from_ull version as this forces an mpz int
361-
mp_obj_int_t *res_p = (mp_obj_int_t *)MP_OBJ_TO_PTR(result);
362+
mp_obj_int_t *res_p = mp_obj_int_new_mpz();
362363

363364
mpz_t l_temp, r_temp, m_temp;
364365
mpz_t *lhs = mp_mpz_for_int(base, &l_temp);
@@ -376,7 +377,7 @@ mp_obj_t mp_obj_int_pow3(mp_obj_t base, mp_obj_t exponent, mp_obj_t modulus) {
376377
if (mod == &m_temp) {
377378
mpz_deinit(mod);
378379
}
379-
return result;
380+
return MP_OBJ_FROM_PTR(res_p);
380381
}
381382
}
382383
#endif

tests/basics/builtin_pow3_intbig.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,8 @@
2020
print(hex(pow(y, x-1, x))) # Should be 1, since x is prime
2121
print(hex(pow(y, y-1, x))) # Should be a 'big value'
2222
print(hex(pow(y, y-1, y))) # Should be a 'big value'
23+
24+
try:
25+
print(pow(1, 2, 0))
26+
except ValueError:
27+
print("ValueError")

0 commit comments

Comments
 (0)