1
2 /* Thread and interpreter state structures and their interfaces */
3
4 #include "Python.h"
5 #include "pycore_ceval.h"
6 #include "pycore_initconfig.h"
7 #include "pycore_pymem.h"
8 #include "pycore_pystate.h"
9 #include "pycore_pylifecycle.h"
10
11 /* --------------------------------------------------------------------------
12 CAUTION
13
14 Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
15 number of these functions are advertised as safe to call when the GIL isn't
16 held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
17 debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
18 to avoid the expense of doing their own locking).
19 -------------------------------------------------------------------------- */
20
21 #ifdef HAVE_DLOPEN
22 #ifdef HAVE_DLFCN_H
23 #include <dlfcn.h>
24 #endif
25 #if !HAVE_DECL_RTLD_LAZY
26 #define RTLD_LAZY 1
27 #endif
28 #endif
29
30 #ifdef __cplusplus
31 extern "C" {
32 #endif
33
34 #define _PyRuntimeGILState_GetThreadState(gilstate) \
35 ((PyThreadState*)_Py_atomic_load_relaxed(&(gilstate)->tstate_current))
36 #define _PyRuntimeGILState_SetThreadState(gilstate, value) \
37 _Py_atomic_store_relaxed(&(gilstate)->tstate_current, \
38 (uintptr_t)(value))
39
40 /* Forward declarations */
41 static PyThreadState *_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate);
42 static void _PyThreadState_Delete(_PyRuntimeState *runtime, PyThreadState *tstate);
43
44
45 static PyStatus
_PyRuntimeState_Init_impl(_PyRuntimeState * runtime)46 _PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
47 {
48 /* We preserve the hook across init, because there is
49 currently no public API to set it between runtime
50 initialization and interpreter initialization. */
51 void *open_code_hook = runtime->open_code_hook;
52 void *open_code_userdata = runtime->open_code_userdata;
53 _Py_AuditHookEntry *audit_hook_head = runtime->audit_hook_head;
54
55 memset(runtime, 0, sizeof(*runtime));
56
57 runtime->open_code_hook = open_code_hook;
58 runtime->open_code_userdata = open_code_userdata;
59 runtime->audit_hook_head = audit_hook_head;
60
61 _PyGC_Initialize(&runtime->gc);
62 _PyEval_Initialize(&runtime->ceval);
63
64 PyPreConfig_InitPythonConfig(&runtime->preconfig);
65
66 runtime->gilstate.check_enabled = 1;
67
68 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
69 in accordance with the specification. */
70 Py_tss_t initial = Py_tss_NEEDS_INIT;
71 runtime->gilstate.autoTSSkey = initial;
72
73 runtime->interpreters.mutex = PyThread_allocate_lock();
74 if (runtime->interpreters.mutex == NULL) {
75 return _PyStatus_ERR("Can't initialize threads for interpreter");
76 }
77 runtime->interpreters.next_id = -1;
78
79 runtime->xidregistry.mutex = PyThread_allocate_lock();
80 if (runtime->xidregistry.mutex == NULL) {
81 return _PyStatus_ERR("Can't initialize threads for cross-interpreter data registry");
82 }
83
84 // Set it to the ID of the main thread of the main interpreter.
85 runtime->main_thread = PyThread_get_thread_ident();
86
87 return _PyStatus_OK();
88 }
89
90 PyStatus
_PyRuntimeState_Init(_PyRuntimeState * runtime)91 _PyRuntimeState_Init(_PyRuntimeState *runtime)
92 {
93 /* Force default allocator, since _PyRuntimeState_Fini() must
94 use the same allocator than this function. */
95 PyMemAllocatorEx old_alloc;
96 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
97
98 PyStatus status = _PyRuntimeState_Init_impl(runtime);
99
100 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
101 return status;
102 }
103
104 void
_PyRuntimeState_Fini(_PyRuntimeState * runtime)105 _PyRuntimeState_Fini(_PyRuntimeState *runtime)
106 {
107 /* Force the allocator used by _PyRuntimeState_Init(). */
108 PyMemAllocatorEx old_alloc;
109 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
110
111 if (runtime->interpreters.mutex != NULL) {
112 PyThread_free_lock(runtime->interpreters.mutex);
113 runtime->interpreters.mutex = NULL;
114 }
115
116 if (runtime->xidregistry.mutex != NULL) {
117 PyThread_free_lock(runtime->xidregistry.mutex);
118 runtime->xidregistry.mutex = NULL;
119 }
120
121 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
122 }
123
124 /* This function is called from PyOS_AfterFork_Child to ensure that
125 * newly created child processes do not share locks with the parent.
126 */
127
128 void
_PyRuntimeState_ReInitThreads(_PyRuntimeState * runtime)129 _PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
130 {
131 // This was initially set in _PyRuntimeState_Init().
132 runtime->main_thread = PyThread_get_thread_ident();
133
134 /* Force default allocator, since _PyRuntimeState_Fini() must
135 use the same allocator than this function. */
136 PyMemAllocatorEx old_alloc;
137 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
138
139 runtime->interpreters.mutex = PyThread_allocate_lock();
140 runtime->interpreters.main->id_mutex = PyThread_allocate_lock();
141 runtime->xidregistry.mutex = PyThread_allocate_lock();
142
143 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
144
145 if (runtime->interpreters.mutex == NULL) {
146 Py_FatalError("Can't initialize lock for runtime interpreters");
147 }
148
149 if (runtime->interpreters.main->id_mutex == NULL) {
150 Py_FatalError("Can't initialize ID lock for main interpreter");
151 }
152
153 if (runtime->xidregistry.mutex == NULL) {
154 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
155 }
156 }
157
158 #define HEAD_LOCK(runtime) \
159 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
160 #define HEAD_UNLOCK(runtime) \
161 PyThread_release_lock((runtime)->interpreters.mutex)
162
163 /* Forward declaration */
164 static void _PyGILState_NoteThreadState(
165 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
166
167 PyStatus
_PyInterpreterState_Enable(_PyRuntimeState * runtime)168 _PyInterpreterState_Enable(_PyRuntimeState *runtime)
169 {
170 struct pyinterpreters *interpreters = &runtime->interpreters;
171 interpreters->next_id = 0;
172
173 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
174 Create a new mutex if needed. */
175 if (interpreters->mutex == NULL) {
176 /* Force default allocator, since _PyRuntimeState_Fini() must
177 use the same allocator than this function. */
178 PyMemAllocatorEx old_alloc;
179 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
180
181 interpreters->mutex = PyThread_allocate_lock();
182
183 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
184
185 if (interpreters->mutex == NULL) {
186 return _PyStatus_ERR("Can't initialize threads for interpreter");
187 }
188 }
189
190 return _PyStatus_OK();
191 }
192
193 PyInterpreterState *
PyInterpreterState_New(void)194 PyInterpreterState_New(void)
195 {
196 if (PySys_Audit("cpython.PyInterpreterState_New", NULL) < 0) {
197 return NULL;
198 }
199
200 PyInterpreterState *interp = PyMem_RawMalloc(sizeof(PyInterpreterState));
201 if (interp == NULL) {
202 return NULL;
203 }
204
205 memset(interp, 0, sizeof(*interp));
206 interp->id_refcount = -1;
207 interp->check_interval = 100;
208
209 PyConfig_InitPythonConfig(&interp->config);
210
211 interp->eval_frame = _PyEval_EvalFrameDefault;
212 #ifdef HAVE_DLOPEN
213 #if HAVE_DECL_RTLD_NOW
214 interp->dlopenflags = RTLD_NOW;
215 #else
216 interp->dlopenflags = RTLD_LAZY;
217 #endif
218 #endif
219
220 _PyRuntimeState *runtime = &_PyRuntime;
221 struct pyinterpreters *interpreters = &runtime->interpreters;
222
223 HEAD_LOCK(runtime);
224 if (interpreters->next_id < 0) {
225 /* overflow or Py_Initialize() not called! */
226 PyErr_SetString(PyExc_RuntimeError,
227 "failed to get an interpreter ID");
228 PyMem_RawFree(interp);
229 interp = NULL;
230 }
231 else {
232 interp->id = interpreters->next_id;
233 interpreters->next_id += 1;
234 interp->next = interpreters->head;
235 if (interpreters->main == NULL) {
236 interpreters->main = interp;
237 }
238 interpreters->head = interp;
239 }
240 HEAD_UNLOCK(runtime);
241
242 if (interp == NULL) {
243 return NULL;
244 }
245
246 interp->tstate_next_unique_id = 0;
247
248 interp->audit_hooks = NULL;
249
250 return interp;
251 }
252
253
254 static void
_PyInterpreterState_Clear(_PyRuntimeState * runtime,PyInterpreterState * interp)255 _PyInterpreterState_Clear(_PyRuntimeState *runtime, PyInterpreterState *interp)
256 {
257 if (PySys_Audit("cpython.PyInterpreterState_Clear", NULL) < 0) {
258 PyErr_Clear();
259 }
260
261 HEAD_LOCK(runtime);
262 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
263 PyThreadState_Clear(p);
264 }
265 HEAD_UNLOCK(runtime);
266
267 Py_CLEAR(interp->audit_hooks);
268
269 PyConfig_Clear(&interp->config);
270 Py_CLEAR(interp->codec_search_path);
271 Py_CLEAR(interp->codec_search_cache);
272 Py_CLEAR(interp->codec_error_registry);
273 Py_CLEAR(interp->modules);
274 Py_CLEAR(interp->modules_by_index);
275 Py_CLEAR(interp->sysdict);
276 Py_CLEAR(interp->builtins);
277 Py_CLEAR(interp->builtins_copy);
278 Py_CLEAR(interp->importlib);
279 Py_CLEAR(interp->import_func);
280 Py_CLEAR(interp->dict);
281 #ifdef HAVE_FORK
282 Py_CLEAR(interp->before_forkers);
283 Py_CLEAR(interp->after_forkers_parent);
284 Py_CLEAR(interp->after_forkers_child);
285 #endif
286 if (runtime->finalizing == NULL) {
287 _PyWarnings_Fini(interp);
288 }
289 // XXX Once we have one allocator per interpreter (i.e.
290 // per-interpreter GC) we must ensure that all of the interpreter's
291 // objects have been cleaned up at the point.
292 }
293
294 void
PyInterpreterState_Clear(PyInterpreterState * interp)295 PyInterpreterState_Clear(PyInterpreterState *interp)
296 {
297 _PyInterpreterState_Clear(&_PyRuntime, interp);
298 }
299
300
301 static void
zapthreads(_PyRuntimeState * runtime,PyInterpreterState * interp)302 zapthreads(_PyRuntimeState *runtime, PyInterpreterState *interp)
303 {
304 PyThreadState *p;
305 /* No need to lock the mutex here because this should only happen
306 when the threads are all really dead (XXX famous last words). */
307 while ((p = interp->tstate_head) != NULL) {
308 _PyThreadState_Delete(runtime, p);
309 }
310 }
311
312
313 static void
_PyInterpreterState_Delete(_PyRuntimeState * runtime,PyInterpreterState * interp)314 _PyInterpreterState_Delete(_PyRuntimeState *runtime,
315 PyInterpreterState *interp)
316 {
317 struct pyinterpreters *interpreters = &runtime->interpreters;
318 zapthreads(runtime, interp);
319 HEAD_LOCK(runtime);
320 PyInterpreterState **p;
321 for (p = &interpreters->head; ; p = &(*p)->next) {
322 if (*p == NULL) {
323 Py_FatalError("PyInterpreterState_Delete: invalid interp");
324 }
325 if (*p == interp) {
326 break;
327 }
328 }
329 if (interp->tstate_head != NULL) {
330 Py_FatalError("PyInterpreterState_Delete: remaining threads");
331 }
332 *p = interp->next;
333 if (interpreters->main == interp) {
334 interpreters->main = NULL;
335 if (interpreters->head != NULL) {
336 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
337 }
338 }
339 HEAD_UNLOCK(runtime);
340 if (interp->id_mutex != NULL) {
341 PyThread_free_lock(interp->id_mutex);
342 }
343 PyMem_RawFree(interp);
344 }
345
346
347 void
PyInterpreterState_Delete(PyInterpreterState * interp)348 PyInterpreterState_Delete(PyInterpreterState *interp)
349 {
350 _PyInterpreterState_Delete(&_PyRuntime, interp);
351 }
352
353
354 /*
355 * Delete all interpreter states except the main interpreter. If there
356 * is a current interpreter state, it *must* be the main interpreter.
357 */
358 void
_PyInterpreterState_DeleteExceptMain(_PyRuntimeState * runtime)359 _PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
360 {
361 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
362 struct pyinterpreters *interpreters = &runtime->interpreters;
363
364 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
365 if (tstate != NULL && tstate->interp != interpreters->main) {
366 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
367 }
368
369 HEAD_LOCK(runtime);
370 PyInterpreterState *interp = interpreters->head;
371 interpreters->head = NULL;
372 while (interp != NULL) {
373 if (interp == interpreters->main) {
374 interpreters->main->next = NULL;
375 interpreters->head = interp;
376 interp = interp->next;
377 continue;
378 }
379
380 _PyInterpreterState_Clear(runtime, interp); // XXX must activate?
381 zapthreads(runtime, interp);
382 if (interp->id_mutex != NULL) {
383 PyThread_free_lock(interp->id_mutex);
384 }
385 PyInterpreterState *prev_interp = interp;
386 interp = interp->next;
387 PyMem_RawFree(prev_interp);
388 }
389 HEAD_UNLOCK(runtime);
390
391 if (interpreters->head == NULL) {
392 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
393 }
394 _PyThreadState_Swap(gilstate, tstate);
395 }
396
397
398 PyInterpreterState *
_PyInterpreterState_Get(void)399 _PyInterpreterState_Get(void)
400 {
401 PyThreadState *tstate = _PyThreadState_GET();
402 if (tstate == NULL) {
403 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
404 }
405 PyInterpreterState *interp = tstate->interp;
406 if (interp == NULL) {
407 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
408 }
409 return interp;
410 }
411
412
413 int64_t
PyInterpreterState_GetID(PyInterpreterState * interp)414 PyInterpreterState_GetID(PyInterpreterState *interp)
415 {
416 if (interp == NULL) {
417 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
418 return -1;
419 }
420 return interp->id;
421 }
422
423
424 static PyInterpreterState *
interp_look_up_id(_PyRuntimeState * runtime,PY_INT64_T requested_id)425 interp_look_up_id(_PyRuntimeState *runtime, PY_INT64_T requested_id)
426 {
427 PyInterpreterState *interp = runtime->interpreters.head;
428 while (interp != NULL) {
429 PY_INT64_T id = PyInterpreterState_GetID(interp);
430 if (id < 0) {
431 return NULL;
432 }
433 if (requested_id == id) {
434 return interp;
435 }
436 interp = PyInterpreterState_Next(interp);
437 }
438 return NULL;
439 }
440
441 PyInterpreterState *
_PyInterpreterState_LookUpID(PY_INT64_T requested_id)442 _PyInterpreterState_LookUpID(PY_INT64_T requested_id)
443 {
444 PyInterpreterState *interp = NULL;
445 if (requested_id >= 0) {
446 _PyRuntimeState *runtime = &_PyRuntime;
447 HEAD_LOCK(runtime);
448 interp = interp_look_up_id(runtime, requested_id);
449 HEAD_UNLOCK(runtime);
450 }
451 if (interp == NULL && !PyErr_Occurred()) {
452 PyErr_Format(PyExc_RuntimeError,
453 "unrecognized interpreter ID %lld", requested_id);
454 }
455 return interp;
456 }
457
458
459 int
_PyInterpreterState_IDInitref(PyInterpreterState * interp)460 _PyInterpreterState_IDInitref(PyInterpreterState *interp)
461 {
462 if (interp->id_mutex != NULL) {
463 return 0;
464 }
465 interp->id_mutex = PyThread_allocate_lock();
466 if (interp->id_mutex == NULL) {
467 PyErr_SetString(PyExc_RuntimeError,
468 "failed to create init interpreter ID mutex");
469 return -1;
470 }
471 interp->id_refcount = 0;
472 return 0;
473 }
474
475
476 void
_PyInterpreterState_IDIncref(PyInterpreterState * interp)477 _PyInterpreterState_IDIncref(PyInterpreterState *interp)
478 {
479 if (interp->id_mutex == NULL) {
480 return;
481 }
482 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
483 interp->id_refcount += 1;
484 PyThread_release_lock(interp->id_mutex);
485 }
486
487
488 void
_PyInterpreterState_IDDecref(PyInterpreterState * interp)489 _PyInterpreterState_IDDecref(PyInterpreterState *interp)
490 {
491 if (interp->id_mutex == NULL) {
492 return;
493 }
494 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
495 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
496 assert(interp->id_refcount != 0);
497 interp->id_refcount -= 1;
498 int64_t refcount = interp->id_refcount;
499 PyThread_release_lock(interp->id_mutex);
500
501 if (refcount == 0 && interp->requires_idref) {
502 // XXX Using the "head" thread isn't strictly correct.
503 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
504 // XXX Possible GILState issues?
505 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
506 Py_EndInterpreter(tstate);
507 _PyThreadState_Swap(gilstate, save_tstate);
508 }
509 }
510
511 int
_PyInterpreterState_RequiresIDRef(PyInterpreterState * interp)512 _PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
513 {
514 return interp->requires_idref;
515 }
516
517 void
_PyInterpreterState_RequireIDRef(PyInterpreterState * interp,int required)518 _PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
519 {
520 interp->requires_idref = required ? 1 : 0;
521 }
522
523 PyObject *
_PyInterpreterState_GetMainModule(PyInterpreterState * interp)524 _PyInterpreterState_GetMainModule(PyInterpreterState *interp)
525 {
526 if (interp->modules == NULL) {
527 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
528 return NULL;
529 }
530 return PyMapping_GetItemString(interp->modules, "__main__");
531 }
532
533 PyObject *
PyInterpreterState_GetDict(PyInterpreterState * interp)534 PyInterpreterState_GetDict(PyInterpreterState *interp)
535 {
536 if (interp->dict == NULL) {
537 interp->dict = PyDict_New();
538 if (interp->dict == NULL) {
539 PyErr_Clear();
540 }
541 }
542 /* Returning NULL means no per-interpreter dict is available. */
543 return interp->dict;
544 }
545
546 /* Default implementation for _PyThreadState_GetFrame */
547 static struct _frame *
threadstate_getframe(PyThreadState * self)548 threadstate_getframe(PyThreadState *self)
549 {
550 return self->frame;
551 }
552
553 static PyThreadState *
new_threadstate(PyInterpreterState * interp,int init)554 new_threadstate(PyInterpreterState *interp, int init)
555 {
556 _PyRuntimeState *runtime = &_PyRuntime;
557 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
558 if (tstate == NULL) {
559 return NULL;
560 }
561
562 if (_PyThreadState_GetFrame == NULL) {
563 _PyThreadState_GetFrame = threadstate_getframe;
564 }
565
566 tstate->interp = interp;
567
568 tstate->frame = NULL;
569 tstate->recursion_depth = 0;
570 tstate->overflowed = 0;
571 tstate->recursion_critical = 0;
572 tstate->stackcheck_counter = 0;
573 tstate->tracing = 0;
574 tstate->use_tracing = 0;
575 tstate->gilstate_counter = 0;
576 tstate->async_exc = NULL;
577 tstate->thread_id = PyThread_get_thread_ident();
578
579 tstate->dict = NULL;
580
581 tstate->curexc_type = NULL;
582 tstate->curexc_value = NULL;
583 tstate->curexc_traceback = NULL;
584
585 tstate->exc_state.exc_type = NULL;
586 tstate->exc_state.exc_value = NULL;
587 tstate->exc_state.exc_traceback = NULL;
588 tstate->exc_state.previous_item = NULL;
589 tstate->exc_info = &tstate->exc_state;
590
591 tstate->c_profilefunc = NULL;
592 tstate->c_tracefunc = NULL;
593 tstate->c_profileobj = NULL;
594 tstate->c_traceobj = NULL;
595
596 tstate->trash_delete_nesting = 0;
597 tstate->trash_delete_later = NULL;
598 tstate->on_delete = NULL;
599 tstate->on_delete_data = NULL;
600
601 tstate->coroutine_origin_tracking_depth = 0;
602
603 tstate->async_gen_firstiter = NULL;
604 tstate->async_gen_finalizer = NULL;
605
606 tstate->context = NULL;
607 tstate->context_ver = 1;
608
609 if (init) {
610 _PyThreadState_Init(runtime, tstate);
611 }
612
613 HEAD_LOCK(runtime);
614 tstate->id = ++interp->tstate_next_unique_id;
615 tstate->prev = NULL;
616 tstate->next = interp->tstate_head;
617 if (tstate->next)
618 tstate->next->prev = tstate;
619 interp->tstate_head = tstate;
620 HEAD_UNLOCK(runtime);
621
622 return tstate;
623 }
624
625 PyThreadState *
PyThreadState_New(PyInterpreterState * interp)626 PyThreadState_New(PyInterpreterState *interp)
627 {
628 return new_threadstate(interp, 1);
629 }
630
631 PyThreadState *
_PyThreadState_Prealloc(PyInterpreterState * interp)632 _PyThreadState_Prealloc(PyInterpreterState *interp)
633 {
634 return new_threadstate(interp, 0);
635 }
636
637 void
_PyThreadState_Init(_PyRuntimeState * runtime,PyThreadState * tstate)638 _PyThreadState_Init(_PyRuntimeState *runtime, PyThreadState *tstate)
639 {
640 _PyGILState_NoteThreadState(&runtime->gilstate, tstate);
641 }
642
643 PyObject*
PyState_FindModule(struct PyModuleDef * module)644 PyState_FindModule(struct PyModuleDef* module)
645 {
646 Py_ssize_t index = module->m_base.m_index;
647 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
648 PyObject *res;
649 if (module->m_slots) {
650 return NULL;
651 }
652 if (index == 0)
653 return NULL;
654 if (state->modules_by_index == NULL)
655 return NULL;
656 if (index >= PyList_GET_SIZE(state->modules_by_index))
657 return NULL;
658 res = PyList_GET_ITEM(state->modules_by_index, index);
659 return res==Py_None ? NULL : res;
660 }
661
662 int
_PyState_AddModule(PyObject * module,struct PyModuleDef * def)663 _PyState_AddModule(PyObject* module, struct PyModuleDef* def)
664 {
665 PyInterpreterState *state;
666 if (!def) {
667 assert(PyErr_Occurred());
668 return -1;
669 }
670 if (def->m_slots) {
671 PyErr_SetString(PyExc_SystemError,
672 "PyState_AddModule called on module with slots");
673 return -1;
674 }
675 state = _PyInterpreterState_GET_UNSAFE();
676 if (!state->modules_by_index) {
677 state->modules_by_index = PyList_New(0);
678 if (!state->modules_by_index)
679 return -1;
680 }
681 while (PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
682 if (PyList_Append(state->modules_by_index, Py_None) < 0)
683 return -1;
684 Py_INCREF(module);
685 return PyList_SetItem(state->modules_by_index,
686 def->m_base.m_index, module);
687 }
688
689 int
PyState_AddModule(PyObject * module,struct PyModuleDef * def)690 PyState_AddModule(PyObject* module, struct PyModuleDef* def)
691 {
692 Py_ssize_t index;
693 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
694 if (!def) {
695 Py_FatalError("PyState_AddModule: Module Definition is NULL");
696 return -1;
697 }
698 index = def->m_base.m_index;
699 if (state->modules_by_index &&
700 index < PyList_GET_SIZE(state->modules_by_index) &&
701 module == PyList_GET_ITEM(state->modules_by_index, index)) {
702 Py_FatalError("PyState_AddModule: Module already added!");
703 return -1;
704 }
705 return _PyState_AddModule(module, def);
706 }
707
708 int
PyState_RemoveModule(struct PyModuleDef * def)709 PyState_RemoveModule(struct PyModuleDef* def)
710 {
711 PyInterpreterState *state;
712 Py_ssize_t index = def->m_base.m_index;
713 if (def->m_slots) {
714 PyErr_SetString(PyExc_SystemError,
715 "PyState_RemoveModule called on module with slots");
716 return -1;
717 }
718 state = _PyInterpreterState_GET_UNSAFE();
719 if (index == 0) {
720 Py_FatalError("PyState_RemoveModule: Module index invalid.");
721 return -1;
722 }
723 if (state->modules_by_index == NULL) {
724 Py_FatalError("PyState_RemoveModule: Interpreters module-list not accessible.");
725 return -1;
726 }
727 if (index > PyList_GET_SIZE(state->modules_by_index)) {
728 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
729 return -1;
730 }
731 Py_INCREF(Py_None);
732 return PyList_SetItem(state->modules_by_index, index, Py_None);
733 }
734
735 /* used by import.c:PyImport_Cleanup */
736 void
_PyState_ClearModules(void)737 _PyState_ClearModules(void)
738 {
739 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
740 if (state->modules_by_index) {
741 Py_ssize_t i;
742 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
743 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
744 if (PyModule_Check(m)) {
745 /* cleanup the saved copy of module dicts */
746 PyModuleDef *md = PyModule_GetDef(m);
747 if (md)
748 Py_CLEAR(md->m_base.m_copy);
749 }
750 }
751 /* Setting modules_by_index to NULL could be dangerous, so we
752 clear the list instead. */
753 if (PyList_SetSlice(state->modules_by_index,
754 0, PyList_GET_SIZE(state->modules_by_index),
755 NULL))
756 PyErr_WriteUnraisable(state->modules_by_index);
757 }
758 }
759
760 void
PyThreadState_Clear(PyThreadState * tstate)761 PyThreadState_Clear(PyThreadState *tstate)
762 {
763 int verbose = tstate->interp->config.verbose;
764
765 if (verbose && tstate->frame != NULL) {
766 /* bpo-20526: After the main thread calls
767 _PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
768 exit when trying to take the GIL. If a thread exit in the middle of
769 _PyEval_EvalFrameDefault(), tstate->frame is not reset to its
770 previous value. It is more likely with daemon threads, but it can
771 happen with regular threads if threading._shutdown() fails
772 (ex: interrupted by CTRL+C). */
773 fprintf(stderr,
774 "PyThreadState_Clear: warning: thread still has a frame\n");
775 }
776
777 /* Don't clear tstate->frame: it is a borrowed reference */
778
779 Py_CLEAR(tstate->dict);
780 Py_CLEAR(tstate->async_exc);
781
782 Py_CLEAR(tstate->curexc_type);
783 Py_CLEAR(tstate->curexc_value);
784 Py_CLEAR(tstate->curexc_traceback);
785
786 Py_CLEAR(tstate->exc_state.exc_type);
787 Py_CLEAR(tstate->exc_state.exc_value);
788 Py_CLEAR(tstate->exc_state.exc_traceback);
789
790 /* The stack of exception states should contain just this thread. */
791 if (verbose && tstate->exc_info != &tstate->exc_state) {
792 fprintf(stderr,
793 "PyThreadState_Clear: warning: thread still has a generator\n");
794 }
795
796 tstate->c_profilefunc = NULL;
797 tstate->c_tracefunc = NULL;
798 Py_CLEAR(tstate->c_profileobj);
799 Py_CLEAR(tstate->c_traceobj);
800
801 Py_CLEAR(tstate->async_gen_firstiter);
802 Py_CLEAR(tstate->async_gen_finalizer);
803
804 Py_CLEAR(tstate->context);
805 }
806
807
808 /* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
809 static void
tstate_delete_common(_PyRuntimeState * runtime,PyThreadState * tstate)810 tstate_delete_common(_PyRuntimeState *runtime, PyThreadState *tstate)
811 {
812 if (tstate == NULL) {
813 Py_FatalError("PyThreadState_Delete: NULL tstate");
814 }
815 PyInterpreterState *interp = tstate->interp;
816 if (interp == NULL) {
817 Py_FatalError("PyThreadState_Delete: NULL interp");
818 }
819 HEAD_LOCK(runtime);
820 if (tstate->prev)
821 tstate->prev->next = tstate->next;
822 else
823 interp->tstate_head = tstate->next;
824 if (tstate->next)
825 tstate->next->prev = tstate->prev;
826 HEAD_UNLOCK(runtime);
827 if (tstate->on_delete != NULL) {
828 tstate->on_delete(tstate->on_delete_data);
829 }
830 PyMem_RawFree(tstate);
831 }
832
833
834 static void
_PyThreadState_Delete(_PyRuntimeState * runtime,PyThreadState * tstate)835 _PyThreadState_Delete(_PyRuntimeState *runtime, PyThreadState *tstate)
836 {
837 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
838 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
839 Py_FatalError("PyThreadState_Delete: tstate is still current");
840 }
841 if (gilstate->autoInterpreterState &&
842 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
843 {
844 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
845 }
846 tstate_delete_common(runtime, tstate);
847 }
848
849
850 void
PyThreadState_Delete(PyThreadState * tstate)851 PyThreadState_Delete(PyThreadState *tstate)
852 {
853 _PyThreadState_Delete(&_PyRuntime, tstate);
854 }
855
856
857 static void
_PyThreadState_DeleteCurrent(_PyRuntimeState * runtime)858 _PyThreadState_DeleteCurrent(_PyRuntimeState *runtime)
859 {
860 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
861 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
862 if (tstate == NULL)
863 Py_FatalError(
864 "PyThreadState_DeleteCurrent: no current tstate");
865 tstate_delete_common(runtime, tstate);
866 if (gilstate->autoInterpreterState &&
867 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
868 {
869 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
870 }
871 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
872 PyEval_ReleaseLock();
873 }
874
875 void
PyThreadState_DeleteCurrent()876 PyThreadState_DeleteCurrent()
877 {
878 _PyThreadState_DeleteCurrent(&_PyRuntime);
879 }
880
881
882 /*
883 * Delete all thread states except the one passed as argument.
884 * Note that, if there is a current thread state, it *must* be the one
885 * passed as argument. Also, this won't touch any other interpreters
886 * than the current one, since we don't know which thread state should
887 * be kept in those other interpreters.
888 */
889 void
_PyThreadState_DeleteExcept(_PyRuntimeState * runtime,PyThreadState * tstate)890 _PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
891 {
892 PyInterpreterState *interp = tstate->interp;
893 PyThreadState *p, *next, *garbage;
894 HEAD_LOCK(runtime);
895 /* Remove all thread states, except tstate, from the linked list of
896 thread states. This will allow calling PyThreadState_Clear()
897 without holding the lock. */
898 garbage = interp->tstate_head;
899 if (garbage == tstate)
900 garbage = tstate->next;
901 if (tstate->prev)
902 tstate->prev->next = tstate->next;
903 if (tstate->next)
904 tstate->next->prev = tstate->prev;
905 tstate->prev = tstate->next = NULL;
906 interp->tstate_head = tstate;
907 HEAD_UNLOCK(runtime);
908 /* Clear and deallocate all stale thread states. Even if this
909 executes Python code, we should be safe since it executes
910 in the current thread, not one of the stale threads. */
911 for (p = garbage; p; p = next) {
912 next = p->next;
913 PyThreadState_Clear(p);
914 PyMem_RawFree(p);
915 }
916 }
917
918
919 PyThreadState *
_PyThreadState_UncheckedGet(void)920 _PyThreadState_UncheckedGet(void)
921 {
922 return _PyThreadState_GET();
923 }
924
925
926 PyThreadState *
PyThreadState_Get(void)927 PyThreadState_Get(void)
928 {
929 PyThreadState *tstate = _PyThreadState_GET();
930 if (tstate == NULL)
931 Py_FatalError("PyThreadState_Get: no current thread");
932
933 return tstate;
934 }
935
936
937 PyThreadState *
_PyThreadState_Swap(struct _gilstate_runtime_state * gilstate,PyThreadState * newts)938 _PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
939 {
940 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
941
942 _PyRuntimeGILState_SetThreadState(gilstate, newts);
943 /* It should not be possible for more than one thread state
944 to be used for a thread. Check this the best we can in debug
945 builds.
946 */
947 #if defined(Py_DEBUG)
948 if (newts) {
949 /* This can be called from PyEval_RestoreThread(). Similar
950 to it, we need to ensure errno doesn't change.
951 */
952 int err = errno;
953 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
954 if (check && check->interp == newts->interp && check != newts)
955 Py_FatalError("Invalid thread state for this thread");
956 errno = err;
957 }
958 #endif
959 return oldts;
960 }
961
962 PyThreadState *
PyThreadState_Swap(PyThreadState * newts)963 PyThreadState_Swap(PyThreadState *newts)
964 {
965 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
966 }
967
968 /* An extension mechanism to store arbitrary additional per-thread state.
969 PyThreadState_GetDict() returns a dictionary that can be used to hold such
970 state; the caller should pick a unique key and store its state there. If
971 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
972 and the caller should assume no per-thread state is available. */
973
974 PyObject *
PyThreadState_GetDict(void)975 PyThreadState_GetDict(void)
976 {
977 PyThreadState *tstate = _PyThreadState_GET();
978 if (tstate == NULL)
979 return NULL;
980
981 if (tstate->dict == NULL) {
982 PyObject *d;
983 tstate->dict = d = PyDict_New();
984 if (d == NULL)
985 PyErr_Clear();
986 }
987 return tstate->dict;
988 }
989
990
991 /* Asynchronously raise an exception in a thread.
992 Requested by Just van Rossum and Alex Martelli.
993 To prevent naive misuse, you must write your own extension
994 to call this, or use ctypes. Must be called with the GIL held.
995 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
996 match any known thread id). Can be called with exc=NULL to clear an
997 existing async exception. This raises no exceptions. */
998
999 int
PyThreadState_SetAsyncExc(unsigned long id,PyObject * exc)1000 PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1001 {
1002 _PyRuntimeState *runtime = &_PyRuntime;
1003 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
1004
1005 /* Although the GIL is held, a few C API functions can be called
1006 * without the GIL held, and in particular some that create and
1007 * destroy thread and interpreter states. Those can mutate the
1008 * list of thread states we're traversing, so to prevent that we lock
1009 * head_mutex for the duration.
1010 */
1011 HEAD_LOCK(runtime);
1012 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
1013 if (p->thread_id == id) {
1014 /* Tricky: we need to decref the current value
1015 * (if any) in p->async_exc, but that can in turn
1016 * allow arbitrary Python code to run, including
1017 * perhaps calls to this function. To prevent
1018 * deadlock, we need to release head_mutex before
1019 * the decref.
1020 */
1021 PyObject *old_exc = p->async_exc;
1022 Py_XINCREF(exc);
1023 p->async_exc = exc;
1024 HEAD_UNLOCK(runtime);
1025 Py_XDECREF(old_exc);
1026 _PyEval_SignalAsyncExc(&runtime->ceval);
1027 return 1;
1028 }
1029 }
1030 HEAD_UNLOCK(runtime);
1031 return 0;
1032 }
1033
1034
1035 /* Routines for advanced debuggers, requested by David Beazley.
1036 Don't use unless you know what you are doing! */
1037
1038 PyInterpreterState *
PyInterpreterState_Head(void)1039 PyInterpreterState_Head(void)
1040 {
1041 return _PyRuntime.interpreters.head;
1042 }
1043
1044 PyInterpreterState *
PyInterpreterState_Main(void)1045 PyInterpreterState_Main(void)
1046 {
1047 return _PyRuntime.interpreters.main;
1048 }
1049
1050 PyInterpreterState *
PyInterpreterState_Next(PyInterpreterState * interp)1051 PyInterpreterState_Next(PyInterpreterState *interp) {
1052 return interp->next;
1053 }
1054
1055 PyThreadState *
PyInterpreterState_ThreadHead(PyInterpreterState * interp)1056 PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
1057 return interp->tstate_head;
1058 }
1059
1060 PyThreadState *
PyThreadState_Next(PyThreadState * tstate)1061 PyThreadState_Next(PyThreadState *tstate) {
1062 return tstate->next;
1063 }
1064
1065 /* The implementation of sys._current_frames(). This is intended to be
1066 called with the GIL held, as it will be when called via
1067 sys._current_frames(). It's possible it would work fine even without
1068 the GIL held, but haven't thought enough about that.
1069 */
1070 PyObject *
_PyThread_CurrentFrames(void)1071 _PyThread_CurrentFrames(void)
1072 {
1073 PyObject *result;
1074 PyInterpreterState *i;
1075
1076 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1077 return NULL;
1078 }
1079
1080 result = PyDict_New();
1081 if (result == NULL)
1082 return NULL;
1083
1084 /* for i in all interpreters:
1085 * for t in all of i's thread states:
1086 * if t's frame isn't NULL, map t's id to its frame
1087 * Because these lists can mutate even when the GIL is held, we
1088 * need to grab head_mutex for the duration.
1089 */
1090 _PyRuntimeState *runtime = &_PyRuntime;
1091 HEAD_LOCK(runtime);
1092 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
1093 PyThreadState *t;
1094 for (t = i->tstate_head; t != NULL; t = t->next) {
1095 PyObject *id;
1096 int stat;
1097 struct _frame *frame = t->frame;
1098 if (frame == NULL)
1099 continue;
1100 id = PyLong_FromUnsignedLong(t->thread_id);
1101 if (id == NULL)
1102 goto Fail;
1103 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1104 Py_DECREF(id);
1105 if (stat < 0)
1106 goto Fail;
1107 }
1108 }
1109 HEAD_UNLOCK(runtime);
1110 return result;
1111
1112 Fail:
1113 HEAD_UNLOCK(runtime);
1114 Py_DECREF(result);
1115 return NULL;
1116 }
1117
1118 /* Python "auto thread state" API. */
1119
1120 /* Keep this as a static, as it is not reliable! It can only
1121 ever be compared to the state for the *current* thread.
1122 * If not equal, then it doesn't matter that the actual
1123 value may change immediately after comparison, as it can't
1124 possibly change to the current thread's state.
1125 * If equal, then the current thread holds the lock, so the value can't
1126 change until we yield the lock.
1127 */
1128 static int
PyThreadState_IsCurrent(PyThreadState * tstate)1129 PyThreadState_IsCurrent(PyThreadState *tstate)
1130 {
1131 /* Must be the tstate for this thread */
1132 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1133 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1134 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
1135 }
1136
1137 /* Internal initialization/finalization functions called by
1138 Py_Initialize/Py_FinalizeEx
1139 */
1140 void
_PyGILState_Init(_PyRuntimeState * runtime,PyInterpreterState * interp,PyThreadState * tstate)1141 _PyGILState_Init(_PyRuntimeState *runtime,
1142 PyInterpreterState *interp, PyThreadState *tstate)
1143 {
1144 /* must init with valid states */
1145 assert(interp != NULL);
1146 assert(tstate != NULL);
1147
1148 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1149
1150 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
1151 Py_FatalError("Could not allocate TSS entry");
1152 }
1153 gilstate->autoInterpreterState = interp;
1154 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1155 assert(tstate->gilstate_counter == 0);
1156
1157 _PyGILState_NoteThreadState(gilstate, tstate);
1158 }
1159
1160 PyInterpreterState *
_PyGILState_GetInterpreterStateUnsafe(void)1161 _PyGILState_GetInterpreterStateUnsafe(void)
1162 {
1163 return _PyRuntime.gilstate.autoInterpreterState;
1164 }
1165
1166 void
_PyGILState_Fini(_PyRuntimeState * runtime)1167 _PyGILState_Fini(_PyRuntimeState *runtime)
1168 {
1169 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1170 PyThread_tss_delete(&gilstate->autoTSSkey);
1171 gilstate->autoInterpreterState = NULL;
1172 }
1173
1174 /* Reset the TSS key - called by PyOS_AfterFork_Child().
1175 * This should not be necessary, but some - buggy - pthread implementations
1176 * don't reset TSS upon fork(), see issue #10517.
1177 */
1178 void
_PyGILState_Reinit(_PyRuntimeState * runtime)1179 _PyGILState_Reinit(_PyRuntimeState *runtime)
1180 {
1181 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1182 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
1183
1184 PyThread_tss_delete(&gilstate->autoTSSkey);
1185 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
1186 Py_FatalError("Could not allocate TSS entry");
1187 }
1188
1189 /* If the thread had an associated auto thread state, reassociate it with
1190 * the new key. */
1191 if (tstate &&
1192 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
1193 {
1194 Py_FatalError("Couldn't create autoTSSkey mapping");
1195 }
1196 }
1197
1198 /* When a thread state is created for a thread by some mechanism other than
1199 PyGILState_Ensure, it's important that the GILState machinery knows about
1200 it so it doesn't try to create another thread state for the thread (this is
1201 a better fix for SF bug #1010677 than the first one attempted).
1202 */
1203 static void
_PyGILState_NoteThreadState(struct _gilstate_runtime_state * gilstate,PyThreadState * tstate)1204 _PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
1205 {
1206 /* If autoTSSkey isn't initialized, this must be the very first
1207 threadstate created in Py_Initialize(). Don't do anything for now
1208 (we'll be back here when _PyGILState_Init is called). */
1209 if (!gilstate->autoInterpreterState) {
1210 return;
1211 }
1212
1213 /* Stick the thread state for this thread in thread specific storage.
1214
1215 The only situation where you can legitimately have more than one
1216 thread state for an OS level thread is when there are multiple
1217 interpreters.
1218
1219 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1220 #10915 and #15751).
1221
1222 The first thread state created for that given OS level thread will
1223 "win", which seems reasonable behaviour.
1224 */
1225 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1226 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
1227 Py_FatalError("Couldn't create autoTSSkey mapping");
1228 }
1229 }
1230
1231 /* PyGILState_Release must not try to delete this thread state. */
1232 tstate->gilstate_counter = 1;
1233 }
1234
1235 /* The public functions */
1236 static PyThreadState *
_PyGILState_GetThisThreadState(struct _gilstate_runtime_state * gilstate)1237 _PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1238 {
1239 if (gilstate->autoInterpreterState == NULL)
1240 return NULL;
1241 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1242 }
1243
1244 PyThreadState *
PyGILState_GetThisThreadState(void)1245 PyGILState_GetThisThreadState(void)
1246 {
1247 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
1248 }
1249
1250 int
PyGILState_Check(void)1251 PyGILState_Check(void)
1252 {
1253
1254 if (!_PyGILState_check_enabled) {
1255 return 1;
1256 }
1257
1258 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1259 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1260 return 1;
1261 }
1262
1263 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1264 if (tstate == NULL) {
1265 return 0;
1266 }
1267
1268 return (tstate == _PyGILState_GetThisThreadState(gilstate));
1269 }
1270
1271 PyGILState_STATE
PyGILState_Ensure(void)1272 PyGILState_Ensure(void)
1273 {
1274 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1275 int current;
1276 PyThreadState *tcur;
1277 int need_init_threads = 0;
1278
1279 /* Note that we do not auto-init Python here - apart from
1280 potential races with 2 threads auto-initializing, pep-311
1281 spells out other issues. Embedders are expected to have
1282 called Py_Initialize() and usually PyEval_InitThreads().
1283 */
1284 /* Py_Initialize() hasn't been called! */
1285 assert(gilstate->autoInterpreterState);
1286
1287 tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1288 if (tcur == NULL) {
1289 need_init_threads = 1;
1290
1291 /* Create a new thread state for this thread */
1292 tcur = PyThreadState_New(gilstate->autoInterpreterState);
1293 if (tcur == NULL)
1294 Py_FatalError("Couldn't create thread-state for new thread");
1295 /* This is our thread state! We'll need to delete it in the
1296 matching call to PyGILState_Release(). */
1297 tcur->gilstate_counter = 0;
1298 current = 0; /* new thread state is never current */
1299 }
1300 else {
1301 current = PyThreadState_IsCurrent(tcur);
1302 }
1303
1304 if (current == 0) {
1305 PyEval_RestoreThread(tcur);
1306 }
1307
1308 /* Update our counter in the thread-state - no need for locks:
1309 - tcur will remain valid as we hold the GIL.
1310 - the counter is safe as we are the only thread "allowed"
1311 to modify this value
1312 */
1313 ++tcur->gilstate_counter;
1314
1315 if (need_init_threads) {
1316 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1317 called from a new thread for the first time, we need the create the
1318 GIL. */
1319 PyEval_InitThreads();
1320 }
1321
1322 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
1323 }
1324
1325 void
PyGILState_Release(PyGILState_STATE oldstate)1326 PyGILState_Release(PyGILState_STATE oldstate)
1327 {
1328 _PyRuntimeState *runtime = &_PyRuntime;
1329 PyThreadState *tcur = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1330 if (tcur == NULL) {
1331 Py_FatalError("auto-releasing thread-state, "
1332 "but no thread-state for this thread");
1333 }
1334
1335 /* We must hold the GIL and have our thread state current */
1336 /* XXX - remove the check - the assert should be fine,
1337 but while this is very new (April 2003), the extra check
1338 by release-only users can't hurt.
1339 */
1340 if (!PyThreadState_IsCurrent(tcur)) {
1341 Py_FatalError("This thread state must be current when releasing");
1342 }
1343 assert(PyThreadState_IsCurrent(tcur));
1344 --tcur->gilstate_counter;
1345 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
1346
1347 /* If we're going to destroy this thread-state, we must
1348 * clear it while the GIL is held, as destructors may run.
1349 */
1350 if (tcur->gilstate_counter == 0) {
1351 /* can't have been locked when we created it */
1352 assert(oldstate == PyGILState_UNLOCKED);
1353 PyThreadState_Clear(tcur);
1354 /* Delete the thread-state. Note this releases the GIL too!
1355 * It's vital that the GIL be held here, to avoid shutdown
1356 * races; see bugs 225673 and 1061968 (that nasty bug has a
1357 * habit of coming back).
1358 */
1359 _PyThreadState_DeleteCurrent(runtime);
1360 }
1361 /* Release the lock if necessary */
1362 else if (oldstate == PyGILState_UNLOCKED)
1363 PyEval_SaveThread();
1364 }
1365
1366
1367 /**************************/
1368 /* cross-interpreter data */
1369 /**************************/
1370
1371 /* cross-interpreter data */
1372
1373 crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1374
1375 /* This is a separate func from _PyCrossInterpreterData_Lookup in order
1376 to keep the registry code separate. */
1377 static crossinterpdatafunc
_lookup_getdata(PyObject * obj)1378 _lookup_getdata(PyObject *obj)
1379 {
1380 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1381 if (getdata == NULL && PyErr_Occurred() == 0)
1382 PyErr_Format(PyExc_ValueError,
1383 "%S does not support cross-interpreter data", obj);
1384 return getdata;
1385 }
1386
1387 int
_PyObject_CheckCrossInterpreterData(PyObject * obj)1388 _PyObject_CheckCrossInterpreterData(PyObject *obj)
1389 {
1390 crossinterpdatafunc getdata = _lookup_getdata(obj);
1391 if (getdata == NULL) {
1392 return -1;
1393 }
1394 return 0;
1395 }
1396
1397 static int
_check_xidata(_PyCrossInterpreterData * data)1398 _check_xidata(_PyCrossInterpreterData *data)
1399 {
1400 // data->data can be anything, including NULL, so we don't check it.
1401
1402 // data->obj may be NULL, so we don't check it.
1403
1404 if (data->interp < 0) {
1405 PyErr_SetString(PyExc_SystemError, "missing interp");
1406 return -1;
1407 }
1408
1409 if (data->new_object == NULL) {
1410 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1411 return -1;
1412 }
1413
1414 // data->free may be NULL, so we don't check it.
1415
1416 return 0;
1417 }
1418
1419 int
_PyObject_GetCrossInterpreterData(PyObject * obj,_PyCrossInterpreterData * data)1420 _PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1421 {
1422 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
1423 // to check the result for NULL.
1424 PyInterpreterState *interp = _PyInterpreterState_Get();
1425
1426 // Reset data before re-populating.
1427 *data = (_PyCrossInterpreterData){0};
1428 data->free = PyMem_RawFree; // Set a default that may be overridden.
1429
1430 // Call the "getdata" func for the object.
1431 Py_INCREF(obj);
1432 crossinterpdatafunc getdata = _lookup_getdata(obj);
1433 if (getdata == NULL) {
1434 Py_DECREF(obj);
1435 return -1;
1436 }
1437 int res = getdata(obj, data);
1438 Py_DECREF(obj);
1439 if (res != 0) {
1440 return -1;
1441 }
1442
1443 // Fill in the blanks and validate the result.
1444 data->interp = interp->id;
1445 if (_check_xidata(data) != 0) {
1446 _PyCrossInterpreterData_Release(data);
1447 return -1;
1448 }
1449
1450 return 0;
1451 }
1452
1453 static void
_release_xidata(void * arg)1454 _release_xidata(void *arg)
1455 {
1456 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1457 if (data->free != NULL) {
1458 data->free(data->data);
1459 }
1460 Py_XDECREF(data->obj);
1461 }
1462
1463 static void
_call_in_interpreter(struct _gilstate_runtime_state * gilstate,PyInterpreterState * interp,void (* func)(void *),void * arg)1464 _call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1465 PyInterpreterState *interp,
1466 void (*func)(void *), void *arg)
1467 {
1468 /* We would use Py_AddPendingCall() if it weren't specific to the
1469 * main interpreter (see bpo-33608). In the meantime we take a
1470 * naive approach.
1471 */
1472 PyThreadState *save_tstate = NULL;
1473 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1474 // XXX Using the "head" thread isn't strictly correct.
1475 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1476 // XXX Possible GILState issues?
1477 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1478 }
1479
1480 func(arg);
1481
1482 // Switch back.
1483 if (save_tstate != NULL) {
1484 _PyThreadState_Swap(gilstate, save_tstate);
1485 }
1486 }
1487
1488 void
_PyCrossInterpreterData_Release(_PyCrossInterpreterData * data)1489 _PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1490 {
1491 if (data->data == NULL && data->obj == NULL) {
1492 // Nothing to release!
1493 return;
1494 }
1495
1496 // Switch to the original interpreter.
1497 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1498 if (interp == NULL) {
1499 // The intepreter was already destroyed.
1500 if (data->free != NULL) {
1501 // XXX Someone leaked some memory...
1502 }
1503 return;
1504 }
1505
1506 // "Release" the data and/or the object.
1507 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1508 _call_in_interpreter(gilstate, interp, _release_xidata, data);
1509 }
1510
1511 PyObject *
_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData * data)1512 _PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1513 {
1514 return data->new_object(data);
1515 }
1516
1517 /* registry of {type -> crossinterpdatafunc} */
1518
1519 /* For now we use a global registry of shareable classes. An
1520 alternative would be to add a tp_* slot for a class's
1521 crossinterpdatafunc. It would be simpler and more efficient. */
1522
1523 static int
_register_xidata(struct _xidregistry * xidregistry,PyTypeObject * cls,crossinterpdatafunc getdata)1524 _register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1525 crossinterpdatafunc getdata)
1526 {
1527 // Note that we effectively replace already registered classes
1528 // rather than failing.
1529 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1530 if (newhead == NULL)
1531 return -1;
1532 newhead->cls = cls;
1533 newhead->getdata = getdata;
1534 newhead->next = xidregistry->head;
1535 xidregistry->head = newhead;
1536 return 0;
1537 }
1538
1539 static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
1540
1541 int
_PyCrossInterpreterData_RegisterClass(PyTypeObject * cls,crossinterpdatafunc getdata)1542 _PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
1543 crossinterpdatafunc getdata)
1544 {
1545 if (!PyType_Check(cls)) {
1546 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1547 return -1;
1548 }
1549 if (getdata == NULL) {
1550 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1551 return -1;
1552 }
1553
1554 // Make sure the class isn't ever deallocated.
1555 Py_INCREF((PyObject *)cls);
1556
1557 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1558 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1559 if (xidregistry->head == NULL) {
1560 _register_builtins_for_crossinterpreter_data(xidregistry);
1561 }
1562 int res = _register_xidata(xidregistry, cls, getdata);
1563 PyThread_release_lock(xidregistry->mutex);
1564 return res;
1565 }
1566
1567 /* Cross-interpreter objects are looked up by exact match on the class.
1568 We can reassess this policy when we move from a global registry to a
1569 tp_* slot. */
1570
1571 crossinterpdatafunc
_PyCrossInterpreterData_Lookup(PyObject * obj)1572 _PyCrossInterpreterData_Lookup(PyObject *obj)
1573 {
1574 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1575 PyObject *cls = PyObject_Type(obj);
1576 crossinterpdatafunc getdata = NULL;
1577 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1578 struct _xidregitem *cur = xidregistry->head;
1579 if (cur == NULL) {
1580 _register_builtins_for_crossinterpreter_data(xidregistry);
1581 cur = xidregistry->head;
1582 }
1583 for(; cur != NULL; cur = cur->next) {
1584 if (cur->cls == (PyTypeObject *)cls) {
1585 getdata = cur->getdata;
1586 break;
1587 }
1588 }
1589 Py_DECREF(cls);
1590 PyThread_release_lock(xidregistry->mutex);
1591 return getdata;
1592 }
1593
1594 /* cross-interpreter data for builtin types */
1595
1596 struct _shared_bytes_data {
1597 char *bytes;
1598 Py_ssize_t len;
1599 };
1600
1601 static PyObject *
_new_bytes_object(_PyCrossInterpreterData * data)1602 _new_bytes_object(_PyCrossInterpreterData *data)
1603 {
1604 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1605 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
1606 }
1607
1608 static int
_bytes_shared(PyObject * obj,_PyCrossInterpreterData * data)1609 _bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1610 {
1611 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1612 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1613 return -1;
1614 }
1615 data->data = (void *)shared;
1616 Py_INCREF(obj);
1617 data->obj = obj; // Will be "released" (decref'ed) when data released.
1618 data->new_object = _new_bytes_object;
1619 data->free = PyMem_Free;
1620 return 0;
1621 }
1622
1623 struct _shared_str_data {
1624 int kind;
1625 const void *buffer;
1626 Py_ssize_t len;
1627 };
1628
1629 static PyObject *
_new_str_object(_PyCrossInterpreterData * data)1630 _new_str_object(_PyCrossInterpreterData *data)
1631 {
1632 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1633 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1634 }
1635
1636 static int
_str_shared(PyObject * obj,_PyCrossInterpreterData * data)1637 _str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1638 {
1639 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1640 shared->kind = PyUnicode_KIND(obj);
1641 shared->buffer = PyUnicode_DATA(obj);
1642 shared->len = PyUnicode_GET_LENGTH(obj);
1643 data->data = (void *)shared;
1644 Py_INCREF(obj);
1645 data->obj = obj; // Will be "released" (decref'ed) when data released.
1646 data->new_object = _new_str_object;
1647 data->free = PyMem_Free;
1648 return 0;
1649 }
1650
1651 static PyObject *
_new_long_object(_PyCrossInterpreterData * data)1652 _new_long_object(_PyCrossInterpreterData *data)
1653 {
1654 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
1655 }
1656
1657 static int
_long_shared(PyObject * obj,_PyCrossInterpreterData * data)1658 _long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1659 {
1660 /* Note that this means the size of shareable ints is bounded by
1661 * sys.maxsize. Hence on 32-bit architectures that is half the
1662 * size of maximum shareable ints on 64-bit.
1663 */
1664 Py_ssize_t value = PyLong_AsSsize_t(obj);
1665 if (value == -1 && PyErr_Occurred()) {
1666 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1667 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1668 }
1669 return -1;
1670 }
1671 data->data = (void *)value;
1672 data->obj = NULL;
1673 data->new_object = _new_long_object;
1674 data->free = NULL;
1675 return 0;
1676 }
1677
1678 static PyObject *
_new_none_object(_PyCrossInterpreterData * data)1679 _new_none_object(_PyCrossInterpreterData *data)
1680 {
1681 // XXX Singleton refcounts are problematic across interpreters...
1682 Py_INCREF(Py_None);
1683 return Py_None;
1684 }
1685
1686 static int
_none_shared(PyObject * obj,_PyCrossInterpreterData * data)1687 _none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1688 {
1689 data->data = NULL;
1690 // data->obj remains NULL
1691 data->new_object = _new_none_object;
1692 data->free = NULL; // There is nothing to free.
1693 return 0;
1694 }
1695
1696 static void
_register_builtins_for_crossinterpreter_data(struct _xidregistry * xidregistry)1697 _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
1698 {
1699 // None
1700 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1701 Py_FatalError("could not register None for cross-interpreter sharing");
1702 }
1703
1704 // int
1705 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
1706 Py_FatalError("could not register int for cross-interpreter sharing");
1707 }
1708
1709 // bytes
1710 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
1711 Py_FatalError("could not register bytes for cross-interpreter sharing");
1712 }
1713
1714 // str
1715 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
1716 Py_FatalError("could not register str for cross-interpreter sharing");
1717 }
1718 }
1719
1720
1721 #ifdef __cplusplus
1722 }
1723 #endif
1724