blob: c791b239993833bb9eb4a2152ecee64d2f56610f [file] [log] [blame]
Guido van Rossuma027efa1997-05-05 20:56:21 +00001
2/* Thread and interpreter state structures and their interfaces */
3
4#include "Python.h"
Victor Stinner09532fe2019-05-10 23:39:09 +02005#include "pycore_ceval.h"
Victor Stinner331a6a52019-05-27 16:39:22 +02006#include "pycore_initconfig.h"
Victor Stinner41010182020-12-26 01:45:43 +01007#include "pycore_object.h" // _PyType_InitCache()
Victor Stinner0e427c62020-03-25 21:22:55 +01008#include "pycore_pyerrors.h"
9#include "pycore_pylifecycle.h"
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +020010#include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
Victor Stinnere5014be2020-04-14 17:52:15 +020011#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner71a35222020-03-26 22:46:14 +010012#include "pycore_sysmodule.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +000013
Tim Peters84705582004-10-10 02:47:33 +000014/* --------------------------------------------------------------------------
15CAUTION
16
Victor Stinner1a7425f2013-07-07 16:25:15 +020017Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
18number of these functions are advertised as safe to call when the GIL isn't
19held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
20debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
21to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000022-------------------------------------------------------------------------- */
23
Martin v. Löwisf0473d52001-07-18 16:17:16 +000024#ifdef HAVE_DLOPEN
25#ifdef HAVE_DLFCN_H
26#include <dlfcn.h>
27#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030028#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000029#define RTLD_LAZY 1
30#endif
31#endif
32
Benjamin Peterson43162b82012-04-13 11:58:27 -040033#ifdef __cplusplus
34extern "C" {
35#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000036
Victor Stinner10c8e6a2019-04-26 01:53:18 +020037#define _PyRuntimeGILState_GetThreadState(gilstate) \
38 ((PyThreadState*)_Py_atomic_load_relaxed(&(gilstate)->tstate_current))
39#define _PyRuntimeGILState_SetThreadState(gilstate, value) \
40 _Py_atomic_store_relaxed(&(gilstate)->tstate_current, \
41 (uintptr_t)(value))
42
43/* Forward declarations */
44static PyThreadState *_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate);
Victor Stinner9da74302019-11-20 11:17:17 +010045static void _PyThreadState_Delete(PyThreadState *tstate, int check_current);
Victor Stinner10c8e6a2019-04-26 01:53:18 +020046
47
Victor Stinner331a6a52019-05-27 16:39:22 +020048static PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010049_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060050{
Steve Dowerb82e17e2019-05-23 08:45:22 -070051 /* We preserve the hook across init, because there is
52 currently no public API to set it between runtime
53 initialization and interpreter initialization. */
54 void *open_code_hook = runtime->open_code_hook;
55 void *open_code_userdata = runtime->open_code_userdata;
56 _Py_AuditHookEntry *audit_hook_head = runtime->audit_hook_head;
57
Eric Snow2ebc5ce2017-09-07 23:51:28 -060058 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010059
Steve Dowerb82e17e2019-05-23 08:45:22 -070060 runtime->open_code_hook = open_code_hook;
61 runtime->open_code_userdata = open_code_userdata;
62 runtime->audit_hook_head = audit_hook_head;
63
Victor Stinnerdab84232020-03-17 18:56:44 +010064 _PyEval_InitRuntimeState(&runtime->ceval);
Victor Stinner441b10c2019-09-28 04:28:35 +020065
Victor Stinner3c30a762019-10-01 10:56:37 +020066 PyPreConfig_InitPythonConfig(&runtime->preconfig);
Michael W. Hudson188d4362005-06-20 16:52:57 +000067
Eric Snow2ebc5ce2017-09-07 23:51:28 -060068 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080069
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090070 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
71 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080072 Py_tss_t initial = Py_tss_NEEDS_INIT;
73 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000074
Eric Snow2ebc5ce2017-09-07 23:51:28 -060075 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080076 if (runtime->interpreters.mutex == NULL) {
Victor Stinnerba3d67c2020-12-26 00:41:46 +010077 return _PyStatus_NO_MEMORY();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080078 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060079 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070080
81 runtime->xidregistry.mutex = PyThread_allocate_lock();
82 if (runtime->xidregistry.mutex == NULL) {
Victor Stinnerba3d67c2020-12-26 00:41:46 +010083 return _PyStatus_NO_MEMORY();
Eric Snow7f8bfc92018-01-29 18:23:44 -070084 }
85
Eric Snow8479a342019-03-08 23:44:33 -070086 // Set it to the ID of the main thread of the main interpreter.
87 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070088
Victor Stinnerba3d67c2020-12-26 00:41:46 +010089 runtime->unicode_ids.lock = PyThread_allocate_lock();
90 if (runtime->unicode_ids.lock == NULL) {
91 return _PyStatus_NO_MEMORY();
92 }
93 runtime->unicode_ids.next_index = 0;
94
Victor Stinner331a6a52019-05-27 16:39:22 +020095 return _PyStatus_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060096}
Eric Snow05351c12017-09-05 21:43:08 -070097
Victor Stinner331a6a52019-05-27 16:39:22 +020098PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010099_PyRuntimeState_Init(_PyRuntimeState *runtime)
100{
101 /* Force default allocator, since _PyRuntimeState_Fini() must
102 use the same allocator than this function. */
103 PyMemAllocatorEx old_alloc;
104 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
105
Victor Stinner331a6a52019-05-27 16:39:22 +0200106 PyStatus status = _PyRuntimeState_Init_impl(runtime);
Victor Stinner5d39e042017-11-29 17:20:38 +0100107
108 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinner331a6a52019-05-27 16:39:22 +0200109 return status;
Victor Stinner5d39e042017-11-29 17:20:38 +0100110}
111
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600112void
113_PyRuntimeState_Fini(_PyRuntimeState *runtime)
114{
Victor Stinner5d39e042017-11-29 17:20:38 +0100115 /* Force the allocator used by _PyRuntimeState_Init(). */
116 PyMemAllocatorEx old_alloc;
117 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerba3d67c2020-12-26 00:41:46 +0100118#define FREE_LOCK(LOCK) \
119 if (LOCK != NULL) { \
120 PyThread_free_lock(LOCK); \
121 LOCK = NULL; \
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600122 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800123
Victor Stinnerba3d67c2020-12-26 00:41:46 +0100124 FREE_LOCK(runtime->interpreters.mutex);
125 FREE_LOCK(runtime->xidregistry.mutex);
126 FREE_LOCK(runtime->unicode_ids.lock);
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100127
Victor Stinnerba3d67c2020-12-26 00:41:46 +0100128#undef FREE_LOCK
Victor Stinnerccb04422017-11-16 03:20:31 -0800129 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600130}
131
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900132#ifdef HAVE_FORK
Eric Snow8479a342019-03-08 23:44:33 -0700133/* This function is called from PyOS_AfterFork_Child to ensure that
Victor Stinner26881c82020-06-02 15:51:37 +0200134 newly created child processes do not share locks with the parent. */
135PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200136_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700137{
138 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200139 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700140
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200141 /* Force default allocator, since _PyRuntimeState_Fini() must
142 use the same allocator than this function. */
143 PyMemAllocatorEx old_alloc;
144 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
145
Victor Stinner26881c82020-06-02 15:51:37 +0200146 int reinit_interp = _PyThread_at_fork_reinit(&runtime->interpreters.mutex);
147 int reinit_main_id = _PyThread_at_fork_reinit(&runtime->interpreters.main->id_mutex);
148 int reinit_xidregistry = _PyThread_at_fork_reinit(&runtime->xidregistry.mutex);
Victor Stinnerba3d67c2020-12-26 00:41:46 +0100149 int reinit_unicode_ids = _PyThread_at_fork_reinit(&runtime->unicode_ids.lock);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200150
151 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
152
Victor Stinner26881c82020-06-02 15:51:37 +0200153 if (reinit_interp < 0
154 || reinit_main_id < 0
Victor Stinnerba3d67c2020-12-26 00:41:46 +0100155 || reinit_xidregistry < 0
156 || reinit_unicode_ids < 0)
Victor Stinner26881c82020-06-02 15:51:37 +0200157 {
158 return _PyStatus_ERR("Failed to reinitialize runtime locks");
Eric Snow8479a342019-03-08 23:44:33 -0700159
Eric Snow8479a342019-03-08 23:44:33 -0700160 }
Victor Stinner26881c82020-06-02 15:51:37 +0200161 return _PyStatus_OK();
Eric Snow8479a342019-03-08 23:44:33 -0700162}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900163#endif
Eric Snow8479a342019-03-08 23:44:33 -0700164
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200165#define HEAD_LOCK(runtime) \
166 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
167#define HEAD_UNLOCK(runtime) \
168 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700169
Victor Stinner8bb32302019-04-24 16:47:40 +0200170/* Forward declaration */
171static void _PyGILState_NoteThreadState(
172 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000173
Victor Stinner331a6a52019-05-27 16:39:22 +0200174PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600175_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700176{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200177 struct pyinterpreters *interpreters = &runtime->interpreters;
178 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100179
180 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
181 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200182 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100183 /* Force default allocator, since _PyRuntimeState_Fini() must
184 use the same allocator than this function. */
185 PyMemAllocatorEx old_alloc;
186 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
187
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200188 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100189
190 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
191
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200192 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200193 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800194 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600195 }
Victor Stinner5d926472018-03-06 14:31:37 +0100196
Victor Stinner331a6a52019-05-27 16:39:22 +0200197 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700198}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000199
200PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000201PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000202{
Victor Stinner71a35222020-03-26 22:46:14 +0100203 PyThreadState *tstate = _PyThreadState_GET();
204 /* tstate is NULL when Py_InitializeFromConfig() calls
205 PyInterpreterState_New() to create the main interpreter. */
206 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_New", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700207 return NULL;
208 }
209
Andy Lester7668a8b2020-03-24 23:26:44 -0500210 PyInterpreterState *interp = PyMem_RawCalloc(1, sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100211 if (interp == NULL) {
212 return NULL;
213 }
214
Eric Snow4c6955e2018-02-16 18:53:40 -0700215 interp->id_refcount = -1;
Victor Stinner022be022019-05-22 23:58:50 +0200216
Victor Stinner71a35222020-03-26 22:46:14 +0100217 /* Don't get runtime from tstate since tstate can be NULL */
Victor Stinner01b1cc12019-11-20 02:27:56 +0100218 _PyRuntimeState *runtime = &_PyRuntime;
219 interp->runtime = runtime;
220
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200221 if (_PyEval_InitState(&interp->ceval) < 0) {
222 goto out_of_memory;
223 }
224
Victor Stinner72474072019-11-20 12:25:50 +0100225 _PyGC_InitState(&interp->gc);
Victor Stinner8462a492019-10-01 12:06:16 +0200226 PyConfig_InitPythonConfig(&interp->config);
Victor Stinner41010182020-12-26 01:45:43 +0100227 _PyType_InitCache(interp);
Victor Stinner022be022019-05-22 23:58:50 +0200228
Victor Stinnerd4341102017-11-23 00:12:09 +0100229 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000230#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300231#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100232 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000233#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100234 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000235#endif
236#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000237
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200238 struct pyinterpreters *interpreters = &runtime->interpreters;
239
240 HEAD_LOCK(runtime);
241 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100242 /* overflow or Py_Initialize() not called! */
Victor Stinner71a35222020-03-26 22:46:14 +0100243 if (tstate != NULL) {
244 _PyErr_SetString(tstate, PyExc_RuntimeError,
245 "failed to get an interpreter ID");
246 }
Pablo Galindo95d630e2018-08-31 22:49:29 +0100247 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100248 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100249 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200250 else {
251 interp->id = interpreters->next_id;
252 interpreters->next_id += 1;
253 interp->next = interpreters->head;
254 if (interpreters->main == NULL) {
255 interpreters->main = interp;
256 }
257 interpreters->head = interp;
258 }
259 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000260
Pablo Galindo95d630e2018-08-31 22:49:29 +0100261 if (interp == NULL) {
262 return NULL;
263 }
264
Yury Selivanovf23746a2018-01-22 19:11:18 -0500265 interp->tstate_next_unique_id = 0;
266
Steve Dowerb82e17e2019-05-23 08:45:22 -0700267 interp->audit_hooks = NULL;
268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 return interp;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200270
271out_of_memory:
272 if (tstate != NULL) {
273 _PyErr_NoMemory(tstate);
274 }
275
276 PyMem_RawFree(interp);
277 return NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000278}
279
280
Victor Stinnereba5bf22020-10-30 22:51:02 +0100281static void
282interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000283{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100284 _PyRuntimeState *runtime = interp->runtime;
285
Victor Stinner71a35222020-03-26 22:46:14 +0100286 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_Clear", NULL) < 0) {
287 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700288 }
289
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200290 HEAD_LOCK(runtime);
291 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200293 }
294 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700295
296 Py_CLEAR(interp->audit_hooks);
297
Victor Stinner331a6a52019-05-27 16:39:22 +0200298 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 Py_CLEAR(interp->codec_search_path);
300 Py_CLEAR(interp->codec_search_cache);
301 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700302 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 Py_CLEAR(interp->modules_by_index);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200304 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400305 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300306 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600307 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200308#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
Victor Stinnerfd957c12020-11-03 18:07:15 +0100313
314 _PyAST_Fini(interp);
315 _PyWarnings_Fini(interp);
Victor Stinnerb8fa1352020-12-15 14:34:19 +0100316 _PyAtExit_Fini(interp);
Victor Stinnerfd957c12020-11-03 18:07:15 +0100317
318 // All Python types must be destroyed before the last GC collection. Python
319 // types create a reference cycle to themselves in their in their
320 // PyTypeObject.tp_mro member (the tuple contains the type).
Victor Stinnereba5bf22020-10-30 22:51:02 +0100321
322 /* Last garbage collection on this interpreter */
323 _PyGC_CollectNoFail(tstate);
Victor Stinnereba5bf22020-10-30 22:51:02 +0100324 _PyGC_Fini(tstate);
325
Hai Shi8ecc0c42020-08-13 05:23:30 +0800326 /* We don't clear sysdict and builtins until the end of this function.
327 Because clearing other attributes can execute arbitrary Python code
328 which requires sysdict and builtins. */
329 PyDict_Clear(interp->sysdict);
330 PyDict_Clear(interp->builtins);
331 Py_CLEAR(interp->sysdict);
332 Py_CLEAR(interp->builtins);
333
Eric Snow5be45a62019-03-08 22:47:07 -0700334 // XXX Once we have one allocator per interpreter (i.e.
335 // per-interpreter GC) we must ensure that all of the interpreter's
336 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000337}
338
339
Victor Stinnereba5bf22020-10-30 22:51:02 +0100340void
341PyInterpreterState_Clear(PyInterpreterState *interp)
342{
343 // Use the current Python thread state to call audit hooks and to collect
344 // garbage. It can be different than the current Python thread state
345 // of 'interp'.
346 PyThreadState *current_tstate = _PyThreadState_GET();
347
348 interpreter_clear(interp, current_tstate);
349}
350
351
352void
353_PyInterpreterState_Clear(PyThreadState *tstate)
354{
355 interpreter_clear(tstate->interp, tstate);
356}
357
358
Guido van Rossum25ce5661997-08-02 03:10:38 +0000359static void
Victor Stinner9da74302019-11-20 11:17:17 +0100360zapthreads(PyInterpreterState *interp, int check_current)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000361{
Victor Stinner9da74302019-11-20 11:17:17 +0100362 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 /* No need to lock the mutex here because this should only happen
364 when the threads are all really dead (XXX famous last words). */
Victor Stinner9da74302019-11-20 11:17:17 +0100365 while ((tstate = interp->tstate_head) != NULL) {
366 _PyThreadState_Delete(tstate, check_current);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000368}
369
370
Victor Stinner01b1cc12019-11-20 02:27:56 +0100371void
372PyInterpreterState_Delete(PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200373{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100374 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200375 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner9da74302019-11-20 11:17:17 +0100376 zapthreads(interp, 0);
377
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200378 _PyEval_FiniState(&interp->ceval);
379
Victor Stinner9da74302019-11-20 11:17:17 +0100380 /* Delete current thread. After this, many C API calls become crashy. */
381 _PyThreadState_Swap(&runtime->gilstate, NULL);
382
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200383 HEAD_LOCK(runtime);
384 PyInterpreterState **p;
385 for (p = &interpreters->head; ; p = &(*p)->next) {
386 if (*p == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100387 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200388 }
389 if (*p == interp) {
390 break;
391 }
392 }
393 if (interp->tstate_head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100394 Py_FatalError("remaining threads");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200395 }
396 *p = interp->next;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200397
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200398 if (interpreters->main == interp) {
399 interpreters->main = NULL;
400 if (interpreters->head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100401 Py_FatalError("remaining subinterpreters");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200402 }
403 }
404 HEAD_UNLOCK(runtime);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200405
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200406 if (interp->id_mutex != NULL) {
407 PyThread_free_lock(interp->id_mutex);
408 }
409 PyMem_RawFree(interp);
410}
411
412
Victor Stinner26881c82020-06-02 15:51:37 +0200413#ifdef HAVE_FORK
Eric Snow59032962018-09-14 14:17:20 -0700414/*
415 * Delete all interpreter states except the main interpreter. If there
416 * is a current interpreter state, it *must* be the main interpreter.
417 */
Victor Stinner26881c82020-06-02 15:51:37 +0200418PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200419_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700420{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200421 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200422 struct pyinterpreters *interpreters = &runtime->interpreters;
423
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200424 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200425 if (tstate != NULL && tstate->interp != interpreters->main) {
Victor Stinner26881c82020-06-02 15:51:37 +0200426 return _PyStatus_ERR("not main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700427 }
428
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200429 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200430 PyInterpreterState *interp = interpreters->head;
431 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100432 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200433 if (interp == interpreters->main) {
434 interpreters->main->next = NULL;
435 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100436 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700437 continue;
438 }
439
Victor Stinner01b1cc12019-11-20 02:27:56 +0100440 PyInterpreterState_Clear(interp); // XXX must activate?
Victor Stinner9da74302019-11-20 11:17:17 +0100441 zapthreads(interp, 1);
Eric Snow59032962018-09-14 14:17:20 -0700442 if (interp->id_mutex != NULL) {
443 PyThread_free_lock(interp->id_mutex);
444 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100445 PyInterpreterState *prev_interp = interp;
446 interp = interp->next;
447 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700448 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200449 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700450
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200451 if (interpreters->head == NULL) {
Victor Stinner26881c82020-06-02 15:51:37 +0200452 return _PyStatus_ERR("missing main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700453 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200454 _PyThreadState_Swap(gilstate, tstate);
Victor Stinner26881c82020-06-02 15:51:37 +0200455 return _PyStatus_OK();
Eric Snow59032962018-09-14 14:17:20 -0700456}
Victor Stinner26881c82020-06-02 15:51:37 +0200457#endif
Eric Snow59032962018-09-14 14:17:20 -0700458
459
Victor Stinnercaba55b2018-08-03 15:33:52 +0200460PyInterpreterState *
Victor Stinnerbe793732020-03-13 18:15:33 +0100461PyInterpreterState_Get(void)
Victor Stinnercaba55b2018-08-03 15:33:52 +0200462{
Victor Stinner50b48572018-11-01 01:51:40 +0100463 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200464 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200465 PyInterpreterState *interp = tstate->interp;
466 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100467 Py_FatalError("no current interpreter");
Victor Stinnercaba55b2018-08-03 15:33:52 +0200468 }
469 return interp;
470}
471
472
Eric Snowe3774162017-05-22 19:46:40 -0700473int64_t
474PyInterpreterState_GetID(PyInterpreterState *interp)
475{
476 if (interp == NULL) {
477 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
478 return -1;
479 }
480 return interp->id;
481}
482
483
Eric Snow5be45a62019-03-08 22:47:07 -0700484static PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200485interp_look_up_id(_PyRuntimeState *runtime, int64_t requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700486{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200487 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100488 while (interp != NULL) {
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200489 int64_t id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700490 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100491 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700492 }
493 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100494 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700495 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100496 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700497 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100498 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700499}
500
Eric Snow5be45a62019-03-08 22:47:07 -0700501PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200502_PyInterpreterState_LookUpID(int64_t requested_id)
Eric Snow5be45a62019-03-08 22:47:07 -0700503{
504 PyInterpreterState *interp = NULL;
505 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200506 _PyRuntimeState *runtime = &_PyRuntime;
507 HEAD_LOCK(runtime);
508 interp = interp_look_up_id(runtime, requested_id);
509 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700510 }
511 if (interp == NULL && !PyErr_Occurred()) {
512 PyErr_Format(PyExc_RuntimeError,
513 "unrecognized interpreter ID %lld", requested_id);
514 }
515 return interp;
516}
517
Eric Snow4c6955e2018-02-16 18:53:40 -0700518
519int
520_PyInterpreterState_IDInitref(PyInterpreterState *interp)
521{
522 if (interp->id_mutex != NULL) {
523 return 0;
524 }
525 interp->id_mutex = PyThread_allocate_lock();
526 if (interp->id_mutex == NULL) {
527 PyErr_SetString(PyExc_RuntimeError,
528 "failed to create init interpreter ID mutex");
529 return -1;
530 }
531 interp->id_refcount = 0;
532 return 0;
533}
534
535
536void
537_PyInterpreterState_IDIncref(PyInterpreterState *interp)
538{
539 if (interp->id_mutex == NULL) {
540 return;
541 }
542 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
543 interp->id_refcount += 1;
544 PyThread_release_lock(interp->id_mutex);
545}
546
547
548void
549_PyInterpreterState_IDDecref(PyInterpreterState *interp)
550{
551 if (interp->id_mutex == NULL) {
552 return;
553 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200554 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700555 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
556 assert(interp->id_refcount != 0);
557 interp->id_refcount -= 1;
558 int64_t refcount = interp->id_refcount;
559 PyThread_release_lock(interp->id_mutex);
560
Eric Snowc11183c2019-03-15 16:35:46 -0600561 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700562 // XXX Using the "head" thread isn't strictly correct.
563 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
564 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200565 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700566 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200567 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700568 }
569}
570
Eric Snowc11183c2019-03-15 16:35:46 -0600571int
572_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
573{
574 return interp->requires_idref;
575}
576
577void
578_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
579{
580 interp->requires_idref = required ? 1 : 0;
581}
582
Eric Snowc11183c2019-03-15 16:35:46 -0600583PyObject *
584_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
585{
586 if (interp->modules == NULL) {
587 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
588 return NULL;
589 }
590 return PyMapping_GetItemString(interp->modules, "__main__");
591}
592
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600593PyObject *
594PyInterpreterState_GetDict(PyInterpreterState *interp)
595{
596 if (interp->dict == NULL) {
597 interp->dict = PyDict_New();
598 if (interp->dict == NULL) {
599 PyErr_Clear();
600 }
601 }
602 /* Returning NULL means no per-interpreter dict is available. */
603 return interp->dict;
604}
605
Victor Stinner45b9be52010-03-03 23:28:07 +0000606static PyThreadState *
607new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000608{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100609 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200610 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200611 if (tstate == NULL) {
612 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000614
Victor Stinner8bb32302019-04-24 16:47:40 +0200615 tstate->interp = interp;
616
617 tstate->frame = NULL;
618 tstate->recursion_depth = 0;
Mark Shannon4e7a69b2020-12-02 13:30:55 +0000619 tstate->recursion_headroom = 0;
Victor Stinner8bb32302019-04-24 16:47:40 +0200620 tstate->stackcheck_counter = 0;
621 tstate->tracing = 0;
622 tstate->use_tracing = 0;
623 tstate->gilstate_counter = 0;
624 tstate->async_exc = NULL;
625 tstate->thread_id = PyThread_get_thread_ident();
626
627 tstate->dict = NULL;
628
629 tstate->curexc_type = NULL;
630 tstate->curexc_value = NULL;
631 tstate->curexc_traceback = NULL;
632
633 tstate->exc_state.exc_type = NULL;
634 tstate->exc_state.exc_value = NULL;
635 tstate->exc_state.exc_traceback = NULL;
636 tstate->exc_state.previous_item = NULL;
637 tstate->exc_info = &tstate->exc_state;
638
639 tstate->c_profilefunc = NULL;
640 tstate->c_tracefunc = NULL;
641 tstate->c_profileobj = NULL;
642 tstate->c_traceobj = NULL;
643
644 tstate->trash_delete_nesting = 0;
645 tstate->trash_delete_later = NULL;
646 tstate->on_delete = NULL;
647 tstate->on_delete_data = NULL;
648
649 tstate->coroutine_origin_tracking_depth = 0;
650
Victor Stinner8bb32302019-04-24 16:47:40 +0200651 tstate->async_gen_firstiter = NULL;
652 tstate->async_gen_finalizer = NULL;
653
654 tstate->context = NULL;
655 tstate->context_ver = 1;
656
Victor Stinner8bb32302019-04-24 16:47:40 +0200657 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100658 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200659 }
660
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200661 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100662 tstate->id = ++interp->tstate_next_unique_id;
Victor Stinner8bb32302019-04-24 16:47:40 +0200663 tstate->prev = NULL;
664 tstate->next = interp->tstate_head;
665 if (tstate->next)
666 tstate->next->prev = tstate;
667 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200668 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000671}
672
Victor Stinner45b9be52010-03-03 23:28:07 +0000673PyThreadState *
674PyThreadState_New(PyInterpreterState *interp)
675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000677}
678
679PyThreadState *
680_PyThreadState_Prealloc(PyInterpreterState *interp)
681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000683}
684
685void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100686_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000687{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100688 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000689}
690
Martin v. Löwis1a214512008-06-11 05:26:20 +0000691PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200692PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000693{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200694 Py_ssize_t index = module->m_base.m_index;
Victor Stinner81a7be32020-04-14 15:14:01 +0200695 PyInterpreterState *state = _PyInterpreterState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000697 if (module->m_slots) {
698 return NULL;
699 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 if (index == 0)
701 return NULL;
702 if (state->modules_by_index == NULL)
703 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200704 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 return NULL;
706 res = PyList_GET_ITEM(state->modules_by_index, index);
707 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000708}
709
710int
Victor Stinner82c83bd2019-11-22 18:52:27 +0100711_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000712{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300713 if (!def) {
Victor Stinner71a35222020-03-26 22:46:14 +0100714 assert(_PyErr_Occurred(tstate));
Berker Peksag4b7b5652016-08-22 18:05:56 +0300715 return -1;
716 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000717 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100718 _PyErr_SetString(tstate,
719 PyExc_SystemError,
720 "PyState_AddModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000721 return -1;
722 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100723
724 PyInterpreterState *interp = tstate->interp;
725 if (!interp->modules_by_index) {
726 interp->modules_by_index = PyList_New(0);
727 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100729 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100731
732 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
733 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100735 }
736 }
737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100739 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000741}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000742
Martin v. Löwis7800f752012-06-22 12:20:55 +0200743int
744PyState_AddModule(PyObject* module, struct PyModuleDef* def)
745{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200746 if (!def) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100747 Py_FatalError("module definition is NULL");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200748 return -1;
749 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100750
751 PyThreadState *tstate = _PyThreadState_GET();
752 PyInterpreterState *interp = tstate->interp;
753 Py_ssize_t index = def->m_base.m_index;
754 if (interp->modules_by_index &&
755 index < PyList_GET_SIZE(interp->modules_by_index) &&
756 module == PyList_GET_ITEM(interp->modules_by_index, index))
757 {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100758 _Py_FatalErrorFormat(__func__, "module %p already added", module);
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100759 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200760 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100761 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200762}
763
764int
765PyState_RemoveModule(struct PyModuleDef* def)
766{
Victor Stinner71a35222020-03-26 22:46:14 +0100767 PyThreadState *tstate = _PyThreadState_GET();
768 PyInterpreterState *interp = tstate->interp;
769
Nick Coghland5cacbb2015-05-23 22:24:10 +1000770 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100771 _PyErr_SetString(tstate,
772 PyExc_SystemError,
773 "PyState_RemoveModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000774 return -1;
775 }
Victor Stinner71a35222020-03-26 22:46:14 +0100776
777 Py_ssize_t index = def->m_base.m_index;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200778 if (index == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100779 Py_FatalError("invalid module index");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200780 }
Victor Stinner71a35222020-03-26 22:46:14 +0100781 if (interp->modules_by_index == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100782 Py_FatalError("Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200783 }
Victor Stinner71a35222020-03-26 22:46:14 +0100784 if (index > PyList_GET_SIZE(interp->modules_by_index)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100785 Py_FatalError("Module index out of bounds.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200786 }
Victor Stinner71a35222020-03-26 22:46:14 +0100787
Zackery Spytz2a893432018-12-05 00:14:00 -0700788 Py_INCREF(Py_None);
Victor Stinner71a35222020-03-26 22:46:14 +0100789 return PyList_SetItem(interp->modules_by_index, index, Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200790}
791
Victor Stinner048a3562020-11-05 00:45:56 +0100792// Used by finalize_modules()
Antoine Pitrou40322e62013-08-11 00:30:09 +0200793void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200794_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200795{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200796 if (!interp->modules_by_index) {
797 return;
798 }
799
800 Py_ssize_t i;
801 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
802 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
803 if (PyModule_Check(m)) {
804 /* cleanup the saved copy of module dicts */
805 PyModuleDef *md = PyModule_GetDef(m);
806 if (md) {
807 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200808 }
809 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200810 }
811
812 /* Setting modules_by_index to NULL could be dangerous, so we
813 clear the list instead. */
814 if (PyList_SetSlice(interp->modules_by_index,
815 0, PyList_GET_SIZE(interp->modules_by_index),
816 NULL)) {
817 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200818 }
819}
820
Guido van Rossuma027efa1997-05-05 20:56:21 +0000821void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000822PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000823{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200824 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200825
Victor Stinner5804f872020-03-24 16:32:26 +0100826 if (verbose && tstate->frame != NULL) {
827 /* bpo-20526: After the main thread calls
828 _PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
829 exit when trying to take the GIL. If a thread exit in the middle of
830 _PyEval_EvalFrameDefault(), tstate->frame is not reset to its
831 previous value. It is more likely with daemon threads, but it can
832 happen with regular threads if threading._shutdown() fails
833 (ex: interrupted by CTRL+C). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 fprintf(stderr,
835 "PyThreadState_Clear: warning: thread still has a frame\n");
Victor Stinner5804f872020-03-24 16:32:26 +0100836 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000837
Victor Stinner5804f872020-03-24 16:32:26 +0100838 /* Don't clear tstate->frame: it is a borrowed reference */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 Py_CLEAR(tstate->dict);
841 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 Py_CLEAR(tstate->curexc_type);
844 Py_CLEAR(tstate->curexc_value);
845 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000846
Mark Shannonae3087c2017-10-22 22:41:51 +0100847 Py_CLEAR(tstate->exc_state.exc_type);
848 Py_CLEAR(tstate->exc_state.exc_value);
849 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300850
Mark Shannonae3087c2017-10-22 22:41:51 +0100851 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200852 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100853 fprintf(stderr,
854 "PyThreadState_Clear: warning: thread still has a generator\n");
855 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 tstate->c_profilefunc = NULL;
858 tstate->c_tracefunc = NULL;
859 Py_CLEAR(tstate->c_profileobj);
860 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400861
Yury Selivanoveb636452016-09-08 22:01:51 -0700862 Py_CLEAR(tstate->async_gen_firstiter);
863 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500864
865 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100866
867 if (tstate->on_delete != NULL) {
868 tstate->on_delete(tstate->on_delete_data);
869 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000870}
871
872
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300873/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000874static void
Victor Stinner9da74302019-11-20 11:17:17 +0100875tstate_delete_common(PyThreadState *tstate,
876 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000877{
Victor Stinner3026cad2020-06-01 16:02:40 +0200878 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200879 PyInterpreterState *interp = tstate->interp;
880 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100881 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200882 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100883 _PyRuntimeState *runtime = interp->runtime;
884
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200885 HEAD_LOCK(runtime);
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100886 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200887 tstate->prev->next = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100888 }
889 else {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200890 interp->tstate_head = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100891 }
892 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200893 tstate->next->prev = tstate->prev;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100894 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200895 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100896
Victor Stinner9da74302019-11-20 11:17:17 +0100897 if (gilstate->autoInterpreterState &&
898 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
899 {
900 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
901 }
902}
903
904
905static void
906_PyThreadState_Delete(PyThreadState *tstate, int check_current)
907{
908 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
909 if (check_current) {
910 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100911 _Py_FatalErrorFormat(__func__, "tstate %p is still current", tstate);
Victor Stinner9da74302019-11-20 11:17:17 +0100912 }
913 }
914 tstate_delete_common(tstate, gilstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100915 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000916}
917
918
Victor Stinner01b1cc12019-11-20 02:27:56 +0100919void
920PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000921{
Victor Stinner9da74302019-11-20 11:17:17 +0100922 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200923}
924
925
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300926void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100927_PyThreadState_DeleteCurrent(PyThreadState *tstate)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200928{
Victor Stinner3026cad2020-06-01 16:02:40 +0200929 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100930 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner9da74302019-11-20 11:17:17 +0100931 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200932 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100933 _PyEval_ReleaseLock(tstate);
934 PyMem_RawFree(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000935}
Guido van Rossum29757862001-01-23 01:46:06 +0000936
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300937void
938PyThreadState_DeleteCurrent(void)
939{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100940 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
941 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
942 _PyThreadState_DeleteCurrent(tstate);
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300943}
944
Guido van Rossum29757862001-01-23 01:46:06 +0000945
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200946/*
947 * Delete all thread states except the one passed as argument.
948 * Note that, if there is a current thread state, it *must* be the one
949 * passed as argument. Also, this won't touch any other interpreters
950 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000951 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200952 */
953void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200954_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200955{
956 PyInterpreterState *interp = tstate->interp;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100957
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200958 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200959 /* Remove all thread states, except tstate, from the linked list of
960 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200961 without holding the lock. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100962 PyThreadState *list = interp->tstate_head;
963 if (list == tstate) {
964 list = tstate->next;
965 }
966 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200967 tstate->prev->next = tstate->next;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100968 }
969 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200970 tstate->next->prev = tstate->prev;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100971 }
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200972 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200973 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200974 HEAD_UNLOCK(runtime);
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100975
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200976 /* Clear and deallocate all stale thread states. Even if this
977 executes Python code, we should be safe since it executes
978 in the current thread, not one of the stale threads. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100979 PyThreadState *p, *next;
980 for (p = list; p; p = next) {
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200981 next = p->next;
982 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200983 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200984 }
985}
986
987
Victor Stinnere838a932020-05-05 19:56:48 +0200988#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
989PyThreadState*
990_PyThreadState_GetTSS(void) {
991 return PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
992}
993#endif
994
995
Guido van Rossuma027efa1997-05-05 20:56:21 +0000996PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100997_PyThreadState_UncheckedGet(void)
998{
Victor Stinner50b48572018-11-01 01:51:40 +0100999 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001000}
1001
1002
1003PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001004PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +00001005{
Victor Stinner50b48572018-11-01 01:51:40 +01001006 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +02001007 _Py_EnsureTstateNotNULL(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +00001009}
1010
1011
Victor Stinner09532fe2019-05-10 23:39:09 +02001012PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001013_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +00001014{
Victor Stinnere838a932020-05-05 19:56:48 +02001015#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1016 PyThreadState *oldts = _PyThreadState_GetTSS();
1017#else
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001018 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Victor Stinnere838a932020-05-05 19:56:48 +02001019#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +00001020
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001021 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 /* It should not be possible for more than one thread state
1023 to be used for a thread. Check this the best we can in debug
1024 builds.
1025 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02001026#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 if (newts) {
1028 /* This can be called from PyEval_RestoreThread(). Similar
1029 to it, we need to ensure errno doesn't change.
1030 */
1031 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001032 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 if (check && check->interp == newts->interp && check != newts)
1034 Py_FatalError("Invalid thread state for this thread");
1035 errno = err;
1036 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001037#endif
Victor Stinnere838a932020-05-05 19:56:48 +02001038#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1039 PyThread_tss_set(&gilstate->autoTSSkey, newts);
1040#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +00001042}
Guido van Rossumede04391998-04-10 20:18:25 +00001043
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001044PyThreadState *
1045PyThreadState_Swap(PyThreadState *newts)
1046{
1047 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
1048}
1049
Guido van Rossumede04391998-04-10 20:18:25 +00001050/* An extension mechanism to store arbitrary additional per-thread state.
1051 PyThreadState_GetDict() returns a dictionary that can be used to hold such
1052 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001053 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
1054 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +00001055
1056PyObject *
Victor Stinner0e427c62020-03-25 21:22:55 +01001057_PyThreadState_GetDict(PyThreadState *tstate)
1058{
1059 assert(tstate != NULL);
1060 if (tstate->dict == NULL) {
1061 tstate->dict = PyDict_New();
1062 if (tstate->dict == NULL) {
1063 _PyErr_Clear(tstate);
1064 }
1065 }
1066 return tstate->dict;
1067}
1068
1069
1070PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001071PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +00001072{
Victor Stinner50b48572018-11-01 01:51:40 +01001073 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner0e427c62020-03-25 21:22:55 +01001074 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 }
Victor Stinner0e427c62020-03-25 21:22:55 +01001077 return _PyThreadState_GetDict(tstate);
Guido van Rossumede04391998-04-10 20:18:25 +00001078}
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001079
1080
Victor Stinner8fb02b62020-03-13 23:38:08 +01001081PyInterpreterState *
1082PyThreadState_GetInterpreter(PyThreadState *tstate)
1083{
1084 assert(tstate != NULL);
Victor Stinner8fb02b62020-03-13 23:38:08 +01001085 return tstate->interp;
1086}
1087
1088
Victor Stinner4386b902020-04-29 03:01:43 +02001089PyFrameObject*
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001090PyThreadState_GetFrame(PyThreadState *tstate)
1091{
1092 assert(tstate != NULL);
Victor Stinner4386b902020-04-29 03:01:43 +02001093 PyFrameObject *frame = tstate->frame;
1094 Py_XINCREF(frame);
1095 return frame;
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001096}
1097
1098
Victor Stinner5c3cda02020-03-25 21:23:53 +01001099uint64_t
1100PyThreadState_GetID(PyThreadState *tstate)
1101{
1102 assert(tstate != NULL);
1103 return tstate->id;
1104}
1105
1106
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001107/* Asynchronously raise an exception in a thread.
1108 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001109 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001110 to call this, or use ctypes. Must be called with the GIL held.
1111 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1112 match any known thread id). Can be called with exc=NULL to clear an
1113 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001114
1115int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001116PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1117{
Victor Stinner09532fe2019-05-10 23:39:09 +02001118 _PyRuntimeState *runtime = &_PyRuntime;
1119 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 /* Although the GIL is held, a few C API functions can be called
1122 * without the GIL held, and in particular some that create and
1123 * destroy thread and interpreter states. Those can mutate the
1124 * list of thread states we're traversing, so to prevent that we lock
1125 * head_mutex for the duration.
1126 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001127 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001128 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1129 if (tstate->thread_id != id) {
1130 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001132
1133 /* Tricky: we need to decref the current value
1134 * (if any) in tstate->async_exc, but that can in turn
1135 * allow arbitrary Python code to run, including
1136 * perhaps calls to this function. To prevent
1137 * deadlock, we need to release head_mutex before
1138 * the decref.
1139 */
1140 PyObject *old_exc = tstate->async_exc;
1141 Py_XINCREF(exc);
1142 tstate->async_exc = exc;
1143 HEAD_UNLOCK(runtime);
1144
1145 Py_XDECREF(old_exc);
1146 _PyEval_SignalAsyncExc(tstate);
1147 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001149 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001151}
1152
1153
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001154/* Routines for advanced debuggers, requested by David Beazley.
1155 Don't use unless you know what you are doing! */
1156
1157PyInterpreterState *
1158PyInterpreterState_Head(void)
1159{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001160 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001161}
1162
1163PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001164PyInterpreterState_Main(void)
1165{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001166 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001167}
1168
1169PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001170PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001172}
1173
1174PyThreadState *
1175PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001177}
1178
1179PyThreadState *
1180PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001182}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001183
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001184/* The implementation of sys._current_frames(). This is intended to be
1185 called with the GIL held, as it will be when called via
1186 sys._current_frames(). It's possible it would work fine even without
1187 the GIL held, but haven't thought enough about that.
1188*/
1189PyObject *
1190_PyThread_CurrentFrames(void)
1191{
Victor Stinner71a35222020-03-26 22:46:14 +01001192 PyThreadState *tstate = _PyThreadState_GET();
1193 if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001194 return NULL;
1195 }
1196
Victor Stinner71a35222020-03-26 22:46:14 +01001197 PyObject *result = PyDict_New();
1198 if (result == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 return NULL;
Victor Stinner71a35222020-03-26 22:46:14 +01001200 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 /* for i in all interpreters:
1203 * for t in all of i's thread states:
1204 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001205 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 * need to grab head_mutex for the duration.
1207 */
Victor Stinner71a35222020-03-26 22:46:14 +01001208 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001209 HEAD_LOCK(runtime);
Victor Stinner71a35222020-03-26 22:46:14 +01001210 PyInterpreterState *i;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001211 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 PyThreadState *t;
1213 for (t = i->tstate_head; t != NULL; t = t->next) {
Victor Stinner4386b902020-04-29 03:01:43 +02001214 PyFrameObject *frame = t->frame;
Victor Stinner71a35222020-03-26 22:46:14 +01001215 if (frame == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 continue;
Victor Stinner71a35222020-03-26 22:46:14 +01001217 }
1218 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1219 if (id == NULL) {
1220 goto fail;
1221 }
1222 int stat = PyDict_SetItem(result, id, (PyObject *)frame);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 Py_DECREF(id);
Victor Stinner71a35222020-03-26 22:46:14 +01001224 if (stat < 0) {
1225 goto fail;
1226 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001227 }
1228 }
Victor Stinner71a35222020-03-26 22:46:14 +01001229 goto done;
1230
1231fail:
1232 Py_CLEAR(result);
1233
1234done:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001235 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001237}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001238
Julien Danjou64366fa2020-11-02 15:16:25 +01001239PyObject *
1240_PyThread_CurrentExceptions(void)
1241{
1242 PyThreadState *tstate = _PyThreadState_GET();
1243
1244 _Py_EnsureTstateNotNULL(tstate);
1245
1246 if (_PySys_Audit(tstate, "sys._current_exceptions", NULL) < 0) {
1247 return NULL;
1248 }
1249
1250 PyObject *result = PyDict_New();
1251 if (result == NULL) {
1252 return NULL;
1253 }
1254
1255 /* for i in all interpreters:
1256 * for t in all of i's thread states:
1257 * if t's frame isn't NULL, map t's id to its frame
1258 * Because these lists can mutate even when the GIL is held, we
1259 * need to grab head_mutex for the duration.
1260 */
1261 _PyRuntimeState *runtime = tstate->interp->runtime;
1262 HEAD_LOCK(runtime);
1263 PyInterpreterState *i;
1264 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
1265 PyThreadState *t;
1266 for (t = i->tstate_head; t != NULL; t = t->next) {
1267 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(t);
1268 if (err_info == NULL) {
1269 continue;
1270 }
1271 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1272 if (id == NULL) {
1273 goto fail;
1274 }
1275 PyObject *exc_info = PyTuple_Pack(
1276 3,
1277 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
1278 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
1279 err_info->exc_traceback != NULL ? err_info->exc_traceback : Py_None);
1280 if (exc_info == NULL) {
1281 Py_DECREF(id);
1282 goto fail;
1283 }
1284 int stat = PyDict_SetItem(result, id, exc_info);
1285 Py_DECREF(id);
1286 Py_DECREF(exc_info);
1287 if (stat < 0) {
1288 goto fail;
1289 }
1290 }
1291 }
1292 goto done;
1293
1294fail:
1295 Py_CLEAR(result);
1296
1297done:
1298 HEAD_UNLOCK(runtime);
1299 return result;
1300}
1301
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001302/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001303
1304/* Keep this as a static, as it is not reliable! It can only
1305 ever be compared to the state for the *current* thread.
1306 * If not equal, then it doesn't matter that the actual
1307 value may change immediately after comparison, as it can't
1308 possibly change to the current thread's state.
1309 * If equal, then the current thread holds the lock, so the value can't
1310 change until we yield the lock.
1311*/
1312static int
1313PyThreadState_IsCurrent(PyThreadState *tstate)
1314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001316 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001317 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1318 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001319}
1320
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001321/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001322 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001323*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001324PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001325_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001326{
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001327 if (!_Py_IsMainInterpreter(tstate)) {
1328 /* Currently, PyGILState is shared by all interpreters. The main
1329 * interpreter is responsible to initialize it. */
1330 return _PyStatus_OK();
1331 }
1332
Victor Stinner8bb32302019-04-24 16:47:40 +02001333 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001334 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001335 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001336
Victor Stinner01b1cc12019-11-20 02:27:56 +01001337 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001338
1339 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001340 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001341 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001342 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001343 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1344 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001345
Victor Stinner8bb32302019-04-24 16:47:40 +02001346 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001347 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001348}
1349
Victor Stinner861d9ab2016-03-16 22:45:24 +01001350PyInterpreterState *
1351_PyGILState_GetInterpreterStateUnsafe(void)
1352{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001353 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001354}
1355
Tim Peters19717fa2004-10-09 17:38:29 +00001356void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001357_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001358{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001359 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001360 PyThread_tss_delete(&gilstate->autoTSSkey);
1361 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001362}
1363
Victor Stinner26881c82020-06-02 15:51:37 +02001364#ifdef HAVE_FORK
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001365/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001366 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001367 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001368 */
Victor Stinner26881c82020-06-02 15:51:37 +02001369PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001370_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001371{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001372 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001373 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001374
1375 PyThread_tss_delete(&gilstate->autoTSSkey);
1376 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner26881c82020-06-02 15:51:37 +02001377 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001378 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001379
Charles-François Natalia233df82011-11-22 19:49:51 +01001380 /* If the thread had an associated auto thread state, reassociate it with
1381 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001382 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001383 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001384 {
Victor Stinner26881c82020-06-02 15:51:37 +02001385 return _PyStatus_ERR("failed to set autoTSSkey");
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001386 }
Victor Stinner26881c82020-06-02 15:51:37 +02001387 return _PyStatus_OK();
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001388}
Victor Stinner26881c82020-06-02 15:51:37 +02001389#endif
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001390
Michael W. Hudson188d4362005-06-20 16:52:57 +00001391/* When a thread state is created for a thread by some mechanism other than
1392 PyGILState_Ensure, it's important that the GILState machinery knows about
1393 it so it doesn't try to create another thread state for the thread (this is
1394 a better fix for SF bug #1010677 than the first one attempted).
1395*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001396static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001397_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001398{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001399 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001400 threadstate created in Py_Initialize(). Don't do anything for now
1401 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001402 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001404 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001405
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001406 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 The only situation where you can legitimately have more than one
1409 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001410 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001411
Victor Stinner590cebe2013-12-13 11:08:56 +01001412 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1413 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001414
Victor Stinner590cebe2013-12-13 11:08:56 +01001415 The first thread state created for that given OS level thread will
1416 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001418 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1419 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001420 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001421 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001422 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 /* PyGILState_Release must not try to delete this thread state. */
1425 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001426}
1427
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001428/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001429static PyThreadState *
1430_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1431{
1432 if (gilstate->autoInterpreterState == NULL)
1433 return NULL;
1434 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1435}
1436
Tim Peters19717fa2004-10-09 17:38:29 +00001437PyThreadState *
1438PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001439{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001440 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001441}
1442
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001443int
1444PyGILState_Check(void)
1445{
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001446 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1447 if (!gilstate->check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001448 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001449 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001450
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001451 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1452 return 1;
1453 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001454
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001455 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1456 if (tstate == NULL) {
1457 return 0;
1458 }
1459
1460 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001461}
1462
Tim Peters19717fa2004-10-09 17:38:29 +00001463PyGILState_STATE
1464PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001465{
Victor Stinner175a7042020-03-10 00:37:48 +01001466 _PyRuntimeState *runtime = &_PyRuntime;
1467 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 /* Note that we do not auto-init Python here - apart from
1470 potential races with 2 threads auto-initializing, pep-311
1471 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001472 called Py_Initialize(). */
1473
1474 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1475 called by Py_Initialize() */
Victor Stinnere838a932020-05-05 19:56:48 +02001476#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinner175a7042020-03-10 00:37:48 +01001477 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinnere838a932020-05-05 19:56:48 +02001478#endif
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001479 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001480
Victor Stinner175a7042020-03-10 00:37:48 +01001481 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1482 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001484 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001485 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001486 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001488 }
1489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 /* This is our thread state! We'll need to delete it in the
1491 matching call to PyGILState_Release(). */
1492 tcur->gilstate_counter = 0;
1493 current = 0; /* new thread state is never current */
1494 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001495 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001497 }
1498
1499 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001501 }
1502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 /* Update our counter in the thread-state - no need for locks:
1504 - tcur will remain valid as we hold the GIL.
1505 - the counter is safe as we are the only thread "allowed"
1506 to modify this value
1507 */
1508 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001511}
1512
Tim Peters19717fa2004-10-09 17:38:29 +00001513void
1514PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001515{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001516 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001517 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1518 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 Py_FatalError("auto-releasing thread-state, "
1520 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001521 }
1522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 /* We must hold the GIL and have our thread state current */
1524 /* XXX - remove the check - the assert should be fine,
1525 but while this is very new (April 2003), the extra check
1526 by release-only users can't hurt.
1527 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001528 if (!PyThreadState_IsCurrent(tstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001529 _Py_FatalErrorFormat(__func__,
1530 "thread state %p must be current when releasing",
1531 tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001532 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001533 assert(PyThreadState_IsCurrent(tstate));
1534 --tstate->gilstate_counter;
1535 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 /* If we're going to destroy this thread-state, we must
1538 * clear it while the GIL is held, as destructors may run.
1539 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001540 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 /* can't have been locked when we created it */
1542 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001543 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 /* Delete the thread-state. Note this releases the GIL too!
1545 * It's vital that the GIL be held here, to avoid shutdown
1546 * races; see bugs 225673 and 1061968 (that nasty bug has a
1547 * habit of coming back).
1548 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001549 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1550 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 }
1552 /* Release the lock if necessary */
1553 else if (oldstate == PyGILState_UNLOCKED)
1554 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001555}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001556
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001557
Eric Snow7f8bfc92018-01-29 18:23:44 -07001558/**************************/
1559/* cross-interpreter data */
1560/**************************/
1561
1562/* cross-interpreter data */
1563
1564crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1565
1566/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1567 to keep the registry code separate. */
1568static crossinterpdatafunc
1569_lookup_getdata(PyObject *obj)
1570{
1571 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1572 if (getdata == NULL && PyErr_Occurred() == 0)
1573 PyErr_Format(PyExc_ValueError,
1574 "%S does not support cross-interpreter data", obj);
1575 return getdata;
1576}
1577
1578int
1579_PyObject_CheckCrossInterpreterData(PyObject *obj)
1580{
1581 crossinterpdatafunc getdata = _lookup_getdata(obj);
1582 if (getdata == NULL) {
1583 return -1;
1584 }
1585 return 0;
1586}
1587
1588static int
Victor Stinner71a35222020-03-26 22:46:14 +01001589_check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001590{
1591 // data->data can be anything, including NULL, so we don't check it.
1592
1593 // data->obj may be NULL, so we don't check it.
1594
1595 if (data->interp < 0) {
Victor Stinner71a35222020-03-26 22:46:14 +01001596 _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001597 return -1;
1598 }
1599
1600 if (data->new_object == NULL) {
Victor Stinner71a35222020-03-26 22:46:14 +01001601 _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001602 return -1;
1603 }
1604
1605 // data->free may be NULL, so we don't check it.
1606
1607 return 0;
1608}
1609
1610int
1611_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1612{
Victor Stinner71a35222020-03-26 22:46:14 +01001613 // PyThreadState_Get() aborts if tstate is NULL.
1614 PyThreadState *tstate = PyThreadState_Get();
1615 PyInterpreterState *interp = tstate->interp;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001616
1617 // Reset data before re-populating.
1618 *data = (_PyCrossInterpreterData){0};
1619 data->free = PyMem_RawFree; // Set a default that may be overridden.
1620
1621 // Call the "getdata" func for the object.
1622 Py_INCREF(obj);
1623 crossinterpdatafunc getdata = _lookup_getdata(obj);
1624 if (getdata == NULL) {
1625 Py_DECREF(obj);
1626 return -1;
1627 }
1628 int res = getdata(obj, data);
1629 Py_DECREF(obj);
1630 if (res != 0) {
1631 return -1;
1632 }
1633
1634 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001635 data->interp = interp->id;
Victor Stinner71a35222020-03-26 22:46:14 +01001636 if (_check_xidata(tstate, data) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001637 _PyCrossInterpreterData_Release(data);
1638 return -1;
1639 }
1640
1641 return 0;
1642}
1643
Victor Stinnere225beb2019-06-03 18:14:24 +02001644static void
Eric Snow63799132018-06-01 18:45:20 -06001645_release_xidata(void *arg)
1646{
1647 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1648 if (data->free != NULL) {
1649 data->free(data->data);
1650 }
1651 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001652}
1653
1654static void
1655_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1656 PyInterpreterState *interp,
1657 void (*func)(void *), void *arg)
1658{
1659 /* We would use Py_AddPendingCall() if it weren't specific to the
1660 * main interpreter (see bpo-33608). In the meantime we take a
1661 * naive approach.
1662 */
1663 PyThreadState *save_tstate = NULL;
1664 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1665 // XXX Using the "head" thread isn't strictly correct.
1666 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1667 // XXX Possible GILState issues?
1668 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1669 }
1670
1671 func(arg);
1672
1673 // Switch back.
1674 if (save_tstate != NULL) {
1675 _PyThreadState_Swap(gilstate, save_tstate);
1676 }
Eric Snow63799132018-06-01 18:45:20 -06001677}
1678
Eric Snow7f8bfc92018-01-29 18:23:44 -07001679void
1680_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1681{
1682 if (data->data == NULL && data->obj == NULL) {
1683 // Nothing to release!
1684 return;
1685 }
1686
Victor Stinnere225beb2019-06-03 18:14:24 +02001687 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001688 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1689 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001690 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001691 if (data->free != NULL) {
1692 // XXX Someone leaked some memory...
1693 }
1694 return;
1695 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001696
Eric Snow7f8bfc92018-01-29 18:23:44 -07001697 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001698 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1699 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001700}
1701
1702PyObject *
1703_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1704{
1705 return data->new_object(data);
1706}
1707
1708/* registry of {type -> crossinterpdatafunc} */
1709
1710/* For now we use a global registry of shareable classes. An
1711 alternative would be to add a tp_* slot for a class's
1712 crossinterpdatafunc. It would be simpler and more efficient. */
1713
1714static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001715_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1716 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001717{
1718 // Note that we effectively replace already registered classes
1719 // rather than failing.
1720 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1721 if (newhead == NULL)
1722 return -1;
1723 newhead->cls = cls;
1724 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001725 newhead->next = xidregistry->head;
1726 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001727 return 0;
1728}
1729
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001730static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001731
1732int
Eric Snowc11183c2019-03-15 16:35:46 -06001733_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001734 crossinterpdatafunc getdata)
1735{
1736 if (!PyType_Check(cls)) {
1737 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1738 return -1;
1739 }
1740 if (getdata == NULL) {
1741 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1742 return -1;
1743 }
1744
1745 // Make sure the class isn't ever deallocated.
1746 Py_INCREF((PyObject *)cls);
1747
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001748 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1749 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1750 if (xidregistry->head == NULL) {
1751 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001752 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001753 int res = _register_xidata(xidregistry, cls, getdata);
1754 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001755 return res;
1756}
1757
Eric Snow6d2cd902018-05-16 15:04:57 -04001758/* Cross-interpreter objects are looked up by exact match on the class.
1759 We can reassess this policy when we move from a global registry to a
1760 tp_* slot. */
1761
Eric Snow7f8bfc92018-01-29 18:23:44 -07001762crossinterpdatafunc
1763_PyCrossInterpreterData_Lookup(PyObject *obj)
1764{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001765 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001766 PyObject *cls = PyObject_Type(obj);
1767 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001768 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1769 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001770 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001771 _register_builtins_for_crossinterpreter_data(xidregistry);
1772 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001773 }
1774 for(; cur != NULL; cur = cur->next) {
1775 if (cur->cls == (PyTypeObject *)cls) {
1776 getdata = cur->getdata;
1777 break;
1778 }
1779 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001780 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001781 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001782 return getdata;
1783}
1784
1785/* cross-interpreter data for builtin types */
1786
Eric Snow6d2cd902018-05-16 15:04:57 -04001787struct _shared_bytes_data {
1788 char *bytes;
1789 Py_ssize_t len;
1790};
1791
Eric Snow7f8bfc92018-01-29 18:23:44 -07001792static PyObject *
1793_new_bytes_object(_PyCrossInterpreterData *data)
1794{
Eric Snow6d2cd902018-05-16 15:04:57 -04001795 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1796 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001797}
1798
1799static int
1800_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1801{
Eric Snow6d2cd902018-05-16 15:04:57 -04001802 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1803 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1804 return -1;
1805 }
1806 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001807 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001808 data->obj = obj; // Will be "released" (decref'ed) when data released.
1809 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001810 data->free = PyMem_Free;
1811 return 0;
1812}
1813
1814struct _shared_str_data {
1815 int kind;
1816 const void *buffer;
1817 Py_ssize_t len;
1818};
1819
1820static PyObject *
1821_new_str_object(_PyCrossInterpreterData *data)
1822{
1823 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1824 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1825}
1826
1827static int
1828_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1829{
1830 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1831 shared->kind = PyUnicode_KIND(obj);
1832 shared->buffer = PyUnicode_DATA(obj);
An Long29c11722020-06-13 20:26:01 +08001833 shared->len = PyUnicode_GET_LENGTH(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001834 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001835 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001836 data->obj = obj; // Will be "released" (decref'ed) when data released.
1837 data->new_object = _new_str_object;
1838 data->free = PyMem_Free;
1839 return 0;
1840}
1841
1842static PyObject *
1843_new_long_object(_PyCrossInterpreterData *data)
1844{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001845 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001846}
1847
1848static int
1849_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1850{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001851 /* Note that this means the size of shareable ints is bounded by
1852 * sys.maxsize. Hence on 32-bit architectures that is half the
1853 * size of maximum shareable ints on 64-bit.
1854 */
1855 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001856 if (value == -1 && PyErr_Occurred()) {
1857 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1858 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1859 }
1860 return -1;
1861 }
1862 data->data = (void *)value;
1863 data->obj = NULL;
1864 data->new_object = _new_long_object;
1865 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001866 return 0;
1867}
1868
1869static PyObject *
1870_new_none_object(_PyCrossInterpreterData *data)
1871{
1872 // XXX Singleton refcounts are problematic across interpreters...
1873 Py_INCREF(Py_None);
1874 return Py_None;
1875}
1876
1877static int
1878_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1879{
1880 data->data = NULL;
1881 // data->obj remains NULL
1882 data->new_object = _new_none_object;
1883 data->free = NULL; // There is nothing to free.
1884 return 0;
1885}
1886
1887static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001888_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001889{
1890 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001891 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001892 Py_FatalError("could not register None for cross-interpreter sharing");
1893 }
1894
Eric Snow6d2cd902018-05-16 15:04:57 -04001895 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001896 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001897 Py_FatalError("could not register int for cross-interpreter sharing");
1898 }
1899
Eric Snow7f8bfc92018-01-29 18:23:44 -07001900 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001901 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001902 Py_FatalError("could not register bytes for cross-interpreter sharing");
1903 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001904
1905 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001906 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001907 Py_FatalError("could not register str for cross-interpreter sharing");
1908 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001909}
1910
1911
Victor Stinner0b72b232020-03-12 23:18:39 +01001912_PyFrameEvalFunction
1913_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1914{
1915 return interp->eval_frame;
1916}
1917
1918
1919void
1920_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1921 _PyFrameEvalFunction eval_frame)
1922{
1923 interp->eval_frame = eval_frame;
1924}
1925
Victor Stinnerda7933e2020-04-13 03:04:28 +02001926
1927const PyConfig*
1928_PyInterpreterState_GetConfig(PyInterpreterState *interp)
1929{
1930 return &interp->config;
1931}
1932
1933
Victor Stinner048a3562020-11-05 00:45:56 +01001934int
1935_PyInterpreterState_GetConfigCopy(PyConfig *config)
Victor Stinnerda7933e2020-04-13 03:04:28 +02001936{
Victor Stinner048a3562020-11-05 00:45:56 +01001937 PyInterpreterState *interp = PyInterpreterState_Get();
1938
1939 PyStatus status = _PyConfig_Copy(config, &interp->config);
1940 if (PyStatus_Exception(status)) {
1941 _PyErr_SetFromPyStatus(status);
1942 return -1;
1943 }
1944 return 0;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001945}
1946
1947
1948const PyConfig*
1949_Py_GetConfig(void)
1950{
1951 assert(PyGILState_Check());
1952 PyThreadState *tstate = _PyThreadState_GET();
1953 return _PyInterpreterState_GetConfig(tstate->interp);
1954}
1955
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001956#ifdef __cplusplus
1957}
1958#endif