Skip to content

Commit d88a6b9

Browse files
authored
gh-162350: Add strong references to arguments of delta_new_impl(). (#162748)
Issue introduced in commit 1994e3f, raised in comment #162500 (comment). `delta_new_impl()` calls `accum()`, which in turn calls `PyNumber_Multiply()` and `PyNumber_Add()`, whose arguments could be a subclass of int or float that overloads `__mul__`/`__add__` with arbitrary Python code. `delta_new_impl()` calls `accum()` for 7 times in sequnce, with each of the 7 timeunit arguments, all with borrowed references, from `microseconds` to `weeks`. Chances are that those arbitrary Python code could release strong references of one of the 7 timeunit arguments. When `accum()` is called with an argument whose last references has been destroyed, it operates on a dangling pointer. Should let `delta_new_impl()` hold strong references of its arguments to avoid being released early.
1 parent ebd4a5d commit d88a6b9

1 file changed

Lines changed: 21 additions & 2 deletions

File tree

‎Modules/_datetimemodule.c‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2795,12 +2795,22 @@ delta_new_impl(PyTypeObject *type, PyObject *days, PyObject *seconds,
27952795
PyObject *minutes, PyObject *hours, PyObject *weeks)
27962796
/*[clinic end generated code: output=61d7e02a92a97700 input=8aebc4cdef360d1f]*/
27972797
{
2798+
/* vectorcall passes borrowed references; hold strong references before
2799+
any conversion can execute arbitrary Python code. */
2800+
Py_XINCREF(days);
2801+
Py_XINCREF(seconds);
2802+
Py_XINCREF(microseconds);
2803+
Py_XINCREF(milliseconds);
2804+
Py_XINCREF(minutes);
2805+
Py_XINCREF(hours);
2806+
Py_XINCREF(weeks);
2807+
27982808
PyObject *self = NULL;
27992809

28002810
PyObject *current_mod;
28012811
datetime_state *st = GET_CURRENT_STATE(current_mod);
28022812
if (st == NULL) {
2803-
return NULL;
2813+
goto Done;
28042814
}
28052815

28062816
PyObject *x = NULL; /* running sum of microseconds */
@@ -2886,7 +2896,16 @@ delta_new_impl(PyTypeObject *type, PyObject *days, PyObject *seconds,
28862896
Py_DECREF(x);
28872897

28882898
Done:
2889-
RELEASE_CURRENT_STATE(st, current_mod);
2899+
Py_XDECREF(days);
2900+
Py_XDECREF(seconds);
2901+
Py_XDECREF(microseconds);
2902+
Py_XDECREF(milliseconds);
2903+
Py_XDECREF(minutes);
2904+
Py_XDECREF(hours);
2905+
Py_XDECREF(weeks);
2906+
if (st != NULL) {
2907+
RELEASE_CURRENT_STATE(st, current_mod);
2908+
}
28902909
return self;
28912910

28922911
#undef CLEANUP

0 commit comments

Comments
 (0)