Skip to content

Commit 16d4968

Browse files
gh-105375: Harden _datetime initialisation (#105604)
Improve error handling so init bails on the first exception.
1 parent 35cff54 commit 16d4968

File tree

2 files changed

+32
-5
lines changed

2 files changed

+32
-5
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix bugs in :mod:`!_datetime` where exceptions could be overwritten in case
2+
of module initialisation failure.

Modules/_datetimemodule.c

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6862,24 +6862,49 @@ _datetime_exec(PyObject *module)
68626862
assert(DI100Y == days_before_year(100+1));
68636863

68646864
us_per_ms = PyLong_FromLong(1000);
6865+
if (us_per_ms == NULL) {
6866+
goto error;
6867+
}
68656868
us_per_second = PyLong_FromLong(1000000);
6869+
if (us_per_second == NULL) {
6870+
goto error;
6871+
}
68666872
us_per_minute = PyLong_FromLong(60000000);
6873+
if (us_per_minute == NULL) {
6874+
goto error;
6875+
}
68676876
seconds_per_day = PyLong_FromLong(24 * 3600);
6868-
if (us_per_ms == NULL || us_per_second == NULL ||
6869-
us_per_minute == NULL || seconds_per_day == NULL) {
6870-
return -1;
6877+
if (seconds_per_day == NULL) {
6878+
goto error;
68716879
}
68726880

68736881
/* The rest are too big for 32-bit ints, but even
68746882
* us_per_week fits in 40 bits, so doubles should be exact.
68756883
*/
68766884
us_per_hour = PyLong_FromDouble(3600000000.0);
6885+
if (us_per_hour == NULL) {
6886+
goto error;
6887+
}
68776888
us_per_day = PyLong_FromDouble(86400000000.0);
6889+
if (us_per_day == NULL) {
6890+
goto error;
6891+
}
68786892
us_per_week = PyLong_FromDouble(604800000000.0);
6879-
if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL) {
6880-
return -1;
6893+
if (us_per_week == NULL) {
6894+
goto error;
68816895
}
6896+
68826897
return 0;
6898+
6899+
error:
6900+
Py_XDECREF(us_per_ms);
6901+
Py_XDECREF(us_per_second);
6902+
Py_XDECREF(us_per_minute);
6903+
Py_XDECREF(us_per_hour);
6904+
Py_XDECREF(us_per_day);
6905+
Py_XDECREF(us_per_week);
6906+
Py_XDECREF(seconds_per_day);
6907+
return -1;
68836908
}
68846909

68856910
static struct PyModuleDef datetimemodule = {

0 commit comments

Comments
 (0)