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 tstate->id = ++interp->tstate_next_unique_id;
610
611 if (init) {
612 _PyThreadState_Init(runtime, tstate);
613 }
614
615 HEAD_LOCK(runtime);
616 tstate->prev = NULL;
617 tstate->next = interp->tstate_head;
618 if (tstate->next)
619 tstate->next->prev = tstate;
620 interp->tstate_head = tstate;
621 HEAD_UNLOCK(runtime);
622
623 return tstate;
624 }
625
626 PyThreadState *
PyThreadState_New(PyInterpreterState * interp)627 PyThreadState_New(PyInterpreterState *interp)
628 {
629 return new_threadstate(interp, 1);
630 }
631
632 PyThreadState *
_PyThreadState_Prealloc(PyInterpreterState * interp)633 _PyThreadState_Prealloc(PyInterpreterState *interp)
634 {
635 return new_threadstate(interp, 0);
636 }
637
638 void
_PyThreadState_Init(_PyRuntimeState * runtime,PyThreadState * tstate)639 _PyThreadState_Init(_PyRuntimeState *runtime, PyThreadState *tstate)
640 {
641 _PyGILState_NoteThreadState(&runtime->gilstate, tstate);
642 }
643
644 PyObject*
PyState_FindModule(struct PyModuleDef * module)645 PyState_FindModule(struct PyModuleDef* module)
646 {
647 Py_ssize_t index = module->m_base.m_index;
648 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
649 PyObject *res;
650 if (module->m_slots) {
651 return NULL;
652 }
653 if (index == 0)
654 return NULL;
655 if (state->modules_by_index == NULL)
656 return NULL;
657 if (index >= PyList_GET_SIZE(state->modules_by_index))
658 return NULL;
659 res = PyList_GET_ITEM(state->modules_by_index, index);
660 return res==Py_None ? NULL : res;
661 }
662
663 int
_PyState_AddModule(PyObject * module,struct PyModuleDef * def)664 _PyState_AddModule(PyObject* module, struct PyModuleDef* def)
665 {
666 PyInterpreterState *state;
667 if (!def) {
668 assert(PyErr_Occurred());
669 return -1;
670 }
671 if (def->m_slots) {
672 PyErr_SetString(PyExc_SystemError,
673 "PyState_AddModule called on module with slots");
674 return -1;
675 }
676 state = _PyInterpreterState_GET_UNSAFE();
677 if (!state->modules_by_index) {
678 state->modules_by_index = PyList_New(0);
679 if (!state->modules_by_index)
680 return -1;
681 }
682 while (PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
683 if (PyList_Append(state->modules_by_index, Py_None) < 0)
684 return -1;
685 Py_INCREF(module);
686 return PyList_SetItem(state->modules_by_index,
687 def->m_base.m_index, module);
688 }
689
690 int
PyState_AddModule(PyObject * module,struct PyModuleDef * def)691 PyState_AddModule(PyObject* module, struct PyModuleDef* def)
692 {
693 Py_ssize_t index;
694 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
695 if (!def) {
696 Py_FatalError("PyState_AddModule: Module Definition is NULL");
697 return -1;
698 }
699 index = def->m_base.m_index;
700 if (state->modules_by_index &&
701 index < PyList_GET_SIZE(state->modules_by_index) &&
702 module == PyList_GET_ITEM(state->modules_by_index, index)) {
703 Py_FatalError("PyState_AddModule: Module already added!");
704 return -1;
705 }
706 return _PyState_AddModule(module, def);
707 }
708
709 int
PyState_RemoveModule(struct PyModuleDef * def)710 PyState_RemoveModule(struct PyModuleDef* def)
711 {
712 PyInterpreterState *state;
713 Py_ssize_t index = def->m_base.m_index;
714 if (def->m_slots) {
715 PyErr_SetString(PyExc_SystemError,
716 "PyState_RemoveModule called on module with slots");
717 return -1;
718 }
719 state = _PyInterpreterState_GET_UNSAFE();
720 if (index == 0) {
721 Py_FatalError("PyState_RemoveModule: Module index invalid.");
722 return -1;
723 }
724 if (state->modules_by_index == NULL) {
725 Py_FatalError("PyState_RemoveModule: Interpreters module-list not accessible.");
726 return -1;
727 }
728 if (index > PyList_GET_SIZE(state->modules_by_index)) {
729 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
730 return -1;
731 }
732 Py_INCREF(Py_None);
733 return PyList_SetItem(state->modules_by_index, index, Py_None);
734 }
735
736 /* used by import.c:PyImport_Cleanup */
737 void
_PyState_ClearModules(void)738 _PyState_ClearModules(void)
739 {
740 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
741 if (state->modules_by_index) {
742 Py_ssize_t i;
743 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
744 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
745 if (PyModule_Check(m)) {
746 /* cleanup the saved copy of module dicts */
747 PyModuleDef *md = PyModule_GetDef(m);
748 if (md)
749 Py_CLEAR(md->m_base.m_copy);
750 }
751 }
752 /* Setting modules_by_index to NULL could be dangerous, so we
753 clear the list instead. */
754 if (PyList_SetSlice(state->modules_by_index,
755 0, PyList_GET_SIZE(state->modules_by_index),
756 NULL))
757 PyErr_WriteUnraisable(state->modules_by_index);
758 }
759 }
760
761 void
PyThreadState_Clear(PyThreadState * tstate)762 PyThreadState_Clear(PyThreadState *tstate)
763 {
764 int verbose = tstate->interp->config.verbose;
765
766 if (verbose && tstate->frame != NULL)
767 fprintf(stderr,
768 "PyThreadState_Clear: warning: thread still has a frame\n");
769
770 Py_CLEAR(tstate->frame);
771
772 Py_CLEAR(tstate->dict);
773 Py_CLEAR(tstate->async_exc);
774
775 Py_CLEAR(tstate->curexc_type);
776 Py_CLEAR(tstate->curexc_value);
777 Py_CLEAR(tstate->curexc_traceback);
778
779 Py_CLEAR(tstate->exc_state.exc_type);
780 Py_CLEAR(tstate->exc_state.exc_value);
781 Py_CLEAR(tstate->exc_state.exc_traceback);
782
783 /* The stack of exception states should contain just this thread. */
784 if (verbose && tstate->exc_info != &tstate->exc_state) {
785 fprintf(stderr,
786 "PyThreadState_Clear: warning: thread still has a generator\n");
787 }
788
789 tstate->c_profilefunc = NULL;
790 tstate->c_tracefunc = NULL;
791 Py_CLEAR(tstate->c_profileobj);
792 Py_CLEAR(tstate->c_traceobj);
793
794 Py_CLEAR(tstate->async_gen_firstiter);
795 Py_CLEAR(tstate->async_gen_finalizer);
796
797 Py_CLEAR(tstate->context);
798 }
799
800
801 /* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
802 static void
tstate_delete_common(_PyRuntimeState * runtime,PyThreadState * tstate)803 tstate_delete_common(_PyRuntimeState *runtime, PyThreadState *tstate)
804 {
805 if (tstate == NULL) {
806 Py_FatalError("PyThreadState_Delete: NULL tstate");
807 }
808 PyInterpreterState *interp = tstate->interp;
809 if (interp == NULL) {
810 Py_FatalError("PyThreadState_Delete: NULL interp");
811 }
812 HEAD_LOCK(runtime);
813 if (tstate->prev)
814 tstate->prev->next = tstate->next;
815 else
816 interp->tstate_head = tstate->next;
817 if (tstate->next)
818 tstate->next->prev = tstate->prev;
819 HEAD_UNLOCK(runtime);
820 if (tstate->on_delete != NULL) {
821 tstate->on_delete(tstate->on_delete_data);
822 }
823 PyMem_RawFree(tstate);
824 }
825
826
827 static void
_PyThreadState_Delete(_PyRuntimeState * runtime,PyThreadState * tstate)828 _PyThreadState_Delete(_PyRuntimeState *runtime, PyThreadState *tstate)
829 {
830 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
831 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
832 Py_FatalError("PyThreadState_Delete: tstate is still current");
833 }
834 if (gilstate->autoInterpreterState &&
835 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
836 {
837 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
838 }
839 tstate_delete_common(runtime, tstate);
840 }
841
842
843 void
PyThreadState_Delete(PyThreadState * tstate)844 PyThreadState_Delete(PyThreadState *tstate)
845 {
846 _PyThreadState_Delete(&_PyRuntime, tstate);
847 }
848
849
850 static void
_PyThreadState_DeleteCurrent(_PyRuntimeState * runtime)851 _PyThreadState_DeleteCurrent(_PyRuntimeState *runtime)
852 {
853 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
854 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
855 if (tstate == NULL)
856 Py_FatalError(
857 "PyThreadState_DeleteCurrent: no current tstate");
858 tstate_delete_common(runtime, tstate);
859 if (gilstate->autoInterpreterState &&
860 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
861 {
862 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
863 }
864 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
865 PyEval_ReleaseLock();
866 }
867
868 void
PyThreadState_DeleteCurrent()869 PyThreadState_DeleteCurrent()
870 {
871 _PyThreadState_DeleteCurrent(&_PyRuntime);
872 }
873
874
875 /*
876 * Delete all thread states except the one passed as argument.
877 * Note that, if there is a current thread state, it *must* be the one
878 * passed as argument. Also, this won't touch any other interpreters
879 * than the current one, since we don't know which thread state should
880 * be kept in those other interpreters.
881 */
882 void
_PyThreadState_DeleteExcept(_PyRuntimeState * runtime,PyThreadState * tstate)883 _PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
884 {
885 PyInterpreterState *interp = tstate->interp;
886 PyThreadState *p, *next, *garbage;
887 HEAD_LOCK(runtime);
888 /* Remove all thread states, except tstate, from the linked list of
889 thread states. This will allow calling PyThreadState_Clear()
890 without holding the lock. */
891 garbage = interp->tstate_head;
892 if (garbage == tstate)
893 garbage = tstate->next;
894 if (tstate->prev)
895 tstate->prev->next = tstate->next;
896 if (tstate->next)
897 tstate->next->prev = tstate->prev;
898 tstate->prev = tstate->next = NULL;
899 interp->tstate_head = tstate;
900 HEAD_UNLOCK(runtime);
901 /* Clear and deallocate all stale thread states. Even if this
902 executes Python code, we should be safe since it executes
903 in the current thread, not one of the stale threads. */
904 for (p = garbage; p; p = next) {
905 next = p->next;
906 PyThreadState_Clear(p);
907 PyMem_RawFree(p);
908 }
909 }
910
911
912 PyThreadState *
_PyThreadState_UncheckedGet(void)913 _PyThreadState_UncheckedGet(void)
914 {
915 return _PyThreadState_GET();
916 }
917
918
919 PyThreadState *
PyThreadState_Get(void)920 PyThreadState_Get(void)
921 {
922 PyThreadState *tstate = _PyThreadState_GET();
923 if (tstate == NULL)
924 Py_FatalError("PyThreadState_Get: no current thread");
925
926 return tstate;
927 }
928
929
930 PyThreadState *
_PyThreadState_Swap(struct _gilstate_runtime_state * gilstate,PyThreadState * newts)931 _PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
932 {
933 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
934
935 _PyRuntimeGILState_SetThreadState(gilstate, newts);
936 /* It should not be possible for more than one thread state
937 to be used for a thread. Check this the best we can in debug
938 builds.
939 */
940 #if defined(Py_DEBUG)
941 if (newts) {
942 /* This can be called from PyEval_RestoreThread(). Similar
943 to it, we need to ensure errno doesn't change.
944 */
945 int err = errno;
946 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
947 if (check && check->interp == newts->interp && check != newts)
948 Py_FatalError("Invalid thread state for this thread");
949 errno = err;
950 }
951 #endif
952 return oldts;
953 }
954
955 PyThreadState *
PyThreadState_Swap(PyThreadState * newts)956 PyThreadState_Swap(PyThreadState *newts)
957 {
958 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
959 }
960
961 /* An extension mechanism to store arbitrary additional per-thread state.
962 PyThreadState_GetDict() returns a dictionary that can be used to hold such
963 state; the caller should pick a unique key and store its state there. If
964 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
965 and the caller should assume no per-thread state is available. */
966
967 PyObject *
PyThreadState_GetDict(void)968 PyThreadState_GetDict(void)
969 {
970 PyThreadState *tstate = _PyThreadState_GET();
971 if (tstate == NULL)
972 return NULL;
973
974 if (tstate->dict == NULL) {
975 PyObject *d;
976 tstate->dict = d = PyDict_New();
977 if (d == NULL)
978 PyErr_Clear();
979 }
980 return tstate->dict;
981 }
982
983
984 /* Asynchronously raise an exception in a thread.
985 Requested by Just van Rossum and Alex Martelli.
986 To prevent naive misuse, you must write your own extension
987 to call this, or use ctypes. Must be called with the GIL held.
988 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
989 match any known thread id). Can be called with exc=NULL to clear an
990 existing async exception. This raises no exceptions. */
991
992 int
PyThreadState_SetAsyncExc(unsigned long id,PyObject * exc)993 PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
994 {
995 _PyRuntimeState *runtime = &_PyRuntime;
996 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
997
998 /* Although the GIL is held, a few C API functions can be called
999 * without the GIL held, and in particular some that create and
1000 * destroy thread and interpreter states. Those can mutate the
1001 * list of thread states we're traversing, so to prevent that we lock
1002 * head_mutex for the duration.
1003 */
1004 HEAD_LOCK(runtime);
1005 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
1006 if (p->thread_id == id) {
1007 /* Tricky: we need to decref the current value
1008 * (if any) in p->async_exc, but that can in turn
1009 * allow arbitrary Python code to run, including
1010 * perhaps calls to this function. To prevent
1011 * deadlock, we need to release head_mutex before
1012 * the decref.
1013 */
1014 PyObject *old_exc = p->async_exc;
1015 Py_XINCREF(exc);
1016 p->async_exc = exc;
1017 HEAD_UNLOCK(runtime);
1018 Py_XDECREF(old_exc);
1019 _PyEval_SignalAsyncExc(&runtime->ceval);
1020 return 1;
1021 }
1022 }
1023 HEAD_UNLOCK(runtime);
1024 return 0;
1025 }
1026
1027
1028 /* Routines for advanced debuggers, requested by David Beazley.
1029 Don't use unless you know what you are doing! */
1030
1031 PyInterpreterState *
PyInterpreterState_Head(void)1032 PyInterpreterState_Head(void)
1033 {
1034 return _PyRuntime.interpreters.head;
1035 }
1036
1037 PyInterpreterState *
PyInterpreterState_Main(void)1038 PyInterpreterState_Main(void)
1039 {
1040 return _PyRuntime.interpreters.main;
1041 }
1042
1043 PyInterpreterState *
PyInterpreterState_Next(PyInterpreterState * interp)1044 PyInterpreterState_Next(PyInterpreterState *interp) {
1045 return interp->next;
1046 }
1047
1048 PyThreadState *
PyInterpreterState_ThreadHead(PyInterpreterState * interp)1049 PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
1050 return interp->tstate_head;
1051 }
1052
1053 PyThreadState *
PyThreadState_Next(PyThreadState * tstate)1054 PyThreadState_Next(PyThreadState *tstate) {
1055 return tstate->next;
1056 }
1057
1058 /* The implementation of sys._current_frames(). This is intended to be
1059 called with the GIL held, as it will be when called via
1060 sys._current_frames(). It's possible it would work fine even without
1061 the GIL held, but haven't thought enough about that.
1062 */
1063 PyObject *
_PyThread_CurrentFrames(void)1064 _PyThread_CurrentFrames(void)
1065 {
1066 PyObject *result;
1067 PyInterpreterState *i;
1068
1069 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1070 return NULL;
1071 }
1072
1073 result = PyDict_New();
1074 if (result == NULL)
1075 return NULL;
1076
1077 /* for i in all interpreters:
1078 * for t in all of i's thread states:
1079 * if t's frame isn't NULL, map t's id to its frame
1080 * Because these lists can mutate even when the GIL is held, we
1081 * need to grab head_mutex for the duration.
1082 */
1083 _PyRuntimeState *runtime = &_PyRuntime;
1084 HEAD_LOCK(runtime);
1085 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
1086 PyThreadState *t;
1087 for (t = i->tstate_head; t != NULL; t = t->next) {
1088 PyObject *id;
1089 int stat;
1090 struct _frame *frame = t->frame;
1091 if (frame == NULL)
1092 continue;
1093 id = PyLong_FromUnsignedLong(t->thread_id);
1094 if (id == NULL)
1095 goto Fail;
1096 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1097 Py_DECREF(id);
1098 if (stat < 0)
1099 goto Fail;
1100 }
1101 }
1102 HEAD_UNLOCK(runtime);
1103 return result;
1104
1105 Fail:
1106 HEAD_UNLOCK(runtime);
1107 Py_DECREF(result);
1108 return NULL;
1109 }
1110
1111 /* Python "auto thread state" API. */
1112
1113 /* Keep this as a static, as it is not reliable! It can only
1114 ever be compared to the state for the *current* thread.
1115 * If not equal, then it doesn't matter that the actual
1116 value may change immediately after comparison, as it can't
1117 possibly change to the current thread's state.
1118 * If equal, then the current thread holds the lock, so the value can't
1119 change until we yield the lock.
1120 */
1121 static int
PyThreadState_IsCurrent(PyThreadState * tstate)1122 PyThreadState_IsCurrent(PyThreadState *tstate)
1123 {
1124 /* Must be the tstate for this thread */
1125 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1126 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1127 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
1128 }
1129
1130 /* Internal initialization/finalization functions called by
1131 Py_Initialize/Py_FinalizeEx
1132 */
1133 void
_PyGILState_Init(_PyRuntimeState * runtime,PyInterpreterState * interp,PyThreadState * tstate)1134 _PyGILState_Init(_PyRuntimeState *runtime,
1135 PyInterpreterState *interp, PyThreadState *tstate)
1136 {
1137 /* must init with valid states */
1138 assert(interp != NULL);
1139 assert(tstate != NULL);
1140
1141 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1142
1143 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
1144 Py_FatalError("Could not allocate TSS entry");
1145 }
1146 gilstate->autoInterpreterState = interp;
1147 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1148 assert(tstate->gilstate_counter == 0);
1149
1150 _PyGILState_NoteThreadState(gilstate, tstate);
1151 }
1152
1153 PyInterpreterState *
_PyGILState_GetInterpreterStateUnsafe(void)1154 _PyGILState_GetInterpreterStateUnsafe(void)
1155 {
1156 return _PyRuntime.gilstate.autoInterpreterState;
1157 }
1158
1159 void
_PyGILState_Fini(_PyRuntimeState * runtime)1160 _PyGILState_Fini(_PyRuntimeState *runtime)
1161 {
1162 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1163 PyThread_tss_delete(&gilstate->autoTSSkey);
1164 gilstate->autoInterpreterState = NULL;
1165 }
1166
1167 /* Reset the TSS key - called by PyOS_AfterFork_Child().
1168 * This should not be necessary, but some - buggy - pthread implementations
1169 * don't reset TSS upon fork(), see issue #10517.
1170 */
1171 void
_PyGILState_Reinit(_PyRuntimeState * runtime)1172 _PyGILState_Reinit(_PyRuntimeState *runtime)
1173 {
1174 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1175 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
1176
1177 PyThread_tss_delete(&gilstate->autoTSSkey);
1178 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
1179 Py_FatalError("Could not allocate TSS entry");
1180 }
1181
1182 /* If the thread had an associated auto thread state, reassociate it with
1183 * the new key. */
1184 if (tstate &&
1185 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
1186 {
1187 Py_FatalError("Couldn't create autoTSSkey mapping");
1188 }
1189 }
1190
1191 /* When a thread state is created for a thread by some mechanism other than
1192 PyGILState_Ensure, it's important that the GILState machinery knows about
1193 it so it doesn't try to create another thread state for the thread (this is
1194 a better fix for SF bug #1010677 than the first one attempted).
1195 */
1196 static void
_PyGILState_NoteThreadState(struct _gilstate_runtime_state * gilstate,PyThreadState * tstate)1197 _PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
1198 {
1199 /* If autoTSSkey isn't initialized, this must be the very first
1200 threadstate created in Py_Initialize(). Don't do anything for now
1201 (we'll be back here when _PyGILState_Init is called). */
1202 if (!gilstate->autoInterpreterState) {
1203 return;
1204 }
1205
1206 /* Stick the thread state for this thread in thread specific storage.
1207
1208 The only situation where you can legitimately have more than one
1209 thread state for an OS level thread is when there are multiple
1210 interpreters.
1211
1212 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1213 #10915 and #15751).
1214
1215 The first thread state created for that given OS level thread will
1216 "win", which seems reasonable behaviour.
1217 */
1218 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1219 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
1220 Py_FatalError("Couldn't create autoTSSkey mapping");
1221 }
1222 }
1223
1224 /* PyGILState_Release must not try to delete this thread state. */
1225 tstate->gilstate_counter = 1;
1226 }
1227
1228 /* The public functions */
1229 static PyThreadState *
_PyGILState_GetThisThreadState(struct _gilstate_runtime_state * gilstate)1230 _PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1231 {
1232 if (gilstate->autoInterpreterState == NULL)
1233 return NULL;
1234 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1235 }
1236
1237 PyThreadState *
PyGILState_GetThisThreadState(void)1238 PyGILState_GetThisThreadState(void)
1239 {
1240 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
1241 }
1242
1243 int
PyGILState_Check(void)1244 PyGILState_Check(void)
1245 {
1246
1247 if (!_PyGILState_check_enabled) {
1248 return 1;
1249 }
1250
1251 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1252 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1253 return 1;
1254 }
1255
1256 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1257 if (tstate == NULL) {
1258 return 0;
1259 }
1260
1261 return (tstate == _PyGILState_GetThisThreadState(gilstate));
1262 }
1263
1264 PyGILState_STATE
PyGILState_Ensure(void)1265 PyGILState_Ensure(void)
1266 {
1267 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1268 int current;
1269 PyThreadState *tcur;
1270 int need_init_threads = 0;
1271
1272 /* Note that we do not auto-init Python here - apart from
1273 potential races with 2 threads auto-initializing, pep-311
1274 spells out other issues. Embedders are expected to have
1275 called Py_Initialize() and usually PyEval_InitThreads().
1276 */
1277 /* Py_Initialize() hasn't been called! */
1278 assert(gilstate->autoInterpreterState);
1279
1280 tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1281 if (tcur == NULL) {
1282 need_init_threads = 1;
1283
1284 /* Create a new thread state for this thread */
1285 tcur = PyThreadState_New(gilstate->autoInterpreterState);
1286 if (tcur == NULL)
1287 Py_FatalError("Couldn't create thread-state for new thread");
1288 /* This is our thread state! We'll need to delete it in the
1289 matching call to PyGILState_Release(). */
1290 tcur->gilstate_counter = 0;
1291 current = 0; /* new thread state is never current */
1292 }
1293 else {
1294 current = PyThreadState_IsCurrent(tcur);
1295 }
1296
1297 if (current == 0) {
1298 PyEval_RestoreThread(tcur);
1299 }
1300
1301 /* Update our counter in the thread-state - no need for locks:
1302 - tcur will remain valid as we hold the GIL.
1303 - the counter is safe as we are the only thread "allowed"
1304 to modify this value
1305 */
1306 ++tcur->gilstate_counter;
1307
1308 if (need_init_threads) {
1309 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1310 called from a new thread for the first time, we need the create the
1311 GIL. */
1312 PyEval_InitThreads();
1313 }
1314
1315 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
1316 }
1317
1318 void
PyGILState_Release(PyGILState_STATE oldstate)1319 PyGILState_Release(PyGILState_STATE oldstate)
1320 {
1321 _PyRuntimeState *runtime = &_PyRuntime;
1322 PyThreadState *tcur = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1323 if (tcur == NULL) {
1324 Py_FatalError("auto-releasing thread-state, "
1325 "but no thread-state for this thread");
1326 }
1327
1328 /* We must hold the GIL and have our thread state current */
1329 /* XXX - remove the check - the assert should be fine,
1330 but while this is very new (April 2003), the extra check
1331 by release-only users can't hurt.
1332 */
1333 if (!PyThreadState_IsCurrent(tcur)) {
1334 Py_FatalError("This thread state must be current when releasing");
1335 }
1336 assert(PyThreadState_IsCurrent(tcur));
1337 --tcur->gilstate_counter;
1338 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
1339
1340 /* If we're going to destroy this thread-state, we must
1341 * clear it while the GIL is held, as destructors may run.
1342 */
1343 if (tcur->gilstate_counter == 0) {
1344 /* can't have been locked when we created it */
1345 assert(oldstate == PyGILState_UNLOCKED);
1346 PyThreadState_Clear(tcur);
1347 /* Delete the thread-state. Note this releases the GIL too!
1348 * It's vital that the GIL be held here, to avoid shutdown
1349 * races; see bugs 225673 and 1061968 (that nasty bug has a
1350 * habit of coming back).
1351 */
1352 _PyThreadState_DeleteCurrent(runtime);
1353 }
1354 /* Release the lock if necessary */
1355 else if (oldstate == PyGILState_UNLOCKED)
1356 PyEval_SaveThread();
1357 }
1358
1359
1360 /**************************/
1361 /* cross-interpreter data */
1362 /**************************/
1363
1364 /* cross-interpreter data */
1365
1366 crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1367
1368 /* This is a separate func from _PyCrossInterpreterData_Lookup in order
1369 to keep the registry code separate. */
1370 static crossinterpdatafunc
_lookup_getdata(PyObject * obj)1371 _lookup_getdata(PyObject *obj)
1372 {
1373 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1374 if (getdata == NULL && PyErr_Occurred() == 0)
1375 PyErr_Format(PyExc_ValueError,
1376 "%S does not support cross-interpreter data", obj);
1377 return getdata;
1378 }
1379
1380 int
_PyObject_CheckCrossInterpreterData(PyObject * obj)1381 _PyObject_CheckCrossInterpreterData(PyObject *obj)
1382 {
1383 crossinterpdatafunc getdata = _lookup_getdata(obj);
1384 if (getdata == NULL) {
1385 return -1;
1386 }
1387 return 0;
1388 }
1389
1390 static int
_check_xidata(_PyCrossInterpreterData * data)1391 _check_xidata(_PyCrossInterpreterData *data)
1392 {
1393 // data->data can be anything, including NULL, so we don't check it.
1394
1395 // data->obj may be NULL, so we don't check it.
1396
1397 if (data->interp < 0) {
1398 PyErr_SetString(PyExc_SystemError, "missing interp");
1399 return -1;
1400 }
1401
1402 if (data->new_object == NULL) {
1403 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1404 return -1;
1405 }
1406
1407 // data->free may be NULL, so we don't check it.
1408
1409 return 0;
1410 }
1411
1412 int
_PyObject_GetCrossInterpreterData(PyObject * obj,_PyCrossInterpreterData * data)1413 _PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1414 {
1415 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
1416 // to check the result for NULL.
1417 PyInterpreterState *interp = _PyInterpreterState_Get();
1418
1419 // Reset data before re-populating.
1420 *data = (_PyCrossInterpreterData){0};
1421 data->free = PyMem_RawFree; // Set a default that may be overridden.
1422
1423 // Call the "getdata" func for the object.
1424 Py_INCREF(obj);
1425 crossinterpdatafunc getdata = _lookup_getdata(obj);
1426 if (getdata == NULL) {
1427 Py_DECREF(obj);
1428 return -1;
1429 }
1430 int res = getdata(obj, data);
1431 Py_DECREF(obj);
1432 if (res != 0) {
1433 return -1;
1434 }
1435
1436 // Fill in the blanks and validate the result.
1437 data->interp = interp->id;
1438 if (_check_xidata(data) != 0) {
1439 _PyCrossInterpreterData_Release(data);
1440 return -1;
1441 }
1442
1443 return 0;
1444 }
1445
1446 static void
_release_xidata(void * arg)1447 _release_xidata(void *arg)
1448 {
1449 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1450 if (data->free != NULL) {
1451 data->free(data->data);
1452 }
1453 Py_XDECREF(data->obj);
1454 }
1455
1456 static void
_call_in_interpreter(struct _gilstate_runtime_state * gilstate,PyInterpreterState * interp,void (* func)(void *),void * arg)1457 _call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1458 PyInterpreterState *interp,
1459 void (*func)(void *), void *arg)
1460 {
1461 /* We would use Py_AddPendingCall() if it weren't specific to the
1462 * main interpreter (see bpo-33608). In the meantime we take a
1463 * naive approach.
1464 */
1465 PyThreadState *save_tstate = NULL;
1466 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1467 // XXX Using the "head" thread isn't strictly correct.
1468 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1469 // XXX Possible GILState issues?
1470 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1471 }
1472
1473 func(arg);
1474
1475 // Switch back.
1476 if (save_tstate != NULL) {
1477 _PyThreadState_Swap(gilstate, save_tstate);
1478 }
1479 }
1480
1481 void
_PyCrossInterpreterData_Release(_PyCrossInterpreterData * data)1482 _PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1483 {
1484 if (data->data == NULL && data->obj == NULL) {
1485 // Nothing to release!
1486 return;
1487 }
1488
1489 // Switch to the original interpreter.
1490 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1491 if (interp == NULL) {
1492 // The intepreter was already destroyed.
1493 if (data->free != NULL) {
1494 // XXX Someone leaked some memory...
1495 }
1496 return;
1497 }
1498
1499 // "Release" the data and/or the object.
1500 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1501 _call_in_interpreter(gilstate, interp, _release_xidata, data);
1502 }
1503
1504 PyObject *
_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData * data)1505 _PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1506 {
1507 return data->new_object(data);
1508 }
1509
1510 /* registry of {type -> crossinterpdatafunc} */
1511
1512 /* For now we use a global registry of shareable classes. An
1513 alternative would be to add a tp_* slot for a class's
1514 crossinterpdatafunc. It would be simpler and more efficient. */
1515
1516 static int
_register_xidata(struct _xidregistry * xidregistry,PyTypeObject * cls,crossinterpdatafunc getdata)1517 _register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1518 crossinterpdatafunc getdata)
1519 {
1520 // Note that we effectively replace already registered classes
1521 // rather than failing.
1522 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1523 if (newhead == NULL)
1524 return -1;
1525 newhead->cls = cls;
1526 newhead->getdata = getdata;
1527 newhead->next = xidregistry->head;
1528 xidregistry->head = newhead;
1529 return 0;
1530 }
1531
1532 static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
1533
1534 int
_PyCrossInterpreterData_RegisterClass(PyTypeObject * cls,crossinterpdatafunc getdata)1535 _PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
1536 crossinterpdatafunc getdata)
1537 {
1538 if (!PyType_Check(cls)) {
1539 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1540 return -1;
1541 }
1542 if (getdata == NULL) {
1543 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1544 return -1;
1545 }
1546
1547 // Make sure the class isn't ever deallocated.
1548 Py_INCREF((PyObject *)cls);
1549
1550 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1551 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1552 if (xidregistry->head == NULL) {
1553 _register_builtins_for_crossinterpreter_data(xidregistry);
1554 }
1555 int res = _register_xidata(xidregistry, cls, getdata);
1556 PyThread_release_lock(xidregistry->mutex);
1557 return res;
1558 }
1559
1560 /* Cross-interpreter objects are looked up by exact match on the class.
1561 We can reassess this policy when we move from a global registry to a
1562 tp_* slot. */
1563
1564 crossinterpdatafunc
_PyCrossInterpreterData_Lookup(PyObject * obj)1565 _PyCrossInterpreterData_Lookup(PyObject *obj)
1566 {
1567 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1568 PyObject *cls = PyObject_Type(obj);
1569 crossinterpdatafunc getdata = NULL;
1570 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1571 struct _xidregitem *cur = xidregistry->head;
1572 if (cur == NULL) {
1573 _register_builtins_for_crossinterpreter_data(xidregistry);
1574 cur = xidregistry->head;
1575 }
1576 for(; cur != NULL; cur = cur->next) {
1577 if (cur->cls == (PyTypeObject *)cls) {
1578 getdata = cur->getdata;
1579 break;
1580 }
1581 }
1582 Py_DECREF(cls);
1583 PyThread_release_lock(xidregistry->mutex);
1584 return getdata;
1585 }
1586
1587 /* cross-interpreter data for builtin types */
1588
1589 struct _shared_bytes_data {
1590 char *bytes;
1591 Py_ssize_t len;
1592 };
1593
1594 static PyObject *
_new_bytes_object(_PyCrossInterpreterData * data)1595 _new_bytes_object(_PyCrossInterpreterData *data)
1596 {
1597 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1598 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
1599 }
1600
1601 static int
_bytes_shared(PyObject * obj,_PyCrossInterpreterData * data)1602 _bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1603 {
1604 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1605 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1606 return -1;
1607 }
1608 data->data = (void *)shared;
1609 Py_INCREF(obj);
1610 data->obj = obj; // Will be "released" (decref'ed) when data released.
1611 data->new_object = _new_bytes_object;
1612 data->free = PyMem_Free;
1613 return 0;
1614 }
1615
1616 struct _shared_str_data {
1617 int kind;
1618 const void *buffer;
1619 Py_ssize_t len;
1620 };
1621
1622 static PyObject *
_new_str_object(_PyCrossInterpreterData * data)1623 _new_str_object(_PyCrossInterpreterData *data)
1624 {
1625 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1626 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1627 }
1628
1629 static int
_str_shared(PyObject * obj,_PyCrossInterpreterData * data)1630 _str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1631 {
1632 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1633 shared->kind = PyUnicode_KIND(obj);
1634 shared->buffer = PyUnicode_DATA(obj);
1635 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1636 data->data = (void *)shared;
1637 Py_INCREF(obj);
1638 data->obj = obj; // Will be "released" (decref'ed) when data released.
1639 data->new_object = _new_str_object;
1640 data->free = PyMem_Free;
1641 return 0;
1642 }
1643
1644 static PyObject *
_new_long_object(_PyCrossInterpreterData * data)1645 _new_long_object(_PyCrossInterpreterData *data)
1646 {
1647 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
1648 }
1649
1650 static int
_long_shared(PyObject * obj,_PyCrossInterpreterData * data)1651 _long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1652 {
1653 /* Note that this means the size of shareable ints is bounded by
1654 * sys.maxsize. Hence on 32-bit architectures that is half the
1655 * size of maximum shareable ints on 64-bit.
1656 */
1657 Py_ssize_t value = PyLong_AsSsize_t(obj);
1658 if (value == -1 && PyErr_Occurred()) {
1659 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1660 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1661 }
1662 return -1;
1663 }
1664 data->data = (void *)value;
1665 data->obj = NULL;
1666 data->new_object = _new_long_object;
1667 data->free = NULL;
1668 return 0;
1669 }
1670
1671 static PyObject *
_new_none_object(_PyCrossInterpreterData * data)1672 _new_none_object(_PyCrossInterpreterData *data)
1673 {
1674 // XXX Singleton refcounts are problematic across interpreters...
1675 Py_INCREF(Py_None);
1676 return Py_None;
1677 }
1678
1679 static int
_none_shared(PyObject * obj,_PyCrossInterpreterData * data)1680 _none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1681 {
1682 data->data = NULL;
1683 // data->obj remains NULL
1684 data->new_object = _new_none_object;
1685 data->free = NULL; // There is nothing to free.
1686 return 0;
1687 }
1688
1689 static void
_register_builtins_for_crossinterpreter_data(struct _xidregistry * xidregistry)1690 _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
1691 {
1692 // None
1693 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1694 Py_FatalError("could not register None for cross-interpreter sharing");
1695 }
1696
1697 // int
1698 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
1699 Py_FatalError("could not register int for cross-interpreter sharing");
1700 }
1701
1702 // bytes
1703 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
1704 Py_FatalError("could not register bytes for cross-interpreter sharing");
1705 }
1706
1707 // str
1708 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
1709 Py_FatalError("could not register str for cross-interpreter sharing");
1710 }
1711 }
1712
1713
1714 #ifdef __cplusplus
1715 }
1716 #endif
1717