Skip to content

Commit f1967e7

Browse files
gh-127945: fix thread safety of ctypes state (#131710)
This fixes thread safety of `array_cache` and `swapped_suffix` by initializing them in module exec to make it thread safety.
1 parent 96ef4c5 commit f1967e7

File tree

1 file changed

+16
-18
lines changed

1 file changed

+16
-18
lines changed

Modules/_ctypes/_ctypes.c

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2148,18 +2148,7 @@ static PyObject *CreateSwappedType(ctypes_state *st, PyTypeObject *type,
21482148
if (!swapped_args)
21492149
return NULL;
21502150

2151-
if (st->swapped_suffix == NULL) {
2152-
#ifdef WORDS_BIGENDIAN
2153-
st->swapped_suffix = PyUnicode_InternFromString("_le");
2154-
#else
2155-
st->swapped_suffix = PyUnicode_InternFromString("_be");
2156-
#endif
2157-
}
2158-
if (st->swapped_suffix == NULL) {
2159-
Py_DECREF(swapped_args);
2160-
return NULL;
2161-
}
2162-
2151+
assert(st->swapped_suffix != NULL);
21632152
newname = PyUnicode_Concat(name, st->swapped_suffix);
21642153
if (newname == NULL) {
21652154
Py_DECREF(swapped_args);
@@ -5113,12 +5102,7 @@ PyCArrayType_from_ctype(ctypes_state *st, PyObject *itemtype, Py_ssize_t length)
51135102
char name[256];
51145103
PyObject *len;
51155104

5116-
if (st->array_cache == NULL) {
5117-
st->array_cache = PyDict_New();
5118-
if (st->array_cache == NULL) {
5119-
return NULL;
5120-
}
5121-
}
5105+
assert(st->array_cache != NULL);
51225106
len = PyLong_FromSsize_t(length);
51235107
if (len == NULL)
51245108
return NULL;
@@ -6099,6 +6083,20 @@ _ctypes_mod_exec(PyObject *mod)
60996083
return -1;
61006084
}
61016085

6086+
st->array_cache = PyDict_New();
6087+
if (st->array_cache == NULL) {
6088+
return -1;
6089+
}
6090+
6091+
#ifdef WORDS_BIGENDIAN
6092+
st->swapped_suffix = PyUnicode_InternFromString("_le");
6093+
#else
6094+
st->swapped_suffix = PyUnicode_InternFromString("_be");
6095+
#endif
6096+
if (st->swapped_suffix == NULL) {
6097+
return -1;
6098+
}
6099+
61026100
if (_ctypes_add_types(mod) < 0) {
61036101
return -1;
61046102
}

0 commit comments

Comments
 (0)