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