Skip to content

Commit ada9b73

Browse files
committedApr 23, 2023
_struct: fix race condition in cache_struct_converter
1 parent 22eca6e commit ada9b73

File tree

1 file changed

+9
-9
lines changed

1 file changed

+9
-9
lines changed
 

‎Modules/_struct.c

+9-9
Original file line numberDiff line numberDiff line change
@@ -2239,15 +2239,9 @@ cache_struct_converter(PyObject *module, PyObject *fmt, PyStructObject **ptr)
22392239
return 1;
22402240
}
22412241

2242-
if (state->cache == NULL) {
2243-
state->cache = PyDict_New();
2244-
if (state->cache == NULL)
2245-
return 0;
2246-
}
2247-
2248-
s_object = PyDict_GetItemWithError(state->cache, fmt);
2242+
s_object = PyDict_FetchItemWithError(state->cache, fmt);
22492243
if (s_object != NULL) {
2250-
*ptr = (PyStructObject *)Py_NewRef(s_object);
2244+
*ptr = (PyStructObject *)s_object;
22512245
return Py_CLEANUP_SUPPORTED;
22522246
}
22532247
else if (PyErr_Occurred()) {
@@ -2277,7 +2271,7 @@ static PyObject *
22772271
_clearcache_impl(PyObject *module)
22782272
/*[clinic end generated code: output=ce4fb8a7bf7cb523 input=463eaae04bab3211]*/
22792273
{
2280-
Py_CLEAR(get_struct_state(module)->cache);
2274+
PyDict_Clear(get_struct_state(module)->cache);
22812275
Py_RETURN_NONE;
22822276
}
22832277

@@ -2506,6 +2500,12 @@ _structmodule_exec(PyObject *m)
25062500
if (state->PyStructType == NULL) {
25072501
return -1;
25082502
}
2503+
2504+
state->cache = PyDict_New();
2505+
if (state->cache == NULL) {
2506+
return -1;
2507+
}
2508+
25092509
if (PyModule_AddType(m, (PyTypeObject *)state->PyStructType) < 0) {
25102510
return -1;
25112511
}

0 commit comments

Comments
 (0)
Please sign in to comment.