99#endif
1010
1111#include "pycore_call.h" // _PyObject_CallNoArgs()
12+ #include "pycore_lock.h" // _PyOnceFlag_CallOnce()
1213#include "pycore_runtime.h" // _Py_ID()
1314
1415#include <ffi.h>
@@ -379,6 +380,27 @@ static CThunkObject* CThunkObject_new(ctypes_state *st, Py_ssize_t nargs)
379380 return p ;
380381}
381382
383+ static _PyOnceFlag closure_alloc_init_once = {0 };
384+
385+ // This is done lazily with a once flag rather than in the module exec function,
386+ // because allocating a closure can have some side effects that affect the whole
387+ // process (gh-135893).
388+ static int
389+ closure_alloc_init (void * Py_UNUSED (arg ))
390+ {
391+ // See https://github.com/python/cpython/issues/128485
392+ // This allocates some memory and then frees it to ensure that libffi's
393+ // dlmalloc allocator initializes itself exactly once, avoiding data races
394+ // between threads that don't share a GIL.
395+ void * codeloc = NULL ;
396+ void * ptr = Py_ffi_closure_alloc (sizeof (void * ), & codeloc );
397+ if (ptr == NULL ) {
398+ return -1 ;
399+ }
400+ Py_ffi_closure_free (ptr );
401+ return 0 ;
402+ }
403+
382404CThunkObject * _ctypes_alloc_callback (ctypes_state * st ,
383405 PyObject * callable ,
384406 PyObject * converters ,
@@ -398,6 +420,12 @@ CThunkObject *_ctypes_alloc_callback(ctypes_state *st,
398420
399421 assert (CThunk_CheckExact (st , (PyObject * )p ));
400422
423+ if (_PyOnceFlag_CallOnce (& closure_alloc_init_once ,
424+ closure_alloc_init , NULL ) < 0 ) {
425+ PyErr_NoMemory ();
426+ goto error ;
427+ }
428+
401429 p -> pcl_write = Py_ffi_closure_alloc (sizeof (ffi_closure ), & p -> pcl_exec );
402430 if (p -> pcl_write == NULL ) {
403431 PyErr_NoMemory ();
0 commit comments