Skip to content

Commit d65baa9

Browse files
Avoid multiplying the whole numerator in _PyTime_FromSecondsObject()
Only the remainder of the division by the denominator is now scaled, as in _PyTime_ObjectToTimeval() and _PyTime_ObjectToTimespec(). Too large values are rejected before the multiplication. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 7b8e62b commit d65baa9

1 file changed

Lines changed: 41 additions & 8 deletions

File tree

‎Python/pytime.c‎

Lines changed: 41 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -954,17 +954,50 @@ pytime_from_object(PyTime_t *tp, PyObject *obj, _PyTime_round_t round,
954954
if (ratio == NULL) {
955955
return pytime_from_pyfloat(tp, obj, round, unit_to_ns);
956956
}
957-
PyObject *nsobj = multiply_divide_and_round(unit_to_ns,
958-
PyTuple_GET_ITEM(ratio, 0),
959-
PyTuple_GET_ITEM(ratio, 1),
960-
round);
957+
PyObject *divmod = checked_divmod(PyTuple_GET_ITEM(ratio, 0),
958+
PyTuple_GET_ITEM(ratio, 1));
959+
if (divmod == NULL) {
960+
Py_DECREF(ratio);
961+
return -1;
962+
}
963+
PyTime_t ns;
964+
if (PyLong_AsInt64(PyTuple_GET_ITEM(divmod, 0), &ns) < 0) {
965+
Py_DECREF(divmod);
966+
Py_DECREF(ratio);
967+
if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
968+
pytime_overflow();
969+
}
970+
return -1;
971+
}
972+
if (round == _PyTime_ROUND_UP) {
973+
/* The remainder is non-negative, so the direction of rounding
974+
depends on the sign of the whole number. */
975+
round = ns < 0 ? _PyTime_ROUND_FLOOR : _PyTime_ROUND_CEILING;
976+
}
977+
PyObject *fracobj = multiply_divide_and_round(
978+
unit_to_ns, PyTuple_GET_ITEM(divmod, 1),
979+
PyTuple_GET_ITEM(ratio, 1), round);
980+
Py_DECREF(divmod);
961981
Py_DECREF(ratio);
962-
if (nsobj == NULL) {
982+
if (fracobj == NULL) {
963983
return -1;
964984
}
965-
int rc = PyLong_AsInt64(nsobj, tp);
966-
Py_DECREF(nsobj);
967-
return rc;
985+
long frac = PyLong_AsLong(fracobj);
986+
Py_DECREF(fracobj);
987+
if (frac == -1 && PyErr_Occurred()) {
988+
return -1;
989+
}
990+
if (ns < 0 && frac > 0) {
991+
/* Avoid a spurious overflow near PyTime_MIN. */
992+
ns += 1;
993+
frac -= unit_to_ns;
994+
}
995+
if (pytime_mul(&ns, unit_to_ns) < 0 || pytime_add(&ns, frac) < 0) {
996+
pytime_overflow();
997+
return -1;
998+
}
999+
*tp = ns;
1000+
return 0;
9681001
}
9691002
}
9701003

0 commit comments

Comments
 (0)