Skip to content

Commit 05acc56

Browse files
Make sure the module exists in static type methods.
1 parent c519e3c commit 05acc56

File tree

1 file changed

+38
-9
lines changed

1 file changed

+38
-9
lines changed

Modules/_datetimemodule.c

Lines changed: 38 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -123,15 +123,44 @@ get_current_module(PyInterpreterState *interp)
123123
return mod;
124124
}
125125

126-
#define GET_CURRENT_STATE(ST_VAR) \
127-
NULL; \
128-
PyObject *current_mod = NULL; \
129-
do { \
130-
PyInterpreterState *interp = PyInterpreterState_Get(); \
131-
current_mod = get_current_module(interp); \
132-
assert(current_mod != NULL); \
133-
ST_VAR = get_module_state(current_mod); \
134-
} while (0)
126+
static PyModuleDef datetimemodule;
127+
128+
static datetime_state *
129+
_get_current_state(PyObject **p_mod)
130+
{
131+
PyInterpreterState *interp = PyInterpreterState_Get();
132+
PyObject *mod = get_current_module(interp);
133+
if (mod == NULL) {
134+
assert(!PyErr_Occurred());
135+
if (PyErr_Occurred()) {
136+
return NULL;
137+
}
138+
/* The static types can outlive the module, so we must
139+
* temporarily load the module if one of the static types'
140+
* methods needs module state. We can cut some corners
141+
* since the module was necessarily already imported successfully
142+
* and the module will only be around temporarily. We don't even
143+
* need a spec. Normally the module would have been found
144+
* and the temporary module would never happen. */
145+
mod = PyModule_New("_datetime");
146+
if (mod == NULL) {
147+
return NULL;
148+
}
149+
((PyModuleObject*)mod)->md_def = &datetimemodule;
150+
if (PyModule_ExecDef(mod, &datetimemodule) < 0) {
151+
Py_DECREF(mod);
152+
return NULL;
153+
}
154+
}
155+
datetime_state *st = get_module_state(mod);
156+
*p_mod = mod;
157+
return st;
158+
}
159+
160+
#define GET_CURRENT_STATE(ST_VAR) \
161+
NULL; \
162+
PyObject *current_mod = NULL; \
163+
ST_VAR = _get_current_state(&current_mod);
135164
#define RELEASE_CURRENT_STATE(ST_VAR) \
136165
Py_DECREF(current_mod)
137166

0 commit comments

Comments
 (0)