blob: 231144b082861f42b35f6bfa75f63e56e480af9e [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 Stinner0e427c62020-03-25 21:22:55 +01007#include "pycore_pyerrors.h"
8#include "pycore_pylifecycle.h"
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +02009#include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
Victor Stinnere5014be2020-04-14 17:52:15 +020010#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner71a35222020-03-26 22:46:14 +010011#include "pycore_sysmodule.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +000012
Tim Peters84705582004-10-10 02:47:33 +000013/* --------------------------------------------------------------------------
14CAUTION
15
Victor Stinner1a7425f2013-07-07 16:25:15 +020016Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
17number of these functions are advertised as safe to call when the GIL isn't
18held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
19debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
20to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000021-------------------------------------------------------------------------- */
22
Martin v. Löwisf0473d52001-07-18 16:17:16 +000023#ifdef HAVE_DLOPEN
24#ifdef HAVE_DLFCN_H
25#include <dlfcn.h>
26#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030027#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000028#define RTLD_LAZY 1
29#endif
30#endif
31
Benjamin Peterson43162b82012-04-13 11:58:27 -040032#ifdef __cplusplus
33extern "C" {
34#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000035
Victor Stinner10c8e6a2019-04-26 01:53:18 +020036#define _PyRuntimeGILState_GetThreadState(gilstate) \
37 ((PyThreadState*)_Py_atomic_load_relaxed(&(gilstate)->tstate_current))
38#define _PyRuntimeGILState_SetThreadState(gilstate, value) \
39 _Py_atomic_store_relaxed(&(gilstate)->tstate_current, \
40 (uintptr_t)(value))
41
42/* Forward declarations */
43static PyThreadState *_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate);
Victor Stinner9da74302019-11-20 11:17:17 +010044static void _PyThreadState_Delete(PyThreadState *tstate, int check_current);
Victor Stinner10c8e6a2019-04-26 01:53:18 +020045
46
Victor Stinner331a6a52019-05-27 16:39:22 +020047static PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010048_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060049{
Steve Dowerb82e17e2019-05-23 08:45:22 -070050 /* We preserve the hook across init, because there is
51 currently no public API to set it between runtime
52 initialization and interpreter initialization. */
53 void *open_code_hook = runtime->open_code_hook;
54 void *open_code_userdata = runtime->open_code_userdata;
55 _Py_AuditHookEntry *audit_hook_head = runtime->audit_hook_head;
56
Eric Snow2ebc5ce2017-09-07 23:51:28 -060057 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010058
Steve Dowerb82e17e2019-05-23 08:45:22 -070059 runtime->open_code_hook = open_code_hook;
60 runtime->open_code_userdata = open_code_userdata;
61 runtime->audit_hook_head = audit_hook_head;
62
Victor Stinnerdab84232020-03-17 18:56:44 +010063 _PyEval_InitRuntimeState(&runtime->ceval);
Victor Stinner441b10c2019-09-28 04:28:35 +020064
Victor Stinner3c30a762019-10-01 10:56:37 +020065 PyPreConfig_InitPythonConfig(&runtime->preconfig);
Michael W. Hudson188d4362005-06-20 16:52:57 +000066
Eric Snow2ebc5ce2017-09-07 23:51:28 -060067 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080068
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090069 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
70 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080071 Py_tss_t initial = Py_tss_NEEDS_INIT;
72 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000073
Eric Snow2ebc5ce2017-09-07 23:51:28 -060074 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080075 if (runtime->interpreters.mutex == NULL) {
Victor Stinnerba3d67c2020-12-26 00:41:46 +010076 return _PyStatus_NO_MEMORY();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080077 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060078 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070079
80 runtime->xidregistry.mutex = PyThread_allocate_lock();
81 if (runtime->xidregistry.mutex == NULL) {
Victor Stinnerba3d67c2020-12-26 00:41:46 +010082 return _PyStatus_NO_MEMORY();
Eric Snow7f8bfc92018-01-29 18:23:44 -070083 }
84
Eric Snow8479a342019-03-08 23:44:33 -070085 // Set it to the ID of the main thread of the main interpreter.
86 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070087
Victor Stinnerba3d67c2020-12-26 00:41:46 +010088 runtime->unicode_ids.lock = PyThread_allocate_lock();
89 if (runtime->unicode_ids.lock == NULL) {
90 return _PyStatus_NO_MEMORY();
91 }
92 runtime->unicode_ids.next_index = 0;
93
Victor Stinner331a6a52019-05-27 16:39:22 +020094 return _PyStatus_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060095}
Eric Snow05351c12017-09-05 21:43:08 -070096
Victor Stinner331a6a52019-05-27 16:39:22 +020097PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010098_PyRuntimeState_Init(_PyRuntimeState *runtime)
99{
100 /* Force default allocator, since _PyRuntimeState_Fini() must
101 use the same allocator than this function. */
102 PyMemAllocatorEx old_alloc;
103 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
104
Victor Stinner331a6a52019-05-27 16:39:22 +0200105 PyStatus status = _PyRuntimeState_Init_impl(runtime);
Victor Stinner5d39e042017-11-29 17:20:38 +0100106
107 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinner331a6a52019-05-27 16:39:22 +0200108 return status;
Victor Stinner5d39e042017-11-29 17:20:38 +0100109}
110
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600111void
112_PyRuntimeState_Fini(_PyRuntimeState *runtime)
113{
Victor Stinner5d39e042017-11-29 17:20:38 +0100114 /* Force the allocator used by _PyRuntimeState_Init(). */
115 PyMemAllocatorEx old_alloc;
116 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerba3d67c2020-12-26 00:41:46 +0100117#define FREE_LOCK(LOCK) \
118 if (LOCK != NULL) { \
119 PyThread_free_lock(LOCK); \
120 LOCK = NULL; \
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600121 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800122
Victor Stinnerba3d67c2020-12-26 00:41:46 +0100123 FREE_LOCK(runtime->interpreters.mutex);
124 FREE_LOCK(runtime->xidregistry.mutex);
125 FREE_LOCK(runtime->unicode_ids.lock);
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100126
Victor Stinnerba3d67c2020-12-26 00:41:46 +0100127#undef FREE_LOCK
Victor Stinnerccb04422017-11-16 03:20:31 -0800128 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600129}
130
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900131#ifdef HAVE_FORK
Eric Snow8479a342019-03-08 23:44:33 -0700132/* This function is called from PyOS_AfterFork_Child to ensure that
Victor Stinner26881c82020-06-02 15:51:37 +0200133 newly created child processes do not share locks with the parent. */
134PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200135_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700136{
137 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200138 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700139
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200140 /* Force default allocator, since _PyRuntimeState_Fini() must
141 use the same allocator than this function. */
142 PyMemAllocatorEx old_alloc;
143 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
144
Victor Stinner26881c82020-06-02 15:51:37 +0200145 int reinit_interp = _PyThread_at_fork_reinit(&runtime->interpreters.mutex);
146 int reinit_main_id = _PyThread_at_fork_reinit(&runtime->interpreters.main->id_mutex);
147 int reinit_xidregistry = _PyThread_at_fork_reinit(&runtime->xidregistry.mutex);
Victor Stinnerba3d67c2020-12-26 00:41:46 +0100148 int reinit_unicode_ids = _PyThread_at_fork_reinit(&runtime->unicode_ids.lock);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200149
150 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
151
Victor Stinner26881c82020-06-02 15:51:37 +0200152 if (reinit_interp < 0
153 || reinit_main_id < 0
Victor Stinnerba3d67c2020-12-26 00:41:46 +0100154 || reinit_xidregistry < 0
155 || reinit_unicode_ids < 0)
Victor Stinner26881c82020-06-02 15:51:37 +0200156 {
157 return _PyStatus_ERR("Failed to reinitialize runtime locks");
Eric Snow8479a342019-03-08 23:44:33 -0700158
Eric Snow8479a342019-03-08 23:44:33 -0700159 }
Victor Stinner26881c82020-06-02 15:51:37 +0200160 return _PyStatus_OK();
Eric Snow8479a342019-03-08 23:44:33 -0700161}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900162#endif
Eric Snow8479a342019-03-08 23:44:33 -0700163
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200164#define HEAD_LOCK(runtime) \
165 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
166#define HEAD_UNLOCK(runtime) \
167 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700168
Victor Stinner8bb32302019-04-24 16:47:40 +0200169/* Forward declaration */
170static void _PyGILState_NoteThreadState(
171 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000172
Victor Stinner331a6a52019-05-27 16:39:22 +0200173PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600174_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700175{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200176 struct pyinterpreters *interpreters = &runtime->interpreters;
177 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100178
179 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
180 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200181 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100182 /* Force default allocator, since _PyRuntimeState_Fini() must
183 use the same allocator than this function. */
184 PyMemAllocatorEx old_alloc;
185 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
186
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200187 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100188
189 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
190
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200191 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200192 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800193 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600194 }
Victor Stinner5d926472018-03-06 14:31:37 +0100195
Victor Stinner331a6a52019-05-27 16:39:22 +0200196 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700197}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000198
199PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000200PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000201{
Victor Stinner71a35222020-03-26 22:46:14 +0100202 PyThreadState *tstate = _PyThreadState_GET();
203 /* tstate is NULL when Py_InitializeFromConfig() calls
204 PyInterpreterState_New() to create the main interpreter. */
205 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_New", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700206 return NULL;
207 }
208
Andy Lester7668a8b2020-03-24 23:26:44 -0500209 PyInterpreterState *interp = PyMem_RawCalloc(1, sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100210 if (interp == NULL) {
211 return NULL;
212 }
213
Eric Snow4c6955e2018-02-16 18:53:40 -0700214 interp->id_refcount = -1;
Victor Stinner022be022019-05-22 23:58:50 +0200215
Victor Stinner71a35222020-03-26 22:46:14 +0100216 /* Don't get runtime from tstate since tstate can be NULL */
Victor Stinner01b1cc12019-11-20 02:27:56 +0100217 _PyRuntimeState *runtime = &_PyRuntime;
218 interp->runtime = runtime;
219
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200220 if (_PyEval_InitState(&interp->ceval) < 0) {
221 goto out_of_memory;
222 }
223
Victor Stinner72474072019-11-20 12:25:50 +0100224 _PyGC_InitState(&interp->gc);
Victor Stinner8462a492019-10-01 12:06:16 +0200225 PyConfig_InitPythonConfig(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200226
Victor Stinnerd4341102017-11-23 00:12:09 +0100227 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000228#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300229#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100230 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000231#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100232 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000233#endif
234#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000235
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200236 struct pyinterpreters *interpreters = &runtime->interpreters;
237
238 HEAD_LOCK(runtime);
239 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100240 /* overflow or Py_Initialize() not called! */
Victor Stinner71a35222020-03-26 22:46:14 +0100241 if (tstate != NULL) {
242 _PyErr_SetString(tstate, PyExc_RuntimeError,
243 "failed to get an interpreter ID");
244 }
Pablo Galindo95d630e2018-08-31 22:49:29 +0100245 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100246 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100247 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200248 else {
249 interp->id = interpreters->next_id;
250 interpreters->next_id += 1;
251 interp->next = interpreters->head;
252 if (interpreters->main == NULL) {
253 interpreters->main = interp;
254 }
255 interpreters->head = interp;
256 }
257 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000258
Pablo Galindo95d630e2018-08-31 22:49:29 +0100259 if (interp == NULL) {
260 return NULL;
261 }
262
Yury Selivanovf23746a2018-01-22 19:11:18 -0500263 interp->tstate_next_unique_id = 0;
264
Steve Dowerb82e17e2019-05-23 08:45:22 -0700265 interp->audit_hooks = NULL;
266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 return interp;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200268
269out_of_memory:
270 if (tstate != NULL) {
271 _PyErr_NoMemory(tstate);
272 }
273
274 PyMem_RawFree(interp);
275 return NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000276}
277
278
Victor Stinnereba5bf22020-10-30 22:51:02 +0100279static void
280interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000281{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100282 _PyRuntimeState *runtime = interp->runtime;
283
Victor Stinner71a35222020-03-26 22:46:14 +0100284 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_Clear", NULL) < 0) {
285 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700286 }
287
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200288 HEAD_LOCK(runtime);
289 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200291 }
292 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700293
294 Py_CLEAR(interp->audit_hooks);
295
Victor Stinner331a6a52019-05-27 16:39:22 +0200296 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 Py_CLEAR(interp->codec_search_path);
298 Py_CLEAR(interp->codec_search_cache);
299 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700300 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 Py_CLEAR(interp->modules_by_index);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200302 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400303 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300304 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600305 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200306#ifdef HAVE_FORK
307 Py_CLEAR(interp->before_forkers);
308 Py_CLEAR(interp->after_forkers_parent);
309 Py_CLEAR(interp->after_forkers_child);
310#endif
Victor Stinnerfd957c12020-11-03 18:07:15 +0100311
312 _PyAST_Fini(interp);
313 _PyWarnings_Fini(interp);
Victor Stinnerb8fa1352020-12-15 14:34:19 +0100314 _PyAtExit_Fini(interp);
Victor Stinnerfd957c12020-11-03 18:07:15 +0100315
316 // All Python types must be destroyed before the last GC collection. Python
317 // types create a reference cycle to themselves in their in their
318 // PyTypeObject.tp_mro member (the tuple contains the type).
Victor Stinnereba5bf22020-10-30 22:51:02 +0100319
320 /* Last garbage collection on this interpreter */
321 _PyGC_CollectNoFail(tstate);
Victor Stinnereba5bf22020-10-30 22:51:02 +0100322 _PyGC_Fini(tstate);
323
Hai Shi8ecc0c42020-08-13 05:23:30 +0800324 /* We don't clear sysdict and builtins until the end of this function.
325 Because clearing other attributes can execute arbitrary Python code
326 which requires sysdict and builtins. */
327 PyDict_Clear(interp->sysdict);
328 PyDict_Clear(interp->builtins);
329 Py_CLEAR(interp->sysdict);
330 Py_CLEAR(interp->builtins);
331
Eric Snow5be45a62019-03-08 22:47:07 -0700332 // XXX Once we have one allocator per interpreter (i.e.
333 // per-interpreter GC) we must ensure that all of the interpreter's
334 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000335}
336
337
Victor Stinnereba5bf22020-10-30 22:51:02 +0100338void
339PyInterpreterState_Clear(PyInterpreterState *interp)
340{
341 // Use the current Python thread state to call audit hooks and to collect
342 // garbage. It can be different than the current Python thread state
343 // of 'interp'.
344 PyThreadState *current_tstate = _PyThreadState_GET();
345
346 interpreter_clear(interp, current_tstate);
347}
348
349
350void
351_PyInterpreterState_Clear(PyThreadState *tstate)
352{
353 interpreter_clear(tstate->interp, tstate);
354}
355
356
Guido van Rossum25ce5661997-08-02 03:10:38 +0000357static void
Victor Stinner9da74302019-11-20 11:17:17 +0100358zapthreads(PyInterpreterState *interp, int check_current)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000359{
Victor Stinner9da74302019-11-20 11:17:17 +0100360 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 /* No need to lock the mutex here because this should only happen
362 when the threads are all really dead (XXX famous last words). */
Victor Stinner9da74302019-11-20 11:17:17 +0100363 while ((tstate = interp->tstate_head) != NULL) {
364 _PyThreadState_Delete(tstate, check_current);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000366}
367
368
Victor Stinner01b1cc12019-11-20 02:27:56 +0100369void
370PyInterpreterState_Delete(PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200371{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100372 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200373 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner9da74302019-11-20 11:17:17 +0100374 zapthreads(interp, 0);
375
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200376 _PyEval_FiniState(&interp->ceval);
377
Victor Stinner9da74302019-11-20 11:17:17 +0100378 /* Delete current thread. After this, many C API calls become crashy. */
379 _PyThreadState_Swap(&runtime->gilstate, NULL);
380
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200381 HEAD_LOCK(runtime);
382 PyInterpreterState **p;
383 for (p = &interpreters->head; ; p = &(*p)->next) {
384 if (*p == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100385 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200386 }
387 if (*p == interp) {
388 break;
389 }
390 }
391 if (interp->tstate_head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100392 Py_FatalError("remaining threads");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200393 }
394 *p = interp->next;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200395
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200396 if (interpreters->main == interp) {
397 interpreters->main = NULL;
398 if (interpreters->head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100399 Py_FatalError("remaining subinterpreters");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200400 }
401 }
402 HEAD_UNLOCK(runtime);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200403
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200404 if (interp->id_mutex != NULL) {
405 PyThread_free_lock(interp->id_mutex);
406 }
407 PyMem_RawFree(interp);
408}
409
410
Victor Stinner26881c82020-06-02 15:51:37 +0200411#ifdef HAVE_FORK
Eric Snow59032962018-09-14 14:17:20 -0700412/*
413 * Delete all interpreter states except the main interpreter. If there
414 * is a current interpreter state, it *must* be the main interpreter.
415 */
Victor Stinner26881c82020-06-02 15:51:37 +0200416PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200417_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700418{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200419 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200420 struct pyinterpreters *interpreters = &runtime->interpreters;
421
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200422 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200423 if (tstate != NULL && tstate->interp != interpreters->main) {
Victor Stinner26881c82020-06-02 15:51:37 +0200424 return _PyStatus_ERR("not main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700425 }
426
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200427 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200428 PyInterpreterState *interp = interpreters->head;
429 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100430 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200431 if (interp == interpreters->main) {
432 interpreters->main->next = NULL;
433 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100434 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700435 continue;
436 }
437
Victor Stinner01b1cc12019-11-20 02:27:56 +0100438 PyInterpreterState_Clear(interp); // XXX must activate?
Victor Stinner9da74302019-11-20 11:17:17 +0100439 zapthreads(interp, 1);
Eric Snow59032962018-09-14 14:17:20 -0700440 if (interp->id_mutex != NULL) {
441 PyThread_free_lock(interp->id_mutex);
442 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100443 PyInterpreterState *prev_interp = interp;
444 interp = interp->next;
445 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700446 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200447 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700448
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200449 if (interpreters->head == NULL) {
Victor Stinner26881c82020-06-02 15:51:37 +0200450 return _PyStatus_ERR("missing main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700451 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200452 _PyThreadState_Swap(gilstate, tstate);
Victor Stinner26881c82020-06-02 15:51:37 +0200453 return _PyStatus_OK();
Eric Snow59032962018-09-14 14:17:20 -0700454}
Victor Stinner26881c82020-06-02 15:51:37 +0200455#endif
Eric Snow59032962018-09-14 14:17:20 -0700456
457
Victor Stinnercaba55b2018-08-03 15:33:52 +0200458PyInterpreterState *
Victor Stinnerbe793732020-03-13 18:15:33 +0100459PyInterpreterState_Get(void)
Victor Stinnercaba55b2018-08-03 15:33:52 +0200460{
Victor Stinner50b48572018-11-01 01:51:40 +0100461 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200462 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200463 PyInterpreterState *interp = tstate->interp;
464 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100465 Py_FatalError("no current interpreter");
Victor Stinnercaba55b2018-08-03 15:33:52 +0200466 }
467 return interp;
468}
469
470
Eric Snowe3774162017-05-22 19:46:40 -0700471int64_t
472PyInterpreterState_GetID(PyInterpreterState *interp)
473{
474 if (interp == NULL) {
475 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
476 return -1;
477 }
478 return interp->id;
479}
480
481
Eric Snow5be45a62019-03-08 22:47:07 -0700482static PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200483interp_look_up_id(_PyRuntimeState *runtime, int64_t requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700484{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200485 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100486 while (interp != NULL) {
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200487 int64_t id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700488 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100489 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700490 }
491 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100492 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700493 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100494 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700495 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100496 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700497}
498
Eric Snow5be45a62019-03-08 22:47:07 -0700499PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200500_PyInterpreterState_LookUpID(int64_t requested_id)
Eric Snow5be45a62019-03-08 22:47:07 -0700501{
502 PyInterpreterState *interp = NULL;
503 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200504 _PyRuntimeState *runtime = &_PyRuntime;
505 HEAD_LOCK(runtime);
506 interp = interp_look_up_id(runtime, requested_id);
507 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700508 }
509 if (interp == NULL && !PyErr_Occurred()) {
510 PyErr_Format(PyExc_RuntimeError,
511 "unrecognized interpreter ID %lld", requested_id);
512 }
513 return interp;
514}
515
Eric Snow4c6955e2018-02-16 18:53:40 -0700516
517int
518_PyInterpreterState_IDInitref(PyInterpreterState *interp)
519{
520 if (interp->id_mutex != NULL) {
521 return 0;
522 }
523 interp->id_mutex = PyThread_allocate_lock();
524 if (interp->id_mutex == NULL) {
525 PyErr_SetString(PyExc_RuntimeError,
526 "failed to create init interpreter ID mutex");
527 return -1;
528 }
529 interp->id_refcount = 0;
530 return 0;
531}
532
533
534void
535_PyInterpreterState_IDIncref(PyInterpreterState *interp)
536{
537 if (interp->id_mutex == NULL) {
538 return;
539 }
540 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
541 interp->id_refcount += 1;
542 PyThread_release_lock(interp->id_mutex);
543}
544
545
546void
547_PyInterpreterState_IDDecref(PyInterpreterState *interp)
548{
549 if (interp->id_mutex == NULL) {
550 return;
551 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200552 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700553 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
554 assert(interp->id_refcount != 0);
555 interp->id_refcount -= 1;
556 int64_t refcount = interp->id_refcount;
557 PyThread_release_lock(interp->id_mutex);
558
Eric Snowc11183c2019-03-15 16:35:46 -0600559 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700560 // XXX Using the "head" thread isn't strictly correct.
561 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
562 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200563 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700564 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200565 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700566 }
567}
568
Eric Snowc11183c2019-03-15 16:35:46 -0600569int
570_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
571{
572 return interp->requires_idref;
573}
574
575void
576_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
577{
578 interp->requires_idref = required ? 1 : 0;
579}
580
Eric Snowc11183c2019-03-15 16:35:46 -0600581PyObject *
582_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
583{
584 if (interp->modules == NULL) {
585 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
586 return NULL;
587 }
588 return PyMapping_GetItemString(interp->modules, "__main__");
589}
590
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600591PyObject *
592PyInterpreterState_GetDict(PyInterpreterState *interp)
593{
594 if (interp->dict == NULL) {
595 interp->dict = PyDict_New();
596 if (interp->dict == NULL) {
597 PyErr_Clear();
598 }
599 }
600 /* Returning NULL means no per-interpreter dict is available. */
601 return interp->dict;
602}
603
Victor Stinner45b9be52010-03-03 23:28:07 +0000604static PyThreadState *
605new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000606{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100607 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200608 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200609 if (tstate == NULL) {
610 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000612
Victor Stinner8bb32302019-04-24 16:47:40 +0200613 tstate->interp = interp;
614
615 tstate->frame = NULL;
616 tstate->recursion_depth = 0;
Mark Shannon4e7a69b2020-12-02 13:30:55 +0000617 tstate->recursion_headroom = 0;
Victor Stinner8bb32302019-04-24 16:47:40 +0200618 tstate->stackcheck_counter = 0;
619 tstate->tracing = 0;
620 tstate->use_tracing = 0;
621 tstate->gilstate_counter = 0;
622 tstate->async_exc = NULL;
623 tstate->thread_id = PyThread_get_thread_ident();
624
625 tstate->dict = NULL;
626
627 tstate->curexc_type = NULL;
628 tstate->curexc_value = NULL;
629 tstate->curexc_traceback = NULL;
630
631 tstate->exc_state.exc_type = NULL;
632 tstate->exc_state.exc_value = NULL;
633 tstate->exc_state.exc_traceback = NULL;
634 tstate->exc_state.previous_item = NULL;
635 tstate->exc_info = &tstate->exc_state;
636
637 tstate->c_profilefunc = NULL;
638 tstate->c_tracefunc = NULL;
639 tstate->c_profileobj = NULL;
640 tstate->c_traceobj = NULL;
641
642 tstate->trash_delete_nesting = 0;
643 tstate->trash_delete_later = NULL;
644 tstate->on_delete = NULL;
645 tstate->on_delete_data = NULL;
646
647 tstate->coroutine_origin_tracking_depth = 0;
648
Victor Stinner8bb32302019-04-24 16:47:40 +0200649 tstate->async_gen_firstiter = NULL;
650 tstate->async_gen_finalizer = NULL;
651
652 tstate->context = NULL;
653 tstate->context_ver = 1;
654
Victor Stinner8bb32302019-04-24 16:47:40 +0200655 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100656 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200657 }
658
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200659 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100660 tstate->id = ++interp->tstate_next_unique_id;
Victor Stinner8bb32302019-04-24 16:47:40 +0200661 tstate->prev = NULL;
662 tstate->next = interp->tstate_head;
663 if (tstate->next)
664 tstate->next->prev = tstate;
665 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200666 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000669}
670
Victor Stinner45b9be52010-03-03 23:28:07 +0000671PyThreadState *
672PyThreadState_New(PyInterpreterState *interp)
673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000675}
676
677PyThreadState *
678_PyThreadState_Prealloc(PyInterpreterState *interp)
679{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000681}
682
683void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100684_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000685{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100686 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000687}
688
Martin v. Löwis1a214512008-06-11 05:26:20 +0000689PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200690PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000691{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200692 Py_ssize_t index = module->m_base.m_index;
Victor Stinner81a7be32020-04-14 15:14:01 +0200693 PyInterpreterState *state = _PyInterpreterState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000695 if (module->m_slots) {
696 return NULL;
697 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 if (index == 0)
699 return NULL;
700 if (state->modules_by_index == NULL)
701 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200702 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 return NULL;
704 res = PyList_GET_ITEM(state->modules_by_index, index);
705 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000706}
707
708int
Victor Stinner82c83bd2019-11-22 18:52:27 +0100709_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000710{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300711 if (!def) {
Victor Stinner71a35222020-03-26 22:46:14 +0100712 assert(_PyErr_Occurred(tstate));
Berker Peksag4b7b5652016-08-22 18:05:56 +0300713 return -1;
714 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000715 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100716 _PyErr_SetString(tstate,
717 PyExc_SystemError,
718 "PyState_AddModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000719 return -1;
720 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100721
722 PyInterpreterState *interp = tstate->interp;
723 if (!interp->modules_by_index) {
724 interp->modules_by_index = PyList_New(0);
725 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100727 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100729
730 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
731 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100733 }
734 }
735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100737 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000739}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000740
Martin v. Löwis7800f752012-06-22 12:20:55 +0200741int
742PyState_AddModule(PyObject* module, struct PyModuleDef* def)
743{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200744 if (!def) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100745 Py_FatalError("module definition is NULL");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200746 return -1;
747 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100748
749 PyThreadState *tstate = _PyThreadState_GET();
750 PyInterpreterState *interp = tstate->interp;
751 Py_ssize_t index = def->m_base.m_index;
752 if (interp->modules_by_index &&
753 index < PyList_GET_SIZE(interp->modules_by_index) &&
754 module == PyList_GET_ITEM(interp->modules_by_index, index))
755 {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100756 _Py_FatalErrorFormat(__func__, "module %p already added", module);
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100757 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200758 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100759 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200760}
761
762int
763PyState_RemoveModule(struct PyModuleDef* def)
764{
Victor Stinner71a35222020-03-26 22:46:14 +0100765 PyThreadState *tstate = _PyThreadState_GET();
766 PyInterpreterState *interp = tstate->interp;
767
Nick Coghland5cacbb2015-05-23 22:24:10 +1000768 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100769 _PyErr_SetString(tstate,
770 PyExc_SystemError,
771 "PyState_RemoveModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000772 return -1;
773 }
Victor Stinner71a35222020-03-26 22:46:14 +0100774
775 Py_ssize_t index = def->m_base.m_index;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200776 if (index == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100777 Py_FatalError("invalid module index");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200778 }
Victor Stinner71a35222020-03-26 22:46:14 +0100779 if (interp->modules_by_index == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100780 Py_FatalError("Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200781 }
Victor Stinner71a35222020-03-26 22:46:14 +0100782 if (index > PyList_GET_SIZE(interp->modules_by_index)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100783 Py_FatalError("Module index out of bounds.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200784 }
Victor Stinner71a35222020-03-26 22:46:14 +0100785
Zackery Spytz2a893432018-12-05 00:14:00 -0700786 Py_INCREF(Py_None);
Victor Stinner71a35222020-03-26 22:46:14 +0100787 return PyList_SetItem(interp->modules_by_index, index, Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200788}
789
Victor Stinner048a3562020-11-05 00:45:56 +0100790// Used by finalize_modules()
Antoine Pitrou40322e62013-08-11 00:30:09 +0200791void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200792_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200793{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200794 if (!interp->modules_by_index) {
795 return;
796 }
797
798 Py_ssize_t i;
799 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
800 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
801 if (PyModule_Check(m)) {
802 /* cleanup the saved copy of module dicts */
803 PyModuleDef *md = PyModule_GetDef(m);
804 if (md) {
805 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200806 }
807 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200808 }
809
810 /* Setting modules_by_index to NULL could be dangerous, so we
811 clear the list instead. */
812 if (PyList_SetSlice(interp->modules_by_index,
813 0, PyList_GET_SIZE(interp->modules_by_index),
814 NULL)) {
815 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200816 }
817}
818
Guido van Rossuma027efa1997-05-05 20:56:21 +0000819void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000820PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000821{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200822 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200823
Victor Stinner5804f872020-03-24 16:32:26 +0100824 if (verbose && tstate->frame != NULL) {
825 /* bpo-20526: After the main thread calls
826 _PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
827 exit when trying to take the GIL. If a thread exit in the middle of
828 _PyEval_EvalFrameDefault(), tstate->frame is not reset to its
829 previous value. It is more likely with daemon threads, but it can
830 happen with regular threads if threading._shutdown() fails
831 (ex: interrupted by CTRL+C). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 fprintf(stderr,
833 "PyThreadState_Clear: warning: thread still has a frame\n");
Victor Stinner5804f872020-03-24 16:32:26 +0100834 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000835
Victor Stinner5804f872020-03-24 16:32:26 +0100836 /* Don't clear tstate->frame: it is a borrowed reference */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 Py_CLEAR(tstate->dict);
839 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 Py_CLEAR(tstate->curexc_type);
842 Py_CLEAR(tstate->curexc_value);
843 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000844
Mark Shannonae3087c2017-10-22 22:41:51 +0100845 Py_CLEAR(tstate->exc_state.exc_type);
846 Py_CLEAR(tstate->exc_state.exc_value);
847 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300848
Mark Shannonae3087c2017-10-22 22:41:51 +0100849 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200850 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100851 fprintf(stderr,
852 "PyThreadState_Clear: warning: thread still has a generator\n");
853 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 tstate->c_profilefunc = NULL;
856 tstate->c_tracefunc = NULL;
857 Py_CLEAR(tstate->c_profileobj);
858 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400859
Yury Selivanoveb636452016-09-08 22:01:51 -0700860 Py_CLEAR(tstate->async_gen_firstiter);
861 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500862
863 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100864
865 if (tstate->on_delete != NULL) {
866 tstate->on_delete(tstate->on_delete_data);
867 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000868}
869
870
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300871/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000872static void
Victor Stinner9da74302019-11-20 11:17:17 +0100873tstate_delete_common(PyThreadState *tstate,
874 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000875{
Victor Stinner3026cad2020-06-01 16:02:40 +0200876 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200877 PyInterpreterState *interp = tstate->interp;
878 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100879 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200880 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100881 _PyRuntimeState *runtime = interp->runtime;
882
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200883 HEAD_LOCK(runtime);
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100884 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200885 tstate->prev->next = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100886 }
887 else {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200888 interp->tstate_head = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100889 }
890 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200891 tstate->next->prev = tstate->prev;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100892 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200893 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100894
Victor Stinner9da74302019-11-20 11:17:17 +0100895 if (gilstate->autoInterpreterState &&
896 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
897 {
898 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
899 }
900}
901
902
903static void
904_PyThreadState_Delete(PyThreadState *tstate, int check_current)
905{
906 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
907 if (check_current) {
908 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100909 _Py_FatalErrorFormat(__func__, "tstate %p is still current", tstate);
Victor Stinner9da74302019-11-20 11:17:17 +0100910 }
911 }
912 tstate_delete_common(tstate, gilstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100913 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000914}
915
916
Victor Stinner01b1cc12019-11-20 02:27:56 +0100917void
918PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000919{
Victor Stinner9da74302019-11-20 11:17:17 +0100920 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200921}
922
923
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300924void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100925_PyThreadState_DeleteCurrent(PyThreadState *tstate)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200926{
Victor Stinner3026cad2020-06-01 16:02:40 +0200927 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100928 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner9da74302019-11-20 11:17:17 +0100929 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200930 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100931 _PyEval_ReleaseLock(tstate);
932 PyMem_RawFree(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000933}
Guido van Rossum29757862001-01-23 01:46:06 +0000934
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300935void
936PyThreadState_DeleteCurrent(void)
937{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100938 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
939 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
940 _PyThreadState_DeleteCurrent(tstate);
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300941}
942
Guido van Rossum29757862001-01-23 01:46:06 +0000943
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200944/*
945 * Delete all thread states except the one passed as argument.
946 * Note that, if there is a current thread state, it *must* be the one
947 * passed as argument. Also, this won't touch any other interpreters
948 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000949 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200950 */
951void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200952_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200953{
954 PyInterpreterState *interp = tstate->interp;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100955
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200956 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200957 /* Remove all thread states, except tstate, from the linked list of
958 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200959 without holding the lock. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100960 PyThreadState *list = interp->tstate_head;
961 if (list == tstate) {
962 list = tstate->next;
963 }
964 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200965 tstate->prev->next = tstate->next;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100966 }
967 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200968 tstate->next->prev = tstate->prev;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100969 }
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200970 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200971 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200972 HEAD_UNLOCK(runtime);
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100973
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200974 /* Clear and deallocate all stale thread states. Even if this
975 executes Python code, we should be safe since it executes
976 in the current thread, not one of the stale threads. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100977 PyThreadState *p, *next;
978 for (p = list; p; p = next) {
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200979 next = p->next;
980 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200981 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200982 }
983}
984
985
Victor Stinnere838a932020-05-05 19:56:48 +0200986#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
987PyThreadState*
988_PyThreadState_GetTSS(void) {
989 return PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
990}
991#endif
992
993
Guido van Rossuma027efa1997-05-05 20:56:21 +0000994PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100995_PyThreadState_UncheckedGet(void)
996{
Victor Stinner50b48572018-11-01 01:51:40 +0100997 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100998}
999
1000
1001PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001002PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +00001003{
Victor Stinner50b48572018-11-01 01:51:40 +01001004 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +02001005 _Py_EnsureTstateNotNULL(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +00001007}
1008
1009
Victor Stinner09532fe2019-05-10 23:39:09 +02001010PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001011_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +00001012{
Victor Stinnere838a932020-05-05 19:56:48 +02001013#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1014 PyThreadState *oldts = _PyThreadState_GetTSS();
1015#else
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001016 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Victor Stinnere838a932020-05-05 19:56:48 +02001017#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +00001018
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001019 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 /* It should not be possible for more than one thread state
1021 to be used for a thread. Check this the best we can in debug
1022 builds.
1023 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02001024#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 if (newts) {
1026 /* This can be called from PyEval_RestoreThread(). Similar
1027 to it, we need to ensure errno doesn't change.
1028 */
1029 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001030 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (check && check->interp == newts->interp && check != newts)
1032 Py_FatalError("Invalid thread state for this thread");
1033 errno = err;
1034 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001035#endif
Victor Stinnere838a932020-05-05 19:56:48 +02001036#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1037 PyThread_tss_set(&gilstate->autoTSSkey, newts);
1038#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +00001040}
Guido van Rossumede04391998-04-10 20:18:25 +00001041
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001042PyThreadState *
1043PyThreadState_Swap(PyThreadState *newts)
1044{
1045 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
1046}
1047
Guido van Rossumede04391998-04-10 20:18:25 +00001048/* An extension mechanism to store arbitrary additional per-thread state.
1049 PyThreadState_GetDict() returns a dictionary that can be used to hold such
1050 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001051 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
1052 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +00001053
1054PyObject *
Victor Stinner0e427c62020-03-25 21:22:55 +01001055_PyThreadState_GetDict(PyThreadState *tstate)
1056{
1057 assert(tstate != NULL);
1058 if (tstate->dict == NULL) {
1059 tstate->dict = PyDict_New();
1060 if (tstate->dict == NULL) {
1061 _PyErr_Clear(tstate);
1062 }
1063 }
1064 return tstate->dict;
1065}
1066
1067
1068PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001069PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +00001070{
Victor Stinner50b48572018-11-01 01:51:40 +01001071 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner0e427c62020-03-25 21:22:55 +01001072 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 }
Victor Stinner0e427c62020-03-25 21:22:55 +01001075 return _PyThreadState_GetDict(tstate);
Guido van Rossumede04391998-04-10 20:18:25 +00001076}
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001077
1078
Victor Stinner8fb02b62020-03-13 23:38:08 +01001079PyInterpreterState *
1080PyThreadState_GetInterpreter(PyThreadState *tstate)
1081{
1082 assert(tstate != NULL);
Victor Stinner8fb02b62020-03-13 23:38:08 +01001083 return tstate->interp;
1084}
1085
1086
Victor Stinner4386b902020-04-29 03:01:43 +02001087PyFrameObject*
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001088PyThreadState_GetFrame(PyThreadState *tstate)
1089{
1090 assert(tstate != NULL);
Victor Stinner4386b902020-04-29 03:01:43 +02001091 PyFrameObject *frame = tstate->frame;
1092 Py_XINCREF(frame);
1093 return frame;
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001094}
1095
1096
Victor Stinner5c3cda02020-03-25 21:23:53 +01001097uint64_t
1098PyThreadState_GetID(PyThreadState *tstate)
1099{
1100 assert(tstate != NULL);
1101 return tstate->id;
1102}
1103
1104
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001105/* Asynchronously raise an exception in a thread.
1106 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001107 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001108 to call this, or use ctypes. Must be called with the GIL held.
1109 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1110 match any known thread id). Can be called with exc=NULL to clear an
1111 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001112
1113int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001114PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1115{
Victor Stinner09532fe2019-05-10 23:39:09 +02001116 _PyRuntimeState *runtime = &_PyRuntime;
1117 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 /* Although the GIL is held, a few C API functions can be called
1120 * without the GIL held, and in particular some that create and
1121 * destroy thread and interpreter states. Those can mutate the
1122 * list of thread states we're traversing, so to prevent that we lock
1123 * head_mutex for the duration.
1124 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001125 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001126 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1127 if (tstate->thread_id != id) {
1128 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001130
1131 /* Tricky: we need to decref the current value
1132 * (if any) in tstate->async_exc, but that can in turn
1133 * allow arbitrary Python code to run, including
1134 * perhaps calls to this function. To prevent
1135 * deadlock, we need to release head_mutex before
1136 * the decref.
1137 */
1138 PyObject *old_exc = tstate->async_exc;
1139 Py_XINCREF(exc);
1140 tstate->async_exc = exc;
1141 HEAD_UNLOCK(runtime);
1142
1143 Py_XDECREF(old_exc);
1144 _PyEval_SignalAsyncExc(tstate);
1145 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001147 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001149}
1150
1151
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001152/* Routines for advanced debuggers, requested by David Beazley.
1153 Don't use unless you know what you are doing! */
1154
1155PyInterpreterState *
1156PyInterpreterState_Head(void)
1157{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001158 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001159}
1160
1161PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001162PyInterpreterState_Main(void)
1163{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001164 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001165}
1166
1167PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001168PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001170}
1171
1172PyThreadState *
1173PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001175}
1176
1177PyThreadState *
1178PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001180}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001181
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001182/* The implementation of sys._current_frames(). This is intended to be
1183 called with the GIL held, as it will be when called via
1184 sys._current_frames(). It's possible it would work fine even without
1185 the GIL held, but haven't thought enough about that.
1186*/
1187PyObject *
1188_PyThread_CurrentFrames(void)
1189{
Victor Stinner71a35222020-03-26 22:46:14 +01001190 PyThreadState *tstate = _PyThreadState_GET();
1191 if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001192 return NULL;
1193 }
1194
Victor Stinner71a35222020-03-26 22:46:14 +01001195 PyObject *result = PyDict_New();
1196 if (result == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 return NULL;
Victor Stinner71a35222020-03-26 22:46:14 +01001198 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 /* for i in all interpreters:
1201 * for t in all of i's thread states:
1202 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001203 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 * need to grab head_mutex for the duration.
1205 */
Victor Stinner71a35222020-03-26 22:46:14 +01001206 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001207 HEAD_LOCK(runtime);
Victor Stinner71a35222020-03-26 22:46:14 +01001208 PyInterpreterState *i;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001209 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 PyThreadState *t;
1211 for (t = i->tstate_head; t != NULL; t = t->next) {
Victor Stinner4386b902020-04-29 03:01:43 +02001212 PyFrameObject *frame = t->frame;
Victor Stinner71a35222020-03-26 22:46:14 +01001213 if (frame == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 continue;
Victor Stinner71a35222020-03-26 22:46:14 +01001215 }
1216 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1217 if (id == NULL) {
1218 goto fail;
1219 }
1220 int stat = PyDict_SetItem(result, id, (PyObject *)frame);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 Py_DECREF(id);
Victor Stinner71a35222020-03-26 22:46:14 +01001222 if (stat < 0) {
1223 goto fail;
1224 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 }
1226 }
Victor Stinner71a35222020-03-26 22:46:14 +01001227 goto done;
1228
1229fail:
1230 Py_CLEAR(result);
1231
1232done:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001233 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001235}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001236
Julien Danjou64366fa2020-11-02 15:16:25 +01001237PyObject *
1238_PyThread_CurrentExceptions(void)
1239{
1240 PyThreadState *tstate = _PyThreadState_GET();
1241
1242 _Py_EnsureTstateNotNULL(tstate);
1243
1244 if (_PySys_Audit(tstate, "sys._current_exceptions", NULL) < 0) {
1245 return NULL;
1246 }
1247
1248 PyObject *result = PyDict_New();
1249 if (result == NULL) {
1250 return NULL;
1251 }
1252
1253 /* for i in all interpreters:
1254 * for t in all of i's thread states:
1255 * if t's frame isn't NULL, map t's id to its frame
1256 * Because these lists can mutate even when the GIL is held, we
1257 * need to grab head_mutex for the duration.
1258 */
1259 _PyRuntimeState *runtime = tstate->interp->runtime;
1260 HEAD_LOCK(runtime);
1261 PyInterpreterState *i;
1262 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
1263 PyThreadState *t;
1264 for (t = i->tstate_head; t != NULL; t = t->next) {
1265 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(t);
1266 if (err_info == NULL) {
1267 continue;
1268 }
1269 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1270 if (id == NULL) {
1271 goto fail;
1272 }
1273 PyObject *exc_info = PyTuple_Pack(
1274 3,
1275 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
1276 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
1277 err_info->exc_traceback != NULL ? err_info->exc_traceback : Py_None);
1278 if (exc_info == NULL) {
1279 Py_DECREF(id);
1280 goto fail;
1281 }
1282 int stat = PyDict_SetItem(result, id, exc_info);
1283 Py_DECREF(id);
1284 Py_DECREF(exc_info);
1285 if (stat < 0) {
1286 goto fail;
1287 }
1288 }
1289 }
1290 goto done;
1291
1292fail:
1293 Py_CLEAR(result);
1294
1295done:
1296 HEAD_UNLOCK(runtime);
1297 return result;
1298}
1299
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001300/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001301
1302/* Keep this as a static, as it is not reliable! It can only
1303 ever be compared to the state for the *current* thread.
1304 * If not equal, then it doesn't matter that the actual
1305 value may change immediately after comparison, as it can't
1306 possibly change to the current thread's state.
1307 * If equal, then the current thread holds the lock, so the value can't
1308 change until we yield the lock.
1309*/
1310static int
1311PyThreadState_IsCurrent(PyThreadState *tstate)
1312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001314 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001315 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1316 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001317}
1318
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001319/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001320 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001321*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001322PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001323_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001324{
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001325 if (!_Py_IsMainInterpreter(tstate)) {
1326 /* Currently, PyGILState is shared by all interpreters. The main
1327 * interpreter is responsible to initialize it. */
1328 return _PyStatus_OK();
1329 }
1330
Victor Stinner8bb32302019-04-24 16:47:40 +02001331 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001332 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001333 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001334
Victor Stinner01b1cc12019-11-20 02:27:56 +01001335 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001336
1337 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001338 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001339 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001340 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001341 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1342 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001343
Victor Stinner8bb32302019-04-24 16:47:40 +02001344 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001345 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001346}
1347
Victor Stinner861d9ab2016-03-16 22:45:24 +01001348PyInterpreterState *
1349_PyGILState_GetInterpreterStateUnsafe(void)
1350{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001351 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001352}
1353
Tim Peters19717fa2004-10-09 17:38:29 +00001354void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001355_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001356{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001357 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001358 PyThread_tss_delete(&gilstate->autoTSSkey);
1359 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001360}
1361
Victor Stinner26881c82020-06-02 15:51:37 +02001362#ifdef HAVE_FORK
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001363/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001364 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001365 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001366 */
Victor Stinner26881c82020-06-02 15:51:37 +02001367PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001368_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001369{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001370 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001371 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001372
1373 PyThread_tss_delete(&gilstate->autoTSSkey);
1374 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner26881c82020-06-02 15:51:37 +02001375 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001376 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001377
Charles-François Natalia233df82011-11-22 19:49:51 +01001378 /* If the thread had an associated auto thread state, reassociate it with
1379 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001380 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001381 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001382 {
Victor Stinner26881c82020-06-02 15:51:37 +02001383 return _PyStatus_ERR("failed to set autoTSSkey");
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001384 }
Victor Stinner26881c82020-06-02 15:51:37 +02001385 return _PyStatus_OK();
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001386}
Victor Stinner26881c82020-06-02 15:51:37 +02001387#endif
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001388
Michael W. Hudson188d4362005-06-20 16:52:57 +00001389/* When a thread state is created for a thread by some mechanism other than
1390 PyGILState_Ensure, it's important that the GILState machinery knows about
1391 it so it doesn't try to create another thread state for the thread (this is
1392 a better fix for SF bug #1010677 than the first one attempted).
1393*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001394static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001395_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001396{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001397 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001398 threadstate created in Py_Initialize(). Don't do anything for now
1399 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001400 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001402 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001403
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001404 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 The only situation where you can legitimately have more than one
1407 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001408 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001409
Victor Stinner590cebe2013-12-13 11:08:56 +01001410 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1411 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001412
Victor Stinner590cebe2013-12-13 11:08:56 +01001413 The first thread state created for that given OS level thread will
1414 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001416 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1417 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001418 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001419 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001420 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 /* PyGILState_Release must not try to delete this thread state. */
1423 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001424}
1425
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001426/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001427static PyThreadState *
1428_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1429{
1430 if (gilstate->autoInterpreterState == NULL)
1431 return NULL;
1432 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1433}
1434
Tim Peters19717fa2004-10-09 17:38:29 +00001435PyThreadState *
1436PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001437{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001438 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001439}
1440
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001441int
1442PyGILState_Check(void)
1443{
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001444 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1445 if (!gilstate->check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001446 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001447 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001448
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001449 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1450 return 1;
1451 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001452
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001453 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1454 if (tstate == NULL) {
1455 return 0;
1456 }
1457
1458 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001459}
1460
Tim Peters19717fa2004-10-09 17:38:29 +00001461PyGILState_STATE
1462PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001463{
Victor Stinner175a7042020-03-10 00:37:48 +01001464 _PyRuntimeState *runtime = &_PyRuntime;
1465 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 /* Note that we do not auto-init Python here - apart from
1468 potential races with 2 threads auto-initializing, pep-311
1469 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001470 called Py_Initialize(). */
1471
1472 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1473 called by Py_Initialize() */
Victor Stinnere838a932020-05-05 19:56:48 +02001474#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinner175a7042020-03-10 00:37:48 +01001475 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinnere838a932020-05-05 19:56:48 +02001476#endif
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001477 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001478
Victor Stinner175a7042020-03-10 00:37:48 +01001479 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1480 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001482 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001483 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001484 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001486 }
1487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 /* This is our thread state! We'll need to delete it in the
1489 matching call to PyGILState_Release(). */
1490 tcur->gilstate_counter = 0;
1491 current = 0; /* new thread state is never current */
1492 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001493 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001495 }
1496
1497 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001499 }
1500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 /* Update our counter in the thread-state - no need for locks:
1502 - tcur will remain valid as we hold the GIL.
1503 - the counter is safe as we are the only thread "allowed"
1504 to modify this value
1505 */
1506 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001509}
1510
Tim Peters19717fa2004-10-09 17:38:29 +00001511void
1512PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001513{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001514 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001515 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1516 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 Py_FatalError("auto-releasing thread-state, "
1518 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001519 }
1520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 /* We must hold the GIL and have our thread state current */
1522 /* XXX - remove the check - the assert should be fine,
1523 but while this is very new (April 2003), the extra check
1524 by release-only users can't hurt.
1525 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001526 if (!PyThreadState_IsCurrent(tstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001527 _Py_FatalErrorFormat(__func__,
1528 "thread state %p must be current when releasing",
1529 tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001530 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001531 assert(PyThreadState_IsCurrent(tstate));
1532 --tstate->gilstate_counter;
1533 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 /* If we're going to destroy this thread-state, we must
1536 * clear it while the GIL is held, as destructors may run.
1537 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001538 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 /* can't have been locked when we created it */
1540 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001541 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 /* Delete the thread-state. Note this releases the GIL too!
1543 * It's vital that the GIL be held here, to avoid shutdown
1544 * races; see bugs 225673 and 1061968 (that nasty bug has a
1545 * habit of coming back).
1546 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001547 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1548 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 }
1550 /* Release the lock if necessary */
1551 else if (oldstate == PyGILState_UNLOCKED)
1552 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001553}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001554
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001555
Eric Snow7f8bfc92018-01-29 18:23:44 -07001556/**************************/
1557/* cross-interpreter data */
1558/**************************/
1559
1560/* cross-interpreter data */
1561
1562crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1563
1564/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1565 to keep the registry code separate. */
1566static crossinterpdatafunc
1567_lookup_getdata(PyObject *obj)
1568{
1569 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1570 if (getdata == NULL && PyErr_Occurred() == 0)
1571 PyErr_Format(PyExc_ValueError,
1572 "%S does not support cross-interpreter data", obj);
1573 return getdata;
1574}
1575
1576int
1577_PyObject_CheckCrossInterpreterData(PyObject *obj)
1578{
1579 crossinterpdatafunc getdata = _lookup_getdata(obj);
1580 if (getdata == NULL) {
1581 return -1;
1582 }
1583 return 0;
1584}
1585
1586static int
Victor Stinner71a35222020-03-26 22:46:14 +01001587_check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001588{
1589 // data->data can be anything, including NULL, so we don't check it.
1590
1591 // data->obj may be NULL, so we don't check it.
1592
1593 if (data->interp < 0) {
Victor Stinner71a35222020-03-26 22:46:14 +01001594 _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001595 return -1;
1596 }
1597
1598 if (data->new_object == NULL) {
Victor Stinner71a35222020-03-26 22:46:14 +01001599 _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001600 return -1;
1601 }
1602
1603 // data->free may be NULL, so we don't check it.
1604
1605 return 0;
1606}
1607
1608int
1609_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1610{
Victor Stinner71a35222020-03-26 22:46:14 +01001611 // PyThreadState_Get() aborts if tstate is NULL.
1612 PyThreadState *tstate = PyThreadState_Get();
1613 PyInterpreterState *interp = tstate->interp;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001614
1615 // Reset data before re-populating.
1616 *data = (_PyCrossInterpreterData){0};
1617 data->free = PyMem_RawFree; // Set a default that may be overridden.
1618
1619 // Call the "getdata" func for the object.
1620 Py_INCREF(obj);
1621 crossinterpdatafunc getdata = _lookup_getdata(obj);
1622 if (getdata == NULL) {
1623 Py_DECREF(obj);
1624 return -1;
1625 }
1626 int res = getdata(obj, data);
1627 Py_DECREF(obj);
1628 if (res != 0) {
1629 return -1;
1630 }
1631
1632 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001633 data->interp = interp->id;
Victor Stinner71a35222020-03-26 22:46:14 +01001634 if (_check_xidata(tstate, data) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001635 _PyCrossInterpreterData_Release(data);
1636 return -1;
1637 }
1638
1639 return 0;
1640}
1641
Victor Stinnere225beb2019-06-03 18:14:24 +02001642static void
Eric Snow63799132018-06-01 18:45:20 -06001643_release_xidata(void *arg)
1644{
1645 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1646 if (data->free != NULL) {
1647 data->free(data->data);
1648 }
1649 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001650}
1651
1652static void
1653_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1654 PyInterpreterState *interp,
1655 void (*func)(void *), void *arg)
1656{
1657 /* We would use Py_AddPendingCall() if it weren't specific to the
1658 * main interpreter (see bpo-33608). In the meantime we take a
1659 * naive approach.
1660 */
1661 PyThreadState *save_tstate = NULL;
1662 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1663 // XXX Using the "head" thread isn't strictly correct.
1664 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1665 // XXX Possible GILState issues?
1666 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1667 }
1668
1669 func(arg);
1670
1671 // Switch back.
1672 if (save_tstate != NULL) {
1673 _PyThreadState_Swap(gilstate, save_tstate);
1674 }
Eric Snow63799132018-06-01 18:45:20 -06001675}
1676
Eric Snow7f8bfc92018-01-29 18:23:44 -07001677void
1678_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1679{
1680 if (data->data == NULL && data->obj == NULL) {
1681 // Nothing to release!
1682 return;
1683 }
1684
Victor Stinnere225beb2019-06-03 18:14:24 +02001685 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001686 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1687 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001688 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001689 if (data->free != NULL) {
1690 // XXX Someone leaked some memory...
1691 }
1692 return;
1693 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001694
Eric Snow7f8bfc92018-01-29 18:23:44 -07001695 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001696 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1697 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001698}
1699
1700PyObject *
1701_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1702{
1703 return data->new_object(data);
1704}
1705
1706/* registry of {type -> crossinterpdatafunc} */
1707
1708/* For now we use a global registry of shareable classes. An
1709 alternative would be to add a tp_* slot for a class's
1710 crossinterpdatafunc. It would be simpler and more efficient. */
1711
1712static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001713_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1714 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001715{
1716 // Note that we effectively replace already registered classes
1717 // rather than failing.
1718 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1719 if (newhead == NULL)
1720 return -1;
1721 newhead->cls = cls;
1722 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001723 newhead->next = xidregistry->head;
1724 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001725 return 0;
1726}
1727
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001728static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001729
1730int
Eric Snowc11183c2019-03-15 16:35:46 -06001731_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001732 crossinterpdatafunc getdata)
1733{
1734 if (!PyType_Check(cls)) {
1735 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1736 return -1;
1737 }
1738 if (getdata == NULL) {
1739 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1740 return -1;
1741 }
1742
1743 // Make sure the class isn't ever deallocated.
1744 Py_INCREF((PyObject *)cls);
1745
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001746 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1747 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1748 if (xidregistry->head == NULL) {
1749 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001750 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001751 int res = _register_xidata(xidregistry, cls, getdata);
1752 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001753 return res;
1754}
1755
Eric Snow6d2cd902018-05-16 15:04:57 -04001756/* Cross-interpreter objects are looked up by exact match on the class.
1757 We can reassess this policy when we move from a global registry to a
1758 tp_* slot. */
1759
Eric Snow7f8bfc92018-01-29 18:23:44 -07001760crossinterpdatafunc
1761_PyCrossInterpreterData_Lookup(PyObject *obj)
1762{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001763 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001764 PyObject *cls = PyObject_Type(obj);
1765 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001766 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1767 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001768 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001769 _register_builtins_for_crossinterpreter_data(xidregistry);
1770 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001771 }
1772 for(; cur != NULL; cur = cur->next) {
1773 if (cur->cls == (PyTypeObject *)cls) {
1774 getdata = cur->getdata;
1775 break;
1776 }
1777 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001778 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001779 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001780 return getdata;
1781}
1782
1783/* cross-interpreter data for builtin types */
1784
Eric Snow6d2cd902018-05-16 15:04:57 -04001785struct _shared_bytes_data {
1786 char *bytes;
1787 Py_ssize_t len;
1788};
1789
Eric Snow7f8bfc92018-01-29 18:23:44 -07001790static PyObject *
1791_new_bytes_object(_PyCrossInterpreterData *data)
1792{
Eric Snow6d2cd902018-05-16 15:04:57 -04001793 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1794 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001795}
1796
1797static int
1798_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1799{
Eric Snow6d2cd902018-05-16 15:04:57 -04001800 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1801 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1802 return -1;
1803 }
1804 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001805 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001806 data->obj = obj; // Will be "released" (decref'ed) when data released.
1807 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001808 data->free = PyMem_Free;
1809 return 0;
1810}
1811
1812struct _shared_str_data {
1813 int kind;
1814 const void *buffer;
1815 Py_ssize_t len;
1816};
1817
1818static PyObject *
1819_new_str_object(_PyCrossInterpreterData *data)
1820{
1821 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1822 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1823}
1824
1825static int
1826_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1827{
1828 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1829 shared->kind = PyUnicode_KIND(obj);
1830 shared->buffer = PyUnicode_DATA(obj);
An Long29c11722020-06-13 20:26:01 +08001831 shared->len = PyUnicode_GET_LENGTH(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001832 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001833 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001834 data->obj = obj; // Will be "released" (decref'ed) when data released.
1835 data->new_object = _new_str_object;
1836 data->free = PyMem_Free;
1837 return 0;
1838}
1839
1840static PyObject *
1841_new_long_object(_PyCrossInterpreterData *data)
1842{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001843 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001844}
1845
1846static int
1847_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1848{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001849 /* Note that this means the size of shareable ints is bounded by
1850 * sys.maxsize. Hence on 32-bit architectures that is half the
1851 * size of maximum shareable ints on 64-bit.
1852 */
1853 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001854 if (value == -1 && PyErr_Occurred()) {
1855 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1856 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1857 }
1858 return -1;
1859 }
1860 data->data = (void *)value;
1861 data->obj = NULL;
1862 data->new_object = _new_long_object;
1863 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001864 return 0;
1865}
1866
1867static PyObject *
1868_new_none_object(_PyCrossInterpreterData *data)
1869{
1870 // XXX Singleton refcounts are problematic across interpreters...
1871 Py_INCREF(Py_None);
1872 return Py_None;
1873}
1874
1875static int
1876_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1877{
1878 data->data = NULL;
1879 // data->obj remains NULL
1880 data->new_object = _new_none_object;
1881 data->free = NULL; // There is nothing to free.
1882 return 0;
1883}
1884
1885static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001886_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001887{
1888 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001889 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001890 Py_FatalError("could not register None for cross-interpreter sharing");
1891 }
1892
Eric Snow6d2cd902018-05-16 15:04:57 -04001893 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001894 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001895 Py_FatalError("could not register int for cross-interpreter sharing");
1896 }
1897
Eric Snow7f8bfc92018-01-29 18:23:44 -07001898 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001899 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001900 Py_FatalError("could not register bytes for cross-interpreter sharing");
1901 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001902
1903 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001904 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001905 Py_FatalError("could not register str for cross-interpreter sharing");
1906 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001907}
1908
1909
Victor Stinner0b72b232020-03-12 23:18:39 +01001910_PyFrameEvalFunction
1911_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1912{
1913 return interp->eval_frame;
1914}
1915
1916
1917void
1918_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1919 _PyFrameEvalFunction eval_frame)
1920{
1921 interp->eval_frame = eval_frame;
1922}
1923
Victor Stinnerda7933e2020-04-13 03:04:28 +02001924
1925const PyConfig*
1926_PyInterpreterState_GetConfig(PyInterpreterState *interp)
1927{
1928 return &interp->config;
1929}
1930
1931
Victor Stinner048a3562020-11-05 00:45:56 +01001932int
1933_PyInterpreterState_GetConfigCopy(PyConfig *config)
Victor Stinnerda7933e2020-04-13 03:04:28 +02001934{
Victor Stinner048a3562020-11-05 00:45:56 +01001935 PyInterpreterState *interp = PyInterpreterState_Get();
1936
1937 PyStatus status = _PyConfig_Copy(config, &interp->config);
1938 if (PyStatus_Exception(status)) {
1939 _PyErr_SetFromPyStatus(status);
1940 return -1;
1941 }
1942 return 0;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001943}
1944
1945
1946const PyConfig*
1947_Py_GetConfig(void)
1948{
1949 assert(PyGILState_Check());
1950 PyThreadState *tstate = _PyThreadState_GET();
1951 return _PyInterpreterState_GetConfig(tstate->interp);
1952}
1953
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001954#ifdef __cplusplus
1955}
1956#endif