Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions Lib/test/datetimetester.py
Original file line number Diff line number Diff line change
Expand Up @@ -7509,6 +7509,54 @@ def func():
self.assertEqual(out, b"a" * 8)
self.assertEqual(err, b"")

@support.cpython_only
def test_gh_151039(self):
# gh-151039: This code used to crash
script = """if True:
import sys, gc
import _datetime

td = _datetime.timedelta # static C type, survives the module
del sys.modules['_datetime']
del _datetime
sys.modules['_datetime'] = None # block re-import
gc.collect() # module object is collected

try:
td(seconds=2) # used to be a segmentation fault
except ImportError:
pass
else:
assert False, "ImportError not raised"
"""
rc, out, err = script_helper.assert_python_ok("-c", script)
self.assertEqual(rc, 0)
self.assertEqual(out, b'')
self.assertEqual(err, b'')

@support.cpython_only
def test_static_type_at_shutdown(self):
# gh-132413
script = textwrap.dedent("""
import _datetime
timedelta = _datetime.timedelta

def gen():
try:
yield
finally:
# sys.modules is empty
_datetime.timedelta(days=1)
timedelta(days=1)

it = gen()
next(it)
""")
rc, out, err = script_helper.assert_python_ok("-c", script)
self.assertEqual(rc, 0)
self.assertEqual(out, b'')
self.assertEqual(err, b'')


def load_tests(loader, standard_tests, pattern):
standard_tests.addTest(ZoneInfoCompleteTest())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix a crash when :class:`datetime.timezone` outlives ``_datetime`` module.
35 changes: 33 additions & 2 deletions Modules/_datetimemodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,10 @@ get_current_module(PyInterpreterState *interp)
}
if (ref != NULL) {
if (ref != Py_None) {
(void)PyWeakref_GetRef(ref, &mod);
if (PyWeakref_GetRef(ref, &mod) < 0) {
Py_DECREF(ref);
goto error;
}
if (mod == Py_None) {
Py_CLEAR(mod);
}
Expand All @@ -163,7 +166,6 @@ _get_current_state(PyObject **p_mod)
PyInterpreterState *interp = PyInterpreterState_Get();
PyObject *mod = get_current_module(interp);
if (mod == NULL) {
assert(!PyErr_Occurred());
if (PyErr_Occurred()) {
return NULL;
}
Expand Down Expand Up @@ -2130,6 +2132,10 @@ delta_to_microseconds(PyDateTime_Delta *self)

PyObject *current_mod = NULL;
datetime_state *st = GET_CURRENT_STATE(current_mod);
if (st == NULL) {
assert(current_mod == NULL);
return NULL;
}

x1 = PyLong_FromLong(GET_TD_DAYS(self));
if (x1 == NULL)
Expand Down Expand Up @@ -2209,6 +2215,10 @@ microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)

PyObject *current_mod = NULL;
datetime_state *st = GET_CURRENT_STATE(current_mod);
if (st == NULL) {
assert(current_mod == NULL);
return NULL;
}

tuple = checked_divmod(pyus, CONST_US_PER_SECOND(st));
if (tuple == NULL) {
Expand Down Expand Up @@ -2817,6 +2827,10 @@ delta_new_impl(PyTypeObject *type, PyObject *days, PyObject *seconds,

PyObject *current_mod = NULL;
datetime_state *st = GET_CURRENT_STATE(current_mod);
if (st == NULL) {
assert(current_mod == NULL);
return NULL;
}

PyObject *x = NULL; /* running sum of microseconds */
PyObject *y = NULL; /* temp sum of microseconds */
Expand Down Expand Up @@ -3016,6 +3030,11 @@ delta_total_seconds(PyObject *op, PyObject *Py_UNUSED(dummy))

PyObject *current_mod = NULL;
datetime_state *st = GET_CURRENT_STATE(current_mod);
if (st == NULL) {
assert(current_mod == NULL);
Py_DECREF(total_microseconds);
return NULL;
}

total_seconds = PyNumber_TrueDivide(total_microseconds, CONST_US_PER_SECOND(st));

Expand Down Expand Up @@ -3869,6 +3888,10 @@ date_isocalendar(PyObject *self, PyObject *Py_UNUSED(dummy))

PyObject *current_mod = NULL;
datetime_state *st = GET_CURRENT_STATE(current_mod);
if (st == NULL) {
assert(current_mod == NULL);
return NULL;
}

PyObject *v = iso_calendar_date_new_impl(ISOCALENDAR_DATE_TYPE(st),
year, week + 1, day + 1);
Expand Down Expand Up @@ -6802,6 +6825,10 @@ local_timezone(PyDateTime_DateTime *utc_time)

PyObject *current_mod = NULL;
datetime_state *st = GET_CURRENT_STATE(current_mod);
if (st == NULL) {
assert(current_mod == NULL);
return NULL;
}

delta = datetime_subtract((PyObject *)utc_time, CONST_EPOCH(st));
RELEASE_CURRENT_STATE(st, current_mod);
Expand Down Expand Up @@ -7049,6 +7076,10 @@ datetime_timestamp(PyObject *op, PyObject *Py_UNUSED(dummy))
if (HASTZINFO(self) && self->tzinfo != Py_None) {
PyObject *current_mod = NULL;
datetime_state *st = GET_CURRENT_STATE(current_mod);
if (st == NULL) {
assert(current_mod == NULL);
return NULL;
}

PyObject *delta;
delta = datetime_subtract(op, CONST_EPOCH(st));
Expand Down
Loading