Debian Codegraph @

lib_pypy/cffi/_embedding.h

raw symbols SCIP
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 #if PY_MAJOR_VERSION < 3
181 (PyCodeObject *)
182 #endif
183 pycode, global_dict, global_dict);
184 if (x == NULL)
185 goto error;
186 Py_DECREF(x);
187
188 /* Done! Now if we've been called from
189 _cffi_start_and_call_python() in an ``extern "Python"``, we can
190 only hope that the Python code did correctly set up the
191 corresponding @ffi.def_extern() function. Otherwise, the
192 general logic of ``extern "Python"`` functions (inside the
193 _cffi_backend module) will find that the reference is still
194 missing and print an error.
195 */
196 result = 0;
197 done:
198 Py_XDECREF(pycode);
199 Py_XDECREF(global_dict);
200 PyGILState_Release(state);
201 return result;
202
203 error:;
204 {
205 /* Print as much information as potentially useful.
206 Debugging load-time failures with embedding is not fun
207 */
208 PyObject *ecap;
209 PyObject *exception, *v, *tb, *f, *modules, *mod;
210 PyErr_Fetch(&exception, &v, &tb);
211 ecap = _cffi_start_error_capture();
212 f = PySys_GetObject((char *)"stderr");
213 if (f != NULL && f != Py_None) {
214 PyFile_WriteString(
215 "Failed to initialize the Python-CFFI embedding logic:\n\n", f);
216 }
217
218 if (exception != NULL) {
219 PyErr_NormalizeException(&exception, &v, &tb);
220 PyErr_Display(exception, v, tb);
221 }
222 Py_XDECREF(exception);
223 Py_XDECREF(v);
224 Py_XDECREF(tb);
225
226 if (f != NULL && f != Py_None) {
227 PyFile_WriteString("\nFrom: " _CFFI_MODULE_NAME
228 "\ncompiled with cffi version: 1.18.0.dev0"
229 "\n_cffi_backend module: ", f);
230 modules = PyImport_GetModuleDict();
231 mod = PyDict_GetItemString(modules, "_cffi_backend");
232 if (mod == NULL) {
233 PyFile_WriteString("not loaded", f);
234 }
235 else {
236 v = PyObject_GetAttrString(mod, "__file__");
237 PyFile_WriteObject(v, f, 0);
238 Py_XDECREF(v);
239 }
240 PyFile_WriteString("\nsys.path: ", f);
241 PyFile_WriteObject(PySys_GetObject((char *)"path"), f, 0);
242 PyFile_WriteString("\n\n", f);
243 }
244 _cffi_stop_error_capture(ecap);
245 }
246 result = -1;
247 goto done;
248 }
249
250 #if PY_VERSION_HEX < 0x03080000
251 PyAPI_DATA(char *) _PyParser_TokenNames[]; /* from CPython */
252 #endif
253
254 static int _cffi_carefully_make_gil(void)
255 {
256 /* This does the basic initialization of Python. It can be called
257 completely concurrently from unrelated threads. It assumes
258 that we don't hold the GIL before (if it exists), and we don't
259 hold it afterwards.
260
261 (What it really does used to be completely different in Python 2
262 and Python 3, with the Python 2 solution avoiding the spin-lock
263 around the Py_InitializeEx() call. However, after recent changes
264 to CPython 2.7 (issue #358) it no longer works. So we use the
265 Python 3 solution everywhere.)
266
267 This initializes Python by calling Py_InitializeEx().
268 Important: this must not be called concurrently at all.
269 So we use a global variable as a simple spin lock. This global
270 variable must be from 'libpythonX.Y.so', not from this
271 cffi-based extension module, because it must be shared from
272 different cffi-based extension modules.
273
274 In Python < 3.8, we choose
275 _PyParser_TokenNames[0] as a completely arbitrary pointer value
276 that is never written to. The default is to point to the
277 string "ENDMARKER". We change it temporarily to point to the
278 next character in that string. (Yes, I know it's REALLY
279 obscure.)
280
281 In Python >= 3.8, this string array is no longer writable, so
282 instead we pick PyCapsuleType.tp_version_tag. We can't change
283 Python < 3.8 because someone might use a mixture of cffi
284 embedded modules, some of which were compiled before this file
285 changed.
286
287 In Python >= 3.12, this stopped working because that particular
288 tp_version_tag gets modified during interpreter startup. It's
289 arguably a bad idea before 3.12 too, but again we can't change
290 that because someone might use a mixture of cffi embedded
291 modules, and no-one reported a bug so far. In Python >= 3.12
292 we go instead for PyCapsuleType.tp_as_buffer, which is supposed
293 to always be NULL. We write to it temporarily a pointer to
294 a struct full of NULLs, which is semantically the same.
295 */
296
297 #ifdef WITH_THREAD
298 # if PY_VERSION_HEX < 0x03080000
299 char *volatile *lock = (char *volatile *)_PyParser_TokenNames;
300 char *old_value, *locked_value;
301
302 while (1) { /* spin loop */
303 old_value = *lock;
304 locked_value = old_value + 1;
305 if (old_value[0] == 'E') {
306 assert(old_value[1] == 'N');
307 if (cffi_compare_and_swap(lock, old_value, locked_value))
308 break;
309 }
310 else {
311 assert(old_value[0] == 'N');
312 /* should ideally do a spin loop instruction here, but
313 hard to do it portably and doesn't really matter I
314 think: PyEval_InitThreads() should be very fast, and
315 this is only run at start-up anyway. */
316 }
317 }
318 # else
319 # if PY_VERSION_HEX < 0x030C0000
320 int volatile *lock = (int volatile *)&PyCapsule_Type.tp_version_tag;
321 int old_value, locked_value = -42;
322 assert(!(PyCapsule_Type.tp_flags & Py_TPFLAGS_HAVE_VERSION_TAG));
323 # else
324 static struct ebp_s { PyBufferProcs buf; int mark; } empty_buffer_procs;
325 empty_buffer_procs.mark = -42;
326 PyBufferProcs *volatile *lock = (PyBufferProcs *volatile *)
327 &PyCapsule_Type.tp_as_buffer;
328 PyBufferProcs *old_value, *locked_value = &empty_buffer_procs.buf;
329 # endif
330
331 while (1) { /* spin loop */
332 old_value = *lock;
333 if (old_value == 0) {
334 if (cffi_compare_and_swap(lock, old_value, locked_value))
335 break;
336 }
337 else {
338 # if PY_VERSION_HEX < 0x030C0000
339 assert(old_value == locked_value);
340 # else
341 /* The pointer should point to a possibly different
342 empty_buffer_procs from another C extension module */
343 assert(((struct ebp_s *)old_value)->mark == -42);
344 # endif
345 /* should ideally do a spin loop instruction here, but
346 hard to do it portably and doesn't really matter I
347 think: PyEval_InitThreads() should be very fast, and
348 this is only run at start-up anyway. */
349 }
350 }
351 # endif
352 #endif
353
354 /* call Py_InitializeEx() */
355 if (!Py_IsInitialized()) {
356 _cffi_py_initialize();
357 #if PY_VERSION_HEX < 0x03070000
358 PyEval_InitThreads();
359 #endif
360 PyEval_SaveThread(); /* release the GIL */
361 /* the returned tstate must be the one that has been stored into the
362 autoTLSkey by _PyGILState_Init() called from Py_Initialize(). */
363 }
364 else {
365 #if PY_VERSION_HEX < 0x03070000
366 /* PyEval_InitThreads() is always a no-op from CPython 3.7 */
367 PyGILState_STATE state = PyGILState_Ensure();
368 PyEval_InitThreads();
369 PyGILState_Release(state);
370 #endif
371 }
372
373 #ifdef WITH_THREAD
374 /* release the lock */
375 while (!cffi_compare_and_swap(lock, locked_value, old_value))
376 ;
377 #endif
378
379 return 0;
380 }
381
382 /********** end CPython-specific section **********/
383
384
385 #else
386
387
388 /********** PyPy-specific section **********/
389
390 PyMODINIT_FUNC _CFFI_PYTHON_STARTUP_FUNC(const void *[]); /* forward */
391
392 static struct _cffi_pypy_init_s {
393 const char *name;
394 void *func; /* function pointer */
395 const char *code;
396 } _cffi_pypy_init = {
397 _CFFI_MODULE_NAME,
398 _CFFI_PYTHON_STARTUP_FUNC,
399 _CFFI_PYTHON_STARTUP_CODE,
400 };
401
402 extern int pypy_carefully_make_gil(const char *);
403 extern int pypy_init_embedded_cffi_module(int, struct _cffi_pypy_init_s *);
404
405 static int _cffi_carefully_make_gil(void)
406 {
407 return pypy_carefully_make_gil(_CFFI_MODULE_NAME);
408 }
409
410 static int _cffi_initialize_python(void)
411 {
412 return pypy_init_embedded_cffi_module(0xB011, &_cffi_pypy_init);
413 }
414
415 /********** end PyPy-specific section **********/
416
417
418 #endif
419
420
421 #ifdef __GNUC__
422 __attribute__((noinline))
423 #endif
424 static _cffi_call_python_fnptr _cffi_start_python(void)
425 {
426 /* Delicate logic to initialize Python. This function can be
427 called multiple times concurrently, e.g. when the process calls
428 its first ``extern "Python"`` functions in multiple threads at
429 once. It can also be called recursively, in which case we must
430 ignore it. We also have to consider what occurs if several
431 different cffi-based extensions reach this code in parallel
432 threads---it is a different copy of the code, then, and we
433 can't have any shared global variable unless it comes from
434 'libpythonX.Y.so'.
435
436 Idea:
437
438 * _cffi_carefully_make_gil(): "carefully" call
439 PyEval_InitThreads() (possibly with Py_InitializeEx() first).
440
441 * then we use a (local) custom lock to make sure that a call to this
442 cffi-based extension will wait if another call to the *same*
443 extension is running the initialization in another thread.
444 It is reentrant, so that a recursive call will not block, but
445 only one from a different thread.
446
447 * then we grab the GIL and (Python 2) we call Py_InitializeEx().
448 At this point, concurrent calls to Py_InitializeEx() are not
449 possible: we have the GIL.
450
451 * do the rest of the specific initialization, which may
452 temporarily release the GIL but not the custom lock.
453 Only release the custom lock when we are done.
454 */
455 static char called = 0;
456
457 if (_cffi_carefully_make_gil() != 0)
458 return NULL;
459
460 _cffi_acquire_reentrant_mutex();
461
462 /* Here the GIL exists, but we don't have it. We're only protected
463 from concurrency by the reentrant mutex. */
464
465 /* This file only initializes the embedded module once, the first
466 time this is called, even if there are subinterpreters. */
467 if (!called) {
468 called = 1; /* invoke _cffi_initialize_python() only once,
469 but don't set '_cffi_call_python' right now,
470 otherwise concurrent threads won't call
471 this function at all (we need them to wait) */
472 if (_cffi_initialize_python() == 0) {
473 /* now initialization is finished. Switch to the fast-path. */
474
475 /* We would like nobody to see the new value of
476 '_cffi_call_python' without also seeing the rest of the
477 data initialized. However, this is not possible. But
478 the new value of '_cffi_call_python' is the function
479 'cffi_call_python()' from _cffi_backend. So: */
480 cffi_write_barrier();
481 /* ^^^ we put a write barrier here, and a corresponding
482 read barrier at the start of cffi_call_python(). This
483 ensures that after that read barrier, we see everything
484 done here before the write barrier.
485 */
486
487 assert(_cffi_call_python_org != NULL);
488 _cffi_call_python = (_cffi_call_python_fnptr)_cffi_call_python_org;
489 }
490 else {
491 /* initialization failed. Reset this to NULL, even if it was
492 already set to some other value. Future calls to
493 _cffi_start_python() are still forced to occur, and will
494 always return NULL from now on. */
495 _cffi_call_python_org = NULL;
496 }
497 }
498
499 _cffi_release_reentrant_mutex();
500
501 return (_cffi_call_python_fnptr)_cffi_call_python_org;
502 }
503
504 static
505 void _cffi_start_and_call_python(struct _cffi_externpy_s *externpy, char *args)
506 {
507 _cffi_call_python_fnptr fnptr;
508 int current_err = errno;
509 #ifdef _MSC_VER
510 int current_lasterr = GetLastError();
511 #endif
512 fnptr = _cffi_start_python();
513 if (fnptr == NULL) {
514 fprintf(stderr, "function %s() called, but initialization code "
515 "failed. Returning 0.\n", externpy->name);
516 memset(args, 0, externpy->size_of_result);
517 }
518 #ifdef _MSC_VER
519 SetLastError(current_lasterr);
520 #endif
521 errno = current_err;
522
523 if (fnptr != NULL)
524 fnptr(externpy, args);
525 }
526
527
528 /* The cffi_start_python() function makes sure Python is initialized
529 and our cffi module is set up. It can be called manually from the
530 user C code. The same effect is obtained automatically from any
531 dll-exported ``extern "Python"`` function. This function returns
532 -1 if initialization failed, 0 if all is OK. */
533 _CFFI_UNUSED_FN
534 static int cffi_start_python(void)
535 {
536 if (_cffi_call_python == &_cffi_start_and_call_python) {
537 if (_cffi_start_python() == NULL)
538 return -1;
539 }
540 cffi_read_barrier();
541 return 0;
542 }
543
544 #undef cffi_compare_and_swap
545 #undef cffi_write_barrier
546 #undef cffi_read_barrier
547
548 #ifdef __cplusplus
549 }
550 #endif