https://github.com/python/cpython/commit/e57a9891990d9191cd19394c3c03db65b5be042b
commit: e57a9891990d9191cd19394c3c03db65b5be042b
branch: 3.15
author: Miss Islington (bot) <[email protected]>
committer: ZeroIntensity <[email protected]>
date: 2026-11-14T04:59:05Z
summary:

[3.15] gh-135893: Lazily initialize the libffi allocator in ctypes (GH-161844) 
(GH-161975)

(cherry picked from commit 9b633f55e1124697372caaec319a3b7583531a74)

Co-authored-by: Peter Bierma <[email protected]>

files:
A Misc/NEWS.d/next/Library/2026-11-11-12-00-00.gh-issue-135893.cTyp3s.rst
M Lib/test/test_ctypes/test_callbacks.py
M Modules/_ctypes/_ctypes.c
M Modules/_ctypes/callbacks.c
M Tools/c-analyzer/cpython/ignored.tsv

diff --git a/Lib/test/test_ctypes/test_callbacks.py 
b/Lib/test/test_ctypes/test_callbacks.py
index d1ac62816eb822..3281537733e818 100644
--- a/Lib/test/test_ctypes/test_callbacks.py
+++ b/Lib/test/test_ctypes/test_callbacks.py
@@ -14,6 +14,7 @@
 from ctypes.util import find_library
 from test import support
 from test.support import import_helper
+from test.support import script_helper
 _ctypes_test = import_helper.import_module("_ctypes_test")
 
 
@@ -343,6 +344,19 @@ def cb():
 
         self.assertEqual(_testfunc_callback_int_to_longlong(cb), -1)
 
+    def test_import_does_not_open_fds(self):
+        # gh-135893: Importing ctypes must not allocate a libffi closure,
+        # which can leave a file descriptor open for the rest of the
+        # process' lifetime.
+        code = """if 1:
+            from test.support import os_helper
+            before = os_helper.fd_count()
+            import ctypes
+            after = os_helper.fd_count()
+            assert before == after
+            """
+        script_helper.assert_python_ok("-c", code)
+
 
 if __name__ == '__main__':
     unittest.main()
diff --git 
a/Misc/NEWS.d/next/Library/2026-11-11-12-00-00.gh-issue-135893.cTyp3s.rst 
b/Misc/NEWS.d/next/Library/2026-11-11-12-00-00.gh-issue-135893.cTyp3s.rst
new file mode 100644
index 00000000000000..bddd3d817ab1cb
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-11-12-00-00.gh-issue-135893.cTyp3s.rst
@@ -0,0 +1,3 @@
+Fix a regression where importing :mod:`ctypes` could leave an extra file
+descriptor open on some Linux systems, or hang in x86-64 macOS applications
+signed with the hardened runtime.
diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c
index 7d486e596f2d92..255d7d5dacb1ed 100644
--- a/Modules/_ctypes/_ctypes.c
+++ b/Modules/_ctypes/_ctypes.c
@@ -6427,18 +6427,6 @@ _ctypes_add_objects(PyObject *mod)
 static int
 _ctypes_mod_exec(PyObject *mod)
 {
-    // See https://github.com/python/cpython/issues/128485
-    // This allocates some memory and then frees it to ensure that the
-    // the dlmalloc allocator initializes itself to avoid data races
-    // in free-threading.
-    void *codeloc = NULL;
-    void *ptr = Py_ffi_closure_alloc(sizeof(void *), &codeloc);
-    if (ptr == NULL) {
-        PyErr_NoMemory();
-        return -1;
-    }
-    Py_ffi_closure_free(ptr);
-
     _ctypes_init_fielddesc();
 
     ctypes_state *st = get_module_state(mod);
diff --git a/Modules/_ctypes/callbacks.c b/Modules/_ctypes/callbacks.c
index e67817e8f6f4d9..2b70907e0b8304 100644
--- a/Modules/_ctypes/callbacks.c
+++ b/Modules/_ctypes/callbacks.c
@@ -9,6 +9,7 @@
 #endif
 
 #include "pycore_call.h"          // _PyObject_CallNoArgs()
+#include "pycore_lock.h"          // _PyOnceFlag_CallOnce()
 #include "pycore_runtime.h"       // _Py_ID()
 
 #include <ffi.h>
@@ -379,6 +380,27 @@ static CThunkObject* CThunkObject_new(ctypes_state *st, 
Py_ssize_t nargs)
     return p;
 }
 
+static _PyOnceFlag closure_alloc_init_once = {0};
+
+// This is done lazily with a once flag rather than in the module exec 
function,
+// because allocating a closure can have some side effects that affect the 
whole
+// process (gh-135893).
+static int
+closure_alloc_init(void *Py_UNUSED(arg))
+{
+    // See https://github.com/python/cpython/issues/128485
+    // This allocates some memory and then frees it to ensure that libffi's
+    // dlmalloc allocator initializes itself exactly once, avoiding data races
+    // between threads that don't share a GIL.
+    void *codeloc = NULL;
+    void *ptr = Py_ffi_closure_alloc(sizeof(void *), &codeloc);
+    if (ptr == NULL) {
+        return -1;
+    }
+    Py_ffi_closure_free(ptr);
+    return 0;
+}
+
 CThunkObject *_ctypes_alloc_callback(ctypes_state *st,
                                     PyObject *callable,
                                     PyObject *converters,
@@ -398,6 +420,12 @@ CThunkObject *_ctypes_alloc_callback(ctypes_state *st,
 
     assert(CThunk_CheckExact(st, (PyObject *)p));
 
+    if (_PyOnceFlag_CallOnce(&closure_alloc_init_once,
+                             closure_alloc_init, NULL) < 0) {
+        PyErr_NoMemory();
+        goto error;
+    }
+
     p->pcl_write = Py_ffi_closure_alloc(sizeof(ffi_closure), &p->pcl_exec);
     if (p->pcl_write == NULL) {
         PyErr_NoMemory();
diff --git a/Tools/c-analyzer/cpython/ignored.tsv 
b/Tools/c-analyzer/cpython/ignored.tsv
index 79edfc53c21a3b..63e41c0b40c59d 100644
--- a/Tools/c-analyzer/cpython/ignored.tsv
+++ b/Tools/c-analyzer/cpython/ignored.tsv
@@ -26,6 +26,7 @@ Modules/posixmodule.c os_pipe_impl    pipe2_works_atomic      
-
 ## guards around resource init
 Python/thread_pthread.h        PyThread__init_thread   lib_initialized -
 Modules/_struct.c      -       endian_tables_init_once -
+Modules/_ctypes/callbacks.c    -       closure_alloc_init_once -
 
 ##-----------------------
 ## other values (not Python-specific)

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to