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#ifdef MS_WIN32
@@ -388,6 +389,27 @@ static CThunkObject* CThunkObject_new(ctypes_state *st, Py_ssize_t nargs)
388389 return p ;
389390}
390391
392+ static _PyOnceFlag closure_alloc_init_once = {0 };
393+
394+ // This is done lazily with a once flag rather than in the module exec function,
395+ // because allocating a closure can have some side effects that affect the whole
396+ // process (gh-135893).
397+ static int
398+ closure_alloc_init (void * Py_UNUSED (arg ))
399+ {
400+ // See https://github.com/python/cpython/issues/128485
401+ // This allocates some memory and then frees it to ensure that libffi's
402+ // dlmalloc allocator initializes itself exactly once, avoiding data races
403+ // between threads that don't share a GIL.
404+ void * codeloc = NULL ;
405+ void * ptr = Py_ffi_closure_alloc (sizeof (void * ), & codeloc );
406+ if (ptr == NULL ) {
407+ return -1 ;
408+ }
409+ Py_ffi_closure_free (ptr );
410+ return 0 ;
411+ }
412+
391413CThunkObject * _ctypes_alloc_callback (ctypes_state * st ,
392414 PyObject * callable ,
393415 PyObject * converters ,
@@ -407,6 +429,12 @@ CThunkObject *_ctypes_alloc_callback(ctypes_state *st,
407429
408430 assert (CThunk_CheckExact (st , (PyObject * )p ));
409431
432+ if (_PyOnceFlag_CallOnce (& closure_alloc_init_once ,
433+ closure_alloc_init , NULL ) < 0 ) {
434+ PyErr_NoMemory ();
435+ goto error ;
436+ }
437+
410438 p -> pcl_write = Py_ffi_closure_alloc (sizeof (ffi_closure ), & p -> pcl_exec );
411439 if (p -> pcl_write == NULL ) {
412440 PyErr_NoMemory ();
0 commit comments