Debian Codegraph @

src/cffi/_embedding.h

raw
1
2 /***** Support code for embedding *****/
3
4 #ifdef __cplusplus
5 extern "C" {
6 #endif
7
8
9 #if defined(_WIN32)
10 # define CFFI_DLLEXPORT __declspec(dllexport)
11 #elif defined(__GNUC__)
12 # define CFFI_DLLEXPORT __attribute__((visibility("default")))
13 #else
14 # define CFFI_DLLEXPORT /* nothing */
15 #endif
16
17
18 /* There are two global variables of type _cffi_call_python_fnptr:
19
20 * _cffi_call_python, which we declare just below, is the one called
21 by ``extern "Python"`` implementations.
22
23 * _cffi_call_python_org, which on CPython is actually part of the
24 _cffi_exports[] array, is the function pointer copied from
25 _cffi_backend. If _cffi_start_python() fails, then this is set
26 to NULL; otherwise, it should never be NULL.
27
28 After initialization is complete, both are equal. However, the
29 first one remains equal to &_cffi_start_and_call_python until the
30 very end of initialization, when we are (or should be) sure that
31 concurrent threads also see a completely initialized world, and
32 only then is it changed.
33 */
34 #undef _cffi_call_python
35 typedef void (*_cffi_call_python_fnptr)(struct _cffi_externpy_s *, char *);
36 static void _cffi_start_and_call_python(struct _cffi_externpy_s *, char *);
37 static _cffi_call_python_fnptr _cffi_call_python = &_cffi_start_and_call_python;
38
39
40 #ifndef _MSC_VER
41 /* --- Assuming a GCC not infinitely old --- */
42 # define cffi_compare_and_swap(l,o,n) __sync_bool_compare_and_swap(l,o,n)
43 # define cffi_write_barrier() __sync_synchronize()
44 # if !defined(__amd64__) && !defined(__x86_64__) && \
45 !defined(__i386__) && !defined(__i386)
46 # define cffi_read_barrier() __sync_synchronize()
47 # else
48 # define cffi_read_barrier() (void)0
49 # endif
50 #else
51 /* --- Windows threads version --- */
52 # include <Windows.h>
53 # define cffi_compare_and_swap(l,o,n) \
54 (InterlockedCompareExchangePointer(l,n,o) == (o))
55 # define cffi_write_barrier() InterlockedCompareExchange(&_cffi_dummy,0,0)
56 # define cffi_read_barrier() (void)0
57 static volatile LONG _cffi_dummy;
58 #endif
59
60 #ifdef WITH_THREAD
61 # ifndef _MSC_VER
62 # include <pthread.h>
63 static pthread_mutex_t _cffi_embed_startup_lock;
64 # else
65 static CRITICAL_SECTION _cffi_embed_startup_lock;
66 # endif
67 static char _cffi_embed_startup_lock_ready = 0;
68 #endif
69
70 static void _cffi_acquire_reentrant_mutex(void)
71 {
72 static void *volatile lock = NULL;
73
74 while (!cffi_compare_and_swap(&lock, NULL, (void *)1)) {
75 /* should ideally do a spin loop instruction here, but
76 hard to do it portably and doesn't really matter I
77 think: pthread_mutex_init() should be very fast, and
78 this is only run at start-up anyway. */
79 }
80
81 #ifdef WITH_THREAD
82 if (!_cffi_embed_startup_lock_ready) {
83 # ifndef _MSC_VER
84 pthread_mutexattr_t attr;
85 pthread_mutexattr_init(&attr);
86 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
87 pthread_mutex_init(&_cffi_embed_startup_lock, &attr);
88 # else
89 InitializeCriticalSection(&_cffi_embed_startup_lock);
90 # endif
91 _cffi_embed_startup_lock_ready = 1;
92 }
93 #endif
94
95 while (!cffi_compare_and_swap(&lock, (void *)1, NULL))
96 ;
97
98 #ifndef _MSC_VER
99 pthread_mutex_lock(&_cffi_embed_startup_lock);
100 #else
101 EnterCriticalSection(&_cffi_embed_startup_lock);
102 #endif
103 }
104
105 static void _cffi_release_reentrant_mutex(void)
106 {
107 #ifndef _MSC_VER
108 pthread_mutex_unlock(&_cffi_embed_startup_lock);
109 #else
110 LeaveCriticalSection(&_cffi_embed_startup_lock);
111 #endif
112 }
113
114
115 /********** CPython-specific section **********/
116 #ifndef PYPY_VERSION
117
118 #include "_cffi_errors.h"
119
120
121 #define _cffi_call_python_org _cffi_exports[_CFFI_CPIDX]
122
123 PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(void); /* forward */
124
125 static void _cffi_py_initialize(void)
126 {
127 /* XXX use initsigs=0, which "skips initialization registration of
128 signal handlers, which might be useful when Python is
129 embedded" according to the Python docs. But review and think
130 if it should be a user-controllable setting.
131
132 XXX we should also give a way to write errors to a buffer
133 instead of to stderr.
134
135 XXX if importing 'site' fails, CPython (any version) calls
136 exit(). Should we try to work around this behavior here?
137 */
138 Py_InitializeEx(0);
139 }
140
141 static int _cffi_initialize_python(void)
142 {
143 /* This initializes Python, imports _cffi_backend, and then the
144 present .dll/.so is set up as a CPython C extension module.
145 */
146 int result;
147 PyGILState_STATE state;
148 PyObject *pycode=NULL, *global_dict=NULL, *x;
149 PyObject *builtins;
150
151 state = PyGILState_Ensure();
152
153 /* Call the initxxx() function from the present module. It will
154 create and initialize us as a CPython extension module, instead
155 of letting the startup Python code do it---it might reimport
156 the same .dll/.so and get maybe confused on some platforms.
157 It might also have troubles locating the .dll/.so again for all
158 I know.
159 */
160 (void)_CFFI_PYTHON_STARTUP_FUNC();
161 if (PyErr_Occurred())
162 goto error;
163
164 /* Now run the Python code provided to ffi.embedding_init_code().
165 */
166 pycode = Py_CompileString(_CFFI_PYTHON_STARTUP_CODE,
167 "<init code for '" _CFFI_MODULE_NAME "'>",
168 Py_file_input);
169 if (pycode == NULL)
170 goto error;
171 global_dict = PyDict_New();
172 if (global_dict == NULL)
173 goto error;
174 builtins = PyEval_GetBuiltins();
175 if (builtins == NULL)
176 goto error;
177 if (PyDict_SetItemString(global_dict, "__builtins__", builtins) < 0)
178 goto error;
179 x = PyEval_EvalCode(
180 pycode, global_dict, global_dict);
181 if (x == NULL)
182 goto error;
183 Py_DECREF(x);
184
185 /* Done! Now if we've been called from
186 _cffi_start_and_call_python() in an ``extern "Python"``, we can
187 only hope that the Python code did correctly set up the
188 corresponding @ffi.def_extern() function. Otherwise, the
189 general logic of ``extern "Python"`` functions (inside the
190 _cffi_backend module) will find that the reference is still
191 missing and print an error.
192 */
193 result = 0;
194 done:
195 Py_XDECREF(pycode);
196 Py_XDECREF(global_dict);
197 PyGILState_Release(state);
198 return result;
199
200 error:;
201 {
202 /* Print as much information as potentially useful.
203 Debugging load-time failures with embedding is not fun
204 */
205 PyObject *ecap;
206 PyObject *exception, *v, *tb, *f, *modules, *mod;
207 PyErr_Fetch(&exception, &v, &tb);
208 ecap = _cffi_start_error_capture();
209 f = PySys_GetObject((char *)"stderr");
210 if (f != NULL && f != Py_None) {
211 PyFile_WriteString(
212 "Failed to initialize the Python-CFFI embedding logic:\n\n", f);
213 }
214
215 if (exception != NULL) {
216 PyErr_NormalizeException(&exception, &v, &tb);
217 PyErr_Display(exception, v, tb);
218 }
219 Py_XDECREF(exception);
220 Py_XDECREF(v);
221 Py_XDECREF(tb);
222
223 if (f != NULL && f != Py_None) {
224 PyFile_WriteString("\nFrom: " _CFFI_MODULE_NAME
225 "\ncompiled with cffi version: 2.1.1"
226 "\n_cffi_backend module: ", f);
227 modules = PyImport_GetModuleDict();
228 mod = PyDict_GetItemString(modules, "_cffi_backend");
229 if (mod == NULL) {
230 PyFile_WriteString("not loaded", f);
231 }
232 else {
233 v = PyObject_GetAttrString(mod, "__file__");
234 PyFile_WriteObject(v, f, 0);
235 Py_XDECREF(v);
236 }
237 PyFile_WriteString("\nsys.path: ", f);
238 PyFile_WriteObject(PySys_GetObject((char *)"path"), f, 0);
239 PyFile_WriteString("\n\n", f);
240 }
241 _cffi_stop_error_capture(ecap);
242 }
243 result = -1;
244 goto done;
245 }
246
247 static int _cffi_carefully_make_gil(void)
248 {
249 /* This does the basic initialization of Python. It can be called
250 completely concurrently from unrelated threads. It assumes
251 that we don't hold the GIL before (if it exists), and we don't
252 hold it afterwards.
253
254 (What it really does used to be completely different in Python 2
255 and Python 3, with the Python 2 solution avoiding the spin-lock
256 around the Py_InitializeEx() call. However, after recent changes
257 to CPython 2.7 (issue #358) it no longer works. So we use the
258 Python 3 solution everywhere.)
259
260 This initializes Python by calling Py_InitializeEx().
261 Important: this must not be called concurrently at all.
262 So we use a global variable as a simple spin lock. This global
263 variable must be from 'libpythonX.Y.so', not from this
264 cffi-based extension module, because it must be shared from
265 different cffi-based extension modules.
266
267 In Python < 3.8, we choose
268 _PyParser_TokenNames[0] as a completely arbitrary pointer value
269 that is never written to. The default is to point to the
270 string "ENDMARKER". We change it temporarily to point to the
271 next character in that string. (Yes, I know it's REALLY
272 obscure.)
273
274 In Python >= 3.8, this string array is no longer writable, so
275 instead we pick PyCapsuleType.tp_version_tag. We can't change
276 Python < 3.8 because someone might use a mixture of cffi
277 embedded modules, some of which were compiled before this file
278 changed.
279
280 In Python >= 3.12, this stopped working because that particular
281 tp_version_tag gets modified during interpreter startup. It's
282 arguably a bad idea before 3.12 too, but again we can't change
283 that because someone might use a mixture of cffi embedded
284 modules, and no-one reported a bug so far. In Python >= 3.12
285 we go instead for PyCapsuleType.tp_as_buffer, which is supposed
286 to always be NULL. We write to it temporarily a pointer to
287 a struct full of NULLs, which is semantically the same.
288 */
289
290 #ifdef WITH_THREAD
291 # if PY_VERSION_HEX < 0x030C0000
292 int volatile *lock = (int volatile *)&PyCapsule_Type.tp_version_tag;
293 int old_value, locked_value = -42;
294 assert(!(PyCapsule_Type.tp_flags & Py_TPFLAGS_HAVE_VERSION_TAG));
295 # else
296 static struct ebp_s { PyBufferProcs buf; int mark; } empty_buffer_procs;
297 empty_buffer_procs.mark = -42;
298 PyBufferProcs *volatile *lock = (PyBufferProcs *volatile *)
299 &PyCapsule_Type.tp_as_buffer;
300 PyBufferProcs *old_value, *locked_value = &empty_buffer_procs.buf;
301 # endif
302
303 while (1) { /* spin loop */
304 old_value = *lock;
305 if (old_value == 0) {
306 if (cffi_compare_and_swap(lock, old_value, locked_value))
307 break;
308 }
309 else {
310 # if PY_VERSION_HEX < 0x030C0000
311 assert(old_value == locked_value);
312 # else
313 /* The pointer should point to a possibly different
314 empty_buffer_procs from another C extension module */
315 assert(((struct ebp_s *)old_value)->mark == -42);
316 # endif
317 /* should ideally do a spin loop instruction here, but
318 hard to do it portably and doesn't really matter I
319 think: PyEval_InitThreads() should be very fast, and
320 this is only run at start-up anyway. */
321 }
322 }
323 #endif
324
325 /* call Py_InitializeEx() */
326 if (!Py_IsInitialized()) {
327 _cffi_py_initialize();
328 PyEval_SaveThread(); /* release the GIL */
329 /* the returned tstate must be the one that has been stored into the
330 autoTLSkey by _PyGILState_Init() called from Py_Initialize(). */
331 }
332 else {
333 }
334
335 #ifdef WITH_THREAD
336 /* release the lock */
337 while (!cffi_compare_and_swap(lock, locked_value, old_value))
338 ;
339 #endif
340
341 return 0;
342 }
343
344 /********** end CPython-specific section **********/
345
346
347 #else
348
349
350 /********** PyPy-specific section **********/
351
352 PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(const void *[]); /* forward */
353
354 static struct _cffi_pypy_init_s {
355 const char *name;
356 void *func; /* function pointer */
357 const char *code;
358 } _cffi_pypy_init = {
359 _CFFI_MODULE_NAME,
360 _CFFI_PYTHON_STARTUP_FUNC,
361 _CFFI_PYTHON_STARTUP_CODE,
362 };
363
364 extern int pypy_carefully_make_gil(const char *);
365 extern int pypy_init_embedded_cffi_module(int, struct _cffi_pypy_init_s *);
366
367 static int _cffi_carefully_make_gil(void)
368 {
369 return pypy_carefully_make_gil(_CFFI_MODULE_NAME);
370 }
371
372 static int _cffi_initialize_python(void)
373 {
374 return pypy_init_embedded_cffi_module(0xB011, &_cffi_pypy_init);
375 }
376
377 /********** end PyPy-specific section **********/
378
379
380 #endif
381
382
383 #ifdef __GNUC__
384 __attribute__((noinline))
385 #endif
386 static _cffi_call_python_fnptr _cffi_start_python(void)
387 {
388 /* Delicate logic to initialize Python. This function can be
389 called multiple times concurrently, e.g. when the process calls
390 its first ``extern "Python"`` functions in multiple threads at
391 once. It can also be called recursively, in which case we must
392 ignore it. We also have to consider what occurs if several
393 different cffi-based extensions reach this code in parallel
394 threads---it is a different copy of the code, then, and we
395 can't have any shared global variable unless it comes from
396 'libpythonX.Y.so'.
397
398 Idea:
399
400 * _cffi_carefully_make_gil(): "carefully" call
401 PyEval_InitThreads() (possibly with Py_InitializeEx() first).
402
403 * then we use a (local) custom lock to make sure that a call to this
404 cffi-based extension will wait if another call to the *same*
405 extension is running the initialization in another thread.
406 It is reentrant, so that a recursive call will not block, but
407 only one from a different thread.
408
409 * then we grab the GIL and (Python 2) we call Py_InitializeEx().
410 At this point, concurrent calls to Py_InitializeEx() are not
411 possible: we have the GIL.
412
413 * do the rest of the specific initialization, which may
414 temporarily release the GIL but not the custom lock.
415 Only release the custom lock when we are done.
416 */
417 static char called = 0;
418
419 if (_cffi_carefully_make_gil() != 0)
420 return NULL;
421
422 _cffi_acquire_reentrant_mutex();
423
424 /* Here the GIL exists, but we don't have it. We're only protected
425 from concurrency by the reentrant mutex. */
426
427 /* This file only initializes the embedded module once, the first
428 time this is called, even if there are subinterpreters. */
429 if (!called) {
430 called = 1; /* invoke _cffi_initialize_python() only once,
431 but don't set '_cffi_call_python' right now,
432 otherwise concurrent threads won't call
433 this function at all (we need them to wait) */
434 if (_cffi_initialize_python() == 0) {
435 /* now initialization is finished. Switch to the fast-path. */
436
437 /* We would like nobody to see the new value of
438 '_cffi_call_python' without also seeing the rest of the
439 data initialized. However, this is not possible. But
440 the new value of '_cffi_call_python' is the function
441 'cffi_call_python()' from _cffi_backend. So: */
442 cffi_write_barrier();
443 /* ^^^ we put a write barrier here, and a corresponding
444 read barrier at the start of cffi_call_python(). This
445 ensures that after that read barrier, we see everything
446 done here before the write barrier.
447 */
448
449 assert(_cffi_call_python_org != NULL);
450 _cffi_call_python = (_cffi_call_python_fnptr)_cffi_call_python_org;
451 }
452 else {
453 /* initialization failed. Reset this to NULL, even if it was
454 already set to some other value. Future calls to
455 _cffi_start_python() are still forced to occur, and will
456 always return NULL from now on. */
457 _cffi_call_python_org = NULL;
458 }
459 }
460
461 _cffi_release_reentrant_mutex();
462
463 return (_cffi_call_python_fnptr)_cffi_call_python_org;
464 }
465
466 static
467 void _cffi_start_and_call_python(struct _cffi_externpy_s *externpy, char *args)
468 {
469 _cffi_call_python_fnptr fnptr;
470 int current_err = errno;
471 #ifdef _MSC_VER
472 int current_lasterr = GetLastError();
473 #endif
474 fnptr = _cffi_start_python();
475 if (fnptr == NULL) {
476 fprintf(stderr, "function %s() called, but initialization code "
477 "failed. Returning 0.\n", externpy->name);
478 memset(args, 0, externpy->size_of_result);
479 }
480 #ifdef _MSC_VER
481 SetLastError(current_lasterr);
482 #endif
483 errno = current_err;
484
485 if (fnptr != NULL)
486 fnptr(externpy, args);
487 }
488
489
490 /* The cffi_start_python() function makes sure Python is initialized
491 and our cffi module is set up. It can be called manually from the
492 user C code. The same effect is obtained automatically from any
493 dll-exported ``extern "Python"`` function. This function returns
494 -1 if initialization failed, 0 if all is OK. */
495 _CFFI_UNUSED_FN
496 static int cffi_start_python(void)
497 {
498 if (_cffi_call_python == &_cffi_start_and_call_python) {
499 if (_cffi_start_python() == NULL)
500 return -1;
501 }
502 cffi_read_barrier();
503 return 0;
504 }
505
506 #undef cffi_compare_and_swap
507 #undef cffi_write_barrier
508 #undef cffi_read_barrier
509
510 #ifdef __cplusplus
511 }
512 #endif