https://github.com/python/cpython/commit/f1967e72498209e42f7cf5eeff0cd84d1ec10d18
commit: f1967e72498209e42f7cf5eeff0cd84d1ec10d18
branch: main
author: Kumar Aditya <kumaradi...@python.org>
committer: kumaraditya303 <kumaradi...@python.org>
date: 2025-03-25T17:03:05+05:30
summary:

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.

files:
M Modules/_ctypes/_ctypes.c

diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c
index 6d817bdaecfa4e..d3e717757b0645 100644
--- a/Modules/_ctypes/_ctypes.c
+++ b/Modules/_ctypes/_ctypes.c
@@ -2148,18 +2148,7 @@ static PyObject *CreateSwappedType(ctypes_state *st, 
PyTypeObject *type,
     if (!swapped_args)
         return NULL;
 
-    if (st->swapped_suffix == NULL) {
-#ifdef WORDS_BIGENDIAN
-        st->swapped_suffix = PyUnicode_InternFromString("_le");
-#else
-        st->swapped_suffix = PyUnicode_InternFromString("_be");
-#endif
-    }
-    if (st->swapped_suffix == NULL) {
-        Py_DECREF(swapped_args);
-        return NULL;
-    }
-
+    assert(st->swapped_suffix != NULL);
     newname = PyUnicode_Concat(name, st->swapped_suffix);
     if (newname == NULL) {
         Py_DECREF(swapped_args);
@@ -5113,12 +5102,7 @@ PyCArrayType_from_ctype(ctypes_state *st, PyObject 
*itemtype, Py_ssize_t length)
     char name[256];
     PyObject *len;
 
-    if (st->array_cache == NULL) {
-        st->array_cache = PyDict_New();
-        if (st->array_cache == NULL) {
-            return NULL;
-        }
-    }
+    assert(st->array_cache != NULL);
     len = PyLong_FromSsize_t(length);
     if (len == NULL)
         return NULL;
@@ -6099,6 +6083,20 @@ _ctypes_mod_exec(PyObject *mod)
         return -1;
     }
 
+    st->array_cache = PyDict_New();
+    if (st->array_cache == NULL) {
+        return -1;
+    }
+
+#ifdef WORDS_BIGENDIAN
+        st->swapped_suffix = PyUnicode_InternFromString("_le");
+#else
+        st->swapped_suffix = PyUnicode_InternFromString("_be");
+#endif
+    if (st->swapped_suffix == NULL) {
+        return -1;
+    }
+
     if (_ctypes_add_types(mod) < 0) {
         return -1;
     }

_______________________________________________
Python-checkins mailing list -- python-checkins@python.org
To unsubscribe send an email to python-checkins-le...@python.org
https://mail.python.org/mailman3/lists/python-checkins.python.org/
Member address: arch...@mail-archive.com

Reply via email to