blob: 8da583f8e06bc0c20c7e2bf99cb9ac4e52209b2d [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 Stinner331a6a52019-05-27 16:39:22 +020076 return _PyStatus_ERR("Can't initialize threads for interpreter");
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 Stinner331a6a52019-05-27 16:39:22 +020082 return _PyStatus_ERR("Can't initialize threads for cross-interpreter data registry");
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 Stinner331a6a52019-05-27 16:39:22 +020088 return _PyStatus_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060089}
Eric Snow05351c12017-09-05 21:43:08 -070090
Victor Stinner331a6a52019-05-27 16:39:22 +020091PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010092_PyRuntimeState_Init(_PyRuntimeState *runtime)
93{
94 /* Force default allocator, since _PyRuntimeState_Fini() must
95 use the same allocator than this function. */
96 PyMemAllocatorEx old_alloc;
97 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
98
Victor Stinner331a6a52019-05-27 16:39:22 +020099 PyStatus status = _PyRuntimeState_Init_impl(runtime);
Victor Stinner5d39e042017-11-29 17:20:38 +0100100
101 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinner331a6a52019-05-27 16:39:22 +0200102 return status;
Victor Stinner5d39e042017-11-29 17:20:38 +0100103}
104
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600105void
106_PyRuntimeState_Fini(_PyRuntimeState *runtime)
107{
Victor Stinner5d39e042017-11-29 17:20:38 +0100108 /* Force the allocator used by _PyRuntimeState_Init(). */
109 PyMemAllocatorEx old_alloc;
110 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -0800111
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600112 if (runtime->interpreters.mutex != NULL) {
113 PyThread_free_lock(runtime->interpreters.mutex);
114 runtime->interpreters.mutex = NULL;
115 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800116
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100117 if (runtime->xidregistry.mutex != NULL) {
118 PyThread_free_lock(runtime->xidregistry.mutex);
119 runtime->xidregistry.mutex = NULL;
120 }
121
Victor Stinnerccb04422017-11-16 03:20:31 -0800122 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600123}
124
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900125#ifdef HAVE_FORK
Eric Snow8479a342019-03-08 23:44:33 -0700126/* This function is called from PyOS_AfterFork_Child to ensure that
Victor Stinner26881c82020-06-02 15:51:37 +0200127 newly created child processes do not share locks with the parent. */
128PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200129_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700130{
131 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200132 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700133
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200134 /* Force default allocator, since _PyRuntimeState_Fini() must
135 use the same allocator than this function. */
136 PyMemAllocatorEx old_alloc;
137 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
138
Victor Stinner26881c82020-06-02 15:51:37 +0200139 int reinit_interp = _PyThread_at_fork_reinit(&runtime->interpreters.mutex);
140 int reinit_main_id = _PyThread_at_fork_reinit(&runtime->interpreters.main->id_mutex);
141 int reinit_xidregistry = _PyThread_at_fork_reinit(&runtime->xidregistry.mutex);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200142
143 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
144
Victor Stinner26881c82020-06-02 15:51:37 +0200145 if (reinit_interp < 0
146 || reinit_main_id < 0
147 || reinit_xidregistry < 0)
148 {
149 return _PyStatus_ERR("Failed to reinitialize runtime locks");
Eric Snow8479a342019-03-08 23:44:33 -0700150
Eric Snow8479a342019-03-08 23:44:33 -0700151 }
Victor Stinner26881c82020-06-02 15:51:37 +0200152 return _PyStatus_OK();
Eric Snow8479a342019-03-08 23:44:33 -0700153}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900154#endif
Eric Snow8479a342019-03-08 23:44:33 -0700155
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200156#define HEAD_LOCK(runtime) \
157 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
158#define HEAD_UNLOCK(runtime) \
159 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700160
Victor Stinner8bb32302019-04-24 16:47:40 +0200161/* Forward declaration */
162static void _PyGILState_NoteThreadState(
163 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000164
Victor Stinner331a6a52019-05-27 16:39:22 +0200165PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600166_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700167{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200168 struct pyinterpreters *interpreters = &runtime->interpreters;
169 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100170
171 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
172 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200173 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100174 /* Force default allocator, since _PyRuntimeState_Fini() must
175 use the same allocator than this function. */
176 PyMemAllocatorEx old_alloc;
177 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
178
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200179 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100180
181 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
182
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200183 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200184 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800185 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600186 }
Victor Stinner5d926472018-03-06 14:31:37 +0100187
Victor Stinner331a6a52019-05-27 16:39:22 +0200188 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700189}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000190
191PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000192PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000193{
Victor Stinner71a35222020-03-26 22:46:14 +0100194 PyThreadState *tstate = _PyThreadState_GET();
195 /* tstate is NULL when Py_InitializeFromConfig() calls
196 PyInterpreterState_New() to create the main interpreter. */
197 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_New", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700198 return NULL;
199 }
200
Andy Lester7668a8b2020-03-24 23:26:44 -0500201 PyInterpreterState *interp = PyMem_RawCalloc(1, sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100202 if (interp == NULL) {
203 return NULL;
204 }
205
Eric Snow4c6955e2018-02-16 18:53:40 -0700206 interp->id_refcount = -1;
Victor Stinner022be022019-05-22 23:58:50 +0200207
Victor Stinner71a35222020-03-26 22:46:14 +0100208 /* Don't get runtime from tstate since tstate can be NULL */
Victor Stinner01b1cc12019-11-20 02:27:56 +0100209 _PyRuntimeState *runtime = &_PyRuntime;
210 interp->runtime = runtime;
211
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200212 if (_PyEval_InitState(&interp->ceval) < 0) {
213 goto out_of_memory;
214 }
215
Victor Stinner72474072019-11-20 12:25:50 +0100216 _PyGC_InitState(&interp->gc);
Victor Stinner8462a492019-10-01 12:06:16 +0200217 PyConfig_InitPythonConfig(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200218
Victor Stinnerd4341102017-11-23 00:12:09 +0100219 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000220#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300221#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100222 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000223#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100224 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000225#endif
226#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000227
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200228 struct pyinterpreters *interpreters = &runtime->interpreters;
229
230 HEAD_LOCK(runtime);
231 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100232 /* overflow or Py_Initialize() not called! */
Victor Stinner71a35222020-03-26 22:46:14 +0100233 if (tstate != NULL) {
234 _PyErr_SetString(tstate, PyExc_RuntimeError,
235 "failed to get an interpreter ID");
236 }
Pablo Galindo95d630e2018-08-31 22:49:29 +0100237 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100238 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100239 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200240 else {
241 interp->id = interpreters->next_id;
242 interpreters->next_id += 1;
243 interp->next = interpreters->head;
244 if (interpreters->main == NULL) {
245 interpreters->main = interp;
246 }
247 interpreters->head = interp;
248 }
249 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000250
Pablo Galindo95d630e2018-08-31 22:49:29 +0100251 if (interp == NULL) {
252 return NULL;
253 }
254
Yury Selivanovf23746a2018-01-22 19:11:18 -0500255 interp->tstate_next_unique_id = 0;
256
Steve Dowerb82e17e2019-05-23 08:45:22 -0700257 interp->audit_hooks = NULL;
258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 return interp;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200260
261out_of_memory:
262 if (tstate != NULL) {
263 _PyErr_NoMemory(tstate);
264 }
265
266 PyMem_RawFree(interp);
267 return NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000268}
269
270
Victor Stinnereba5bf22020-10-30 22:51:02 +0100271static void
272interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000273{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100274 _PyRuntimeState *runtime = interp->runtime;
275
Victor Stinner71a35222020-03-26 22:46:14 +0100276 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_Clear", NULL) < 0) {
277 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700278 }
279
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200280 HEAD_LOCK(runtime);
281 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200283 }
284 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700285
286 Py_CLEAR(interp->audit_hooks);
287
Victor Stinner331a6a52019-05-27 16:39:22 +0200288 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 Py_CLEAR(interp->codec_search_path);
290 Py_CLEAR(interp->codec_search_cache);
291 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700292 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 Py_CLEAR(interp->modules_by_index);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200294 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400295 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300296 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600297 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200298#ifdef HAVE_FORK
299 Py_CLEAR(interp->before_forkers);
300 Py_CLEAR(interp->after_forkers_parent);
301 Py_CLEAR(interp->after_forkers_child);
302#endif
Victor Stinnerfd957c12020-11-03 18:07:15 +0100303
304 _PyAST_Fini(interp);
305 _PyWarnings_Fini(interp);
306
307 // All Python types must be destroyed before the last GC collection. Python
308 // types create a reference cycle to themselves in their in their
309 // PyTypeObject.tp_mro member (the tuple contains the type).
Victor Stinnereba5bf22020-10-30 22:51:02 +0100310
311 /* Last garbage collection on this interpreter */
312 _PyGC_CollectNoFail(tstate);
Victor Stinnereba5bf22020-10-30 22:51:02 +0100313 _PyGC_Fini(tstate);
314
Hai Shi8ecc0c42020-08-13 05:23:30 +0800315 /* We don't clear sysdict and builtins until the end of this function.
316 Because clearing other attributes can execute arbitrary Python code
317 which requires sysdict and builtins. */
318 PyDict_Clear(interp->sysdict);
319 PyDict_Clear(interp->builtins);
320 Py_CLEAR(interp->sysdict);
321 Py_CLEAR(interp->builtins);
322
Eric Snow5be45a62019-03-08 22:47:07 -0700323 // XXX Once we have one allocator per interpreter (i.e.
324 // per-interpreter GC) we must ensure that all of the interpreter's
325 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000326}
327
328
Victor Stinnereba5bf22020-10-30 22:51:02 +0100329void
330PyInterpreterState_Clear(PyInterpreterState *interp)
331{
332 // Use the current Python thread state to call audit hooks and to collect
333 // garbage. It can be different than the current Python thread state
334 // of 'interp'.
335 PyThreadState *current_tstate = _PyThreadState_GET();
336
337 interpreter_clear(interp, current_tstate);
338}
339
340
341void
342_PyInterpreterState_Clear(PyThreadState *tstate)
343{
344 interpreter_clear(tstate->interp, tstate);
345}
346
347
Guido van Rossum25ce5661997-08-02 03:10:38 +0000348static void
Victor Stinner9da74302019-11-20 11:17:17 +0100349zapthreads(PyInterpreterState *interp, int check_current)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000350{
Victor Stinner9da74302019-11-20 11:17:17 +0100351 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 /* No need to lock the mutex here because this should only happen
353 when the threads are all really dead (XXX famous last words). */
Victor Stinner9da74302019-11-20 11:17:17 +0100354 while ((tstate = interp->tstate_head) != NULL) {
355 _PyThreadState_Delete(tstate, check_current);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000357}
358
359
Victor Stinner01b1cc12019-11-20 02:27:56 +0100360void
361PyInterpreterState_Delete(PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200362{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100363 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200364 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner9da74302019-11-20 11:17:17 +0100365 zapthreads(interp, 0);
366
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200367 _PyEval_FiniState(&interp->ceval);
368
Victor Stinner9da74302019-11-20 11:17:17 +0100369 /* Delete current thread. After this, many C API calls become crashy. */
370 _PyThreadState_Swap(&runtime->gilstate, NULL);
371
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200372 HEAD_LOCK(runtime);
373 PyInterpreterState **p;
374 for (p = &interpreters->head; ; p = &(*p)->next) {
375 if (*p == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100376 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200377 }
378 if (*p == interp) {
379 break;
380 }
381 }
382 if (interp->tstate_head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100383 Py_FatalError("remaining threads");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200384 }
385 *p = interp->next;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200386
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200387 if (interpreters->main == interp) {
388 interpreters->main = NULL;
389 if (interpreters->head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100390 Py_FatalError("remaining subinterpreters");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200391 }
392 }
393 HEAD_UNLOCK(runtime);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200394
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200395 if (interp->id_mutex != NULL) {
396 PyThread_free_lock(interp->id_mutex);
397 }
398 PyMem_RawFree(interp);
399}
400
401
Victor Stinner26881c82020-06-02 15:51:37 +0200402#ifdef HAVE_FORK
Eric Snow59032962018-09-14 14:17:20 -0700403/*
404 * Delete all interpreter states except the main interpreter. If there
405 * is a current interpreter state, it *must* be the main interpreter.
406 */
Victor Stinner26881c82020-06-02 15:51:37 +0200407PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200408_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700409{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200410 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200411 struct pyinterpreters *interpreters = &runtime->interpreters;
412
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200413 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200414 if (tstate != NULL && tstate->interp != interpreters->main) {
Victor Stinner26881c82020-06-02 15:51:37 +0200415 return _PyStatus_ERR("not main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700416 }
417
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200418 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200419 PyInterpreterState *interp = interpreters->head;
420 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100421 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200422 if (interp == interpreters->main) {
423 interpreters->main->next = NULL;
424 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100425 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700426 continue;
427 }
428
Victor Stinner01b1cc12019-11-20 02:27:56 +0100429 PyInterpreterState_Clear(interp); // XXX must activate?
Victor Stinner9da74302019-11-20 11:17:17 +0100430 zapthreads(interp, 1);
Eric Snow59032962018-09-14 14:17:20 -0700431 if (interp->id_mutex != NULL) {
432 PyThread_free_lock(interp->id_mutex);
433 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100434 PyInterpreterState *prev_interp = interp;
435 interp = interp->next;
436 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700437 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200438 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700439
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200440 if (interpreters->head == NULL) {
Victor Stinner26881c82020-06-02 15:51:37 +0200441 return _PyStatus_ERR("missing main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700442 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200443 _PyThreadState_Swap(gilstate, tstate);
Victor Stinner26881c82020-06-02 15:51:37 +0200444 return _PyStatus_OK();
Eric Snow59032962018-09-14 14:17:20 -0700445}
Victor Stinner26881c82020-06-02 15:51:37 +0200446#endif
Eric Snow59032962018-09-14 14:17:20 -0700447
448
Victor Stinnercaba55b2018-08-03 15:33:52 +0200449PyInterpreterState *
Victor Stinnerbe793732020-03-13 18:15:33 +0100450PyInterpreterState_Get(void)
Victor Stinnercaba55b2018-08-03 15:33:52 +0200451{
Victor Stinner50b48572018-11-01 01:51:40 +0100452 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200453 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200454 PyInterpreterState *interp = tstate->interp;
455 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100456 Py_FatalError("no current interpreter");
Victor Stinnercaba55b2018-08-03 15:33:52 +0200457 }
458 return interp;
459}
460
461
Eric Snowe3774162017-05-22 19:46:40 -0700462int64_t
463PyInterpreterState_GetID(PyInterpreterState *interp)
464{
465 if (interp == NULL) {
466 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
467 return -1;
468 }
469 return interp->id;
470}
471
472
Eric Snow5be45a62019-03-08 22:47:07 -0700473static PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200474interp_look_up_id(_PyRuntimeState *runtime, int64_t requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700475{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200476 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100477 while (interp != NULL) {
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200478 int64_t id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700479 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100480 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700481 }
482 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100483 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700484 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100485 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700486 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100487 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700488}
489
Eric Snow5be45a62019-03-08 22:47:07 -0700490PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200491_PyInterpreterState_LookUpID(int64_t requested_id)
Eric Snow5be45a62019-03-08 22:47:07 -0700492{
493 PyInterpreterState *interp = NULL;
494 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200495 _PyRuntimeState *runtime = &_PyRuntime;
496 HEAD_LOCK(runtime);
497 interp = interp_look_up_id(runtime, requested_id);
498 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700499 }
500 if (interp == NULL && !PyErr_Occurred()) {
501 PyErr_Format(PyExc_RuntimeError,
502 "unrecognized interpreter ID %lld", requested_id);
503 }
504 return interp;
505}
506
Eric Snow4c6955e2018-02-16 18:53:40 -0700507
508int
509_PyInterpreterState_IDInitref(PyInterpreterState *interp)
510{
511 if (interp->id_mutex != NULL) {
512 return 0;
513 }
514 interp->id_mutex = PyThread_allocate_lock();
515 if (interp->id_mutex == NULL) {
516 PyErr_SetString(PyExc_RuntimeError,
517 "failed to create init interpreter ID mutex");
518 return -1;
519 }
520 interp->id_refcount = 0;
521 return 0;
522}
523
524
525void
526_PyInterpreterState_IDIncref(PyInterpreterState *interp)
527{
528 if (interp->id_mutex == NULL) {
529 return;
530 }
531 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
532 interp->id_refcount += 1;
533 PyThread_release_lock(interp->id_mutex);
534}
535
536
537void
538_PyInterpreterState_IDDecref(PyInterpreterState *interp)
539{
540 if (interp->id_mutex == NULL) {
541 return;
542 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200543 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700544 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
545 assert(interp->id_refcount != 0);
546 interp->id_refcount -= 1;
547 int64_t refcount = interp->id_refcount;
548 PyThread_release_lock(interp->id_mutex);
549
Eric Snowc11183c2019-03-15 16:35:46 -0600550 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700551 // XXX Using the "head" thread isn't strictly correct.
552 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
553 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200554 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700555 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200556 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700557 }
558}
559
Eric Snowc11183c2019-03-15 16:35:46 -0600560int
561_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
562{
563 return interp->requires_idref;
564}
565
566void
567_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
568{
569 interp->requires_idref = required ? 1 : 0;
570}
571
Eric Snowc11183c2019-03-15 16:35:46 -0600572PyObject *
573_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
574{
575 if (interp->modules == NULL) {
576 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
577 return NULL;
578 }
579 return PyMapping_GetItemString(interp->modules, "__main__");
580}
581
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600582PyObject *
583PyInterpreterState_GetDict(PyInterpreterState *interp)
584{
585 if (interp->dict == NULL) {
586 interp->dict = PyDict_New();
587 if (interp->dict == NULL) {
588 PyErr_Clear();
589 }
590 }
591 /* Returning NULL means no per-interpreter dict is available. */
592 return interp->dict;
593}
594
Victor Stinner45b9be52010-03-03 23:28:07 +0000595static PyThreadState *
596new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000597{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100598 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200599 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200600 if (tstate == NULL) {
601 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000603
Victor Stinner8bb32302019-04-24 16:47:40 +0200604 tstate->interp = interp;
605
606 tstate->frame = NULL;
607 tstate->recursion_depth = 0;
Mark Shannon4e7a69b2020-12-02 13:30:55 +0000608 tstate->recursion_headroom = 0;
Victor Stinner8bb32302019-04-24 16:47:40 +0200609 tstate->stackcheck_counter = 0;
610 tstate->tracing = 0;
611 tstate->use_tracing = 0;
612 tstate->gilstate_counter = 0;
613 tstate->async_exc = NULL;
614 tstate->thread_id = PyThread_get_thread_ident();
615
616 tstate->dict = NULL;
617
618 tstate->curexc_type = NULL;
619 tstate->curexc_value = NULL;
620 tstate->curexc_traceback = NULL;
621
622 tstate->exc_state.exc_type = NULL;
623 tstate->exc_state.exc_value = NULL;
624 tstate->exc_state.exc_traceback = NULL;
625 tstate->exc_state.previous_item = NULL;
626 tstate->exc_info = &tstate->exc_state;
627
628 tstate->c_profilefunc = NULL;
629 tstate->c_tracefunc = NULL;
630 tstate->c_profileobj = NULL;
631 tstate->c_traceobj = NULL;
632
633 tstate->trash_delete_nesting = 0;
634 tstate->trash_delete_later = NULL;
635 tstate->on_delete = NULL;
636 tstate->on_delete_data = NULL;
637
638 tstate->coroutine_origin_tracking_depth = 0;
639
Victor Stinner8bb32302019-04-24 16:47:40 +0200640 tstate->async_gen_firstiter = NULL;
641 tstate->async_gen_finalizer = NULL;
642
643 tstate->context = NULL;
644 tstate->context_ver = 1;
645
Victor Stinner8bb32302019-04-24 16:47:40 +0200646 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100647 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200648 }
649
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200650 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100651 tstate->id = ++interp->tstate_next_unique_id;
Victor Stinner8bb32302019-04-24 16:47:40 +0200652 tstate->prev = NULL;
653 tstate->next = interp->tstate_head;
654 if (tstate->next)
655 tstate->next->prev = tstate;
656 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200657 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000660}
661
Victor Stinner45b9be52010-03-03 23:28:07 +0000662PyThreadState *
663PyThreadState_New(PyInterpreterState *interp)
664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000666}
667
668PyThreadState *
669_PyThreadState_Prealloc(PyInterpreterState *interp)
670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000672}
673
674void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100675_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000676{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100677 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000678}
679
Martin v. Löwis1a214512008-06-11 05:26:20 +0000680PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200681PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000682{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200683 Py_ssize_t index = module->m_base.m_index;
Victor Stinner81a7be32020-04-14 15:14:01 +0200684 PyInterpreterState *state = _PyInterpreterState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000686 if (module->m_slots) {
687 return NULL;
688 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 if (index == 0)
690 return NULL;
691 if (state->modules_by_index == NULL)
692 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200693 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 return NULL;
695 res = PyList_GET_ITEM(state->modules_by_index, index);
696 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000697}
698
699int
Victor Stinner82c83bd2019-11-22 18:52:27 +0100700_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000701{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300702 if (!def) {
Victor Stinner71a35222020-03-26 22:46:14 +0100703 assert(_PyErr_Occurred(tstate));
Berker Peksag4b7b5652016-08-22 18:05:56 +0300704 return -1;
705 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000706 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100707 _PyErr_SetString(tstate,
708 PyExc_SystemError,
709 "PyState_AddModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000710 return -1;
711 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100712
713 PyInterpreterState *interp = tstate->interp;
714 if (!interp->modules_by_index) {
715 interp->modules_by_index = PyList_New(0);
716 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100718 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100720
721 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
722 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100724 }
725 }
726
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100728 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000730}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000731
Martin v. Löwis7800f752012-06-22 12:20:55 +0200732int
733PyState_AddModule(PyObject* module, struct PyModuleDef* def)
734{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200735 if (!def) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100736 Py_FatalError("module definition is NULL");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200737 return -1;
738 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100739
740 PyThreadState *tstate = _PyThreadState_GET();
741 PyInterpreterState *interp = tstate->interp;
742 Py_ssize_t index = def->m_base.m_index;
743 if (interp->modules_by_index &&
744 index < PyList_GET_SIZE(interp->modules_by_index) &&
745 module == PyList_GET_ITEM(interp->modules_by_index, index))
746 {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100747 _Py_FatalErrorFormat(__func__, "module %p already added", module);
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100748 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200749 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100750 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200751}
752
753int
754PyState_RemoveModule(struct PyModuleDef* def)
755{
Victor Stinner71a35222020-03-26 22:46:14 +0100756 PyThreadState *tstate = _PyThreadState_GET();
757 PyInterpreterState *interp = tstate->interp;
758
Nick Coghland5cacbb2015-05-23 22:24:10 +1000759 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100760 _PyErr_SetString(tstate,
761 PyExc_SystemError,
762 "PyState_RemoveModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000763 return -1;
764 }
Victor Stinner71a35222020-03-26 22:46:14 +0100765
766 Py_ssize_t index = def->m_base.m_index;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200767 if (index == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100768 Py_FatalError("invalid module index");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200769 }
Victor Stinner71a35222020-03-26 22:46:14 +0100770 if (interp->modules_by_index == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100771 Py_FatalError("Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200772 }
Victor Stinner71a35222020-03-26 22:46:14 +0100773 if (index > PyList_GET_SIZE(interp->modules_by_index)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100774 Py_FatalError("Module index out of bounds.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200775 }
Victor Stinner71a35222020-03-26 22:46:14 +0100776
Zackery Spytz2a893432018-12-05 00:14:00 -0700777 Py_INCREF(Py_None);
Victor Stinner71a35222020-03-26 22:46:14 +0100778 return PyList_SetItem(interp->modules_by_index, index, Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200779}
780
Victor Stinner048a3562020-11-05 00:45:56 +0100781// Used by finalize_modules()
Antoine Pitrou40322e62013-08-11 00:30:09 +0200782void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200783_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200784{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200785 if (!interp->modules_by_index) {
786 return;
787 }
788
789 Py_ssize_t i;
790 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
791 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
792 if (PyModule_Check(m)) {
793 /* cleanup the saved copy of module dicts */
794 PyModuleDef *md = PyModule_GetDef(m);
795 if (md) {
796 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200797 }
798 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200799 }
800
801 /* Setting modules_by_index to NULL could be dangerous, so we
802 clear the list instead. */
803 if (PyList_SetSlice(interp->modules_by_index,
804 0, PyList_GET_SIZE(interp->modules_by_index),
805 NULL)) {
806 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200807 }
808}
809
Guido van Rossuma027efa1997-05-05 20:56:21 +0000810void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000811PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000812{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200813 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200814
Victor Stinner5804f872020-03-24 16:32:26 +0100815 if (verbose && tstate->frame != NULL) {
816 /* bpo-20526: After the main thread calls
817 _PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
818 exit when trying to take the GIL. If a thread exit in the middle of
819 _PyEval_EvalFrameDefault(), tstate->frame is not reset to its
820 previous value. It is more likely with daemon threads, but it can
821 happen with regular threads if threading._shutdown() fails
822 (ex: interrupted by CTRL+C). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 fprintf(stderr,
824 "PyThreadState_Clear: warning: thread still has a frame\n");
Victor Stinner5804f872020-03-24 16:32:26 +0100825 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000826
Victor Stinner5804f872020-03-24 16:32:26 +0100827 /* Don't clear tstate->frame: it is a borrowed reference */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 Py_CLEAR(tstate->dict);
830 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 Py_CLEAR(tstate->curexc_type);
833 Py_CLEAR(tstate->curexc_value);
834 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000835
Mark Shannonae3087c2017-10-22 22:41:51 +0100836 Py_CLEAR(tstate->exc_state.exc_type);
837 Py_CLEAR(tstate->exc_state.exc_value);
838 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300839
Mark Shannonae3087c2017-10-22 22:41:51 +0100840 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200841 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100842 fprintf(stderr,
843 "PyThreadState_Clear: warning: thread still has a generator\n");
844 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 tstate->c_profilefunc = NULL;
847 tstate->c_tracefunc = NULL;
848 Py_CLEAR(tstate->c_profileobj);
849 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400850
Yury Selivanoveb636452016-09-08 22:01:51 -0700851 Py_CLEAR(tstate->async_gen_firstiter);
852 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500853
854 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100855
856 if (tstate->on_delete != NULL) {
857 tstate->on_delete(tstate->on_delete_data);
858 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000859}
860
861
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300862/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000863static void
Victor Stinner9da74302019-11-20 11:17:17 +0100864tstate_delete_common(PyThreadState *tstate,
865 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000866{
Victor Stinner3026cad2020-06-01 16:02:40 +0200867 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200868 PyInterpreterState *interp = tstate->interp;
869 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100870 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200871 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100872 _PyRuntimeState *runtime = interp->runtime;
873
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200874 HEAD_LOCK(runtime);
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100875 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200876 tstate->prev->next = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100877 }
878 else {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200879 interp->tstate_head = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100880 }
881 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200882 tstate->next->prev = tstate->prev;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100883 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200884 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100885
Victor Stinner9da74302019-11-20 11:17:17 +0100886 if (gilstate->autoInterpreterState &&
887 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
888 {
889 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
890 }
891}
892
893
894static void
895_PyThreadState_Delete(PyThreadState *tstate, int check_current)
896{
897 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
898 if (check_current) {
899 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100900 _Py_FatalErrorFormat(__func__, "tstate %p is still current", tstate);
Victor Stinner9da74302019-11-20 11:17:17 +0100901 }
902 }
903 tstate_delete_common(tstate, gilstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100904 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000905}
906
907
Victor Stinner01b1cc12019-11-20 02:27:56 +0100908void
909PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000910{
Victor Stinner9da74302019-11-20 11:17:17 +0100911 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200912}
913
914
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300915void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100916_PyThreadState_DeleteCurrent(PyThreadState *tstate)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200917{
Victor Stinner3026cad2020-06-01 16:02:40 +0200918 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100919 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner9da74302019-11-20 11:17:17 +0100920 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200921 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100922 _PyEval_ReleaseLock(tstate);
923 PyMem_RawFree(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000924}
Guido van Rossum29757862001-01-23 01:46:06 +0000925
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300926void
927PyThreadState_DeleteCurrent(void)
928{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100929 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
930 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
931 _PyThreadState_DeleteCurrent(tstate);
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300932}
933
Guido van Rossum29757862001-01-23 01:46:06 +0000934
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200935/*
936 * Delete all thread states except the one passed as argument.
937 * Note that, if there is a current thread state, it *must* be the one
938 * passed as argument. Also, this won't touch any other interpreters
939 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000940 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200941 */
942void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200943_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200944{
945 PyInterpreterState *interp = tstate->interp;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100946
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200947 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200948 /* Remove all thread states, except tstate, from the linked list of
949 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200950 without holding the lock. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100951 PyThreadState *list = interp->tstate_head;
952 if (list == tstate) {
953 list = tstate->next;
954 }
955 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200956 tstate->prev->next = tstate->next;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100957 }
958 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200959 tstate->next->prev = tstate->prev;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100960 }
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200961 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200962 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200963 HEAD_UNLOCK(runtime);
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100964
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200965 /* Clear and deallocate all stale thread states. Even if this
966 executes Python code, we should be safe since it executes
967 in the current thread, not one of the stale threads. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100968 PyThreadState *p, *next;
969 for (p = list; p; p = next) {
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200970 next = p->next;
971 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200972 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200973 }
974}
975
976
Victor Stinnere838a932020-05-05 19:56:48 +0200977#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
978PyThreadState*
979_PyThreadState_GetTSS(void) {
980 return PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
981}
982#endif
983
984
Guido van Rossuma027efa1997-05-05 20:56:21 +0000985PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100986_PyThreadState_UncheckedGet(void)
987{
Victor Stinner50b48572018-11-01 01:51:40 +0100988 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100989}
990
991
992PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000993PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000994{
Victor Stinner50b48572018-11-01 01:51:40 +0100995 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200996 _Py_EnsureTstateNotNULL(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000998}
999
1000
Victor Stinner09532fe2019-05-10 23:39:09 +02001001PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001002_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +00001003{
Victor Stinnere838a932020-05-05 19:56:48 +02001004#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1005 PyThreadState *oldts = _PyThreadState_GetTSS();
1006#else
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001007 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Victor Stinnere838a932020-05-05 19:56:48 +02001008#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +00001009
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001010 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 /* It should not be possible for more than one thread state
1012 to be used for a thread. Check this the best we can in debug
1013 builds.
1014 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02001015#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 if (newts) {
1017 /* This can be called from PyEval_RestoreThread(). Similar
1018 to it, we need to ensure errno doesn't change.
1019 */
1020 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001021 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (check && check->interp == newts->interp && check != newts)
1023 Py_FatalError("Invalid thread state for this thread");
1024 errno = err;
1025 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001026#endif
Victor Stinnere838a932020-05-05 19:56:48 +02001027#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1028 PyThread_tss_set(&gilstate->autoTSSkey, newts);
1029#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +00001031}
Guido van Rossumede04391998-04-10 20:18:25 +00001032
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001033PyThreadState *
1034PyThreadState_Swap(PyThreadState *newts)
1035{
1036 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
1037}
1038
Guido van Rossumede04391998-04-10 20:18:25 +00001039/* An extension mechanism to store arbitrary additional per-thread state.
1040 PyThreadState_GetDict() returns a dictionary that can be used to hold such
1041 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001042 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
1043 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +00001044
1045PyObject *
Victor Stinner0e427c62020-03-25 21:22:55 +01001046_PyThreadState_GetDict(PyThreadState *tstate)
1047{
1048 assert(tstate != NULL);
1049 if (tstate->dict == NULL) {
1050 tstate->dict = PyDict_New();
1051 if (tstate->dict == NULL) {
1052 _PyErr_Clear(tstate);
1053 }
1054 }
1055 return tstate->dict;
1056}
1057
1058
1059PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001060PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +00001061{
Victor Stinner50b48572018-11-01 01:51:40 +01001062 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner0e427c62020-03-25 21:22:55 +01001063 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 }
Victor Stinner0e427c62020-03-25 21:22:55 +01001066 return _PyThreadState_GetDict(tstate);
Guido van Rossumede04391998-04-10 20:18:25 +00001067}
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001068
1069
Victor Stinner8fb02b62020-03-13 23:38:08 +01001070PyInterpreterState *
1071PyThreadState_GetInterpreter(PyThreadState *tstate)
1072{
1073 assert(tstate != NULL);
Victor Stinner8fb02b62020-03-13 23:38:08 +01001074 return tstate->interp;
1075}
1076
1077
Victor Stinner4386b902020-04-29 03:01:43 +02001078PyFrameObject*
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001079PyThreadState_GetFrame(PyThreadState *tstate)
1080{
1081 assert(tstate != NULL);
Victor Stinner4386b902020-04-29 03:01:43 +02001082 PyFrameObject *frame = tstate->frame;
1083 Py_XINCREF(frame);
1084 return frame;
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001085}
1086
1087
Victor Stinner5c3cda02020-03-25 21:23:53 +01001088uint64_t
1089PyThreadState_GetID(PyThreadState *tstate)
1090{
1091 assert(tstate != NULL);
1092 return tstate->id;
1093}
1094
1095
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001096/* Asynchronously raise an exception in a thread.
1097 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001098 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001099 to call this, or use ctypes. Must be called with the GIL held.
1100 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1101 match any known thread id). Can be called with exc=NULL to clear an
1102 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001103
1104int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001105PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1106{
Victor Stinner09532fe2019-05-10 23:39:09 +02001107 _PyRuntimeState *runtime = &_PyRuntime;
1108 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 /* Although the GIL is held, a few C API functions can be called
1111 * without the GIL held, and in particular some that create and
1112 * destroy thread and interpreter states. Those can mutate the
1113 * list of thread states we're traversing, so to prevent that we lock
1114 * head_mutex for the duration.
1115 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001116 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001117 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1118 if (tstate->thread_id != id) {
1119 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001121
1122 /* Tricky: we need to decref the current value
1123 * (if any) in tstate->async_exc, but that can in turn
1124 * allow arbitrary Python code to run, including
1125 * perhaps calls to this function. To prevent
1126 * deadlock, we need to release head_mutex before
1127 * the decref.
1128 */
1129 PyObject *old_exc = tstate->async_exc;
1130 Py_XINCREF(exc);
1131 tstate->async_exc = exc;
1132 HEAD_UNLOCK(runtime);
1133
1134 Py_XDECREF(old_exc);
1135 _PyEval_SignalAsyncExc(tstate);
1136 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001138 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001140}
1141
1142
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001143/* Routines for advanced debuggers, requested by David Beazley.
1144 Don't use unless you know what you are doing! */
1145
1146PyInterpreterState *
1147PyInterpreterState_Head(void)
1148{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001149 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001150}
1151
1152PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001153PyInterpreterState_Main(void)
1154{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001155 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001156}
1157
1158PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001159PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001161}
1162
1163PyThreadState *
1164PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001166}
1167
1168PyThreadState *
1169PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001171}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001172
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001173/* The implementation of sys._current_frames(). This is intended to be
1174 called with the GIL held, as it will be when called via
1175 sys._current_frames(). It's possible it would work fine even without
1176 the GIL held, but haven't thought enough about that.
1177*/
1178PyObject *
1179_PyThread_CurrentFrames(void)
1180{
Victor Stinner71a35222020-03-26 22:46:14 +01001181 PyThreadState *tstate = _PyThreadState_GET();
1182 if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001183 return NULL;
1184 }
1185
Victor Stinner71a35222020-03-26 22:46:14 +01001186 PyObject *result = PyDict_New();
1187 if (result == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 return NULL;
Victor Stinner71a35222020-03-26 22:46:14 +01001189 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 /* for i in all interpreters:
1192 * for t in all of i's thread states:
1193 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001194 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 * need to grab head_mutex for the duration.
1196 */
Victor Stinner71a35222020-03-26 22:46:14 +01001197 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001198 HEAD_LOCK(runtime);
Victor Stinner71a35222020-03-26 22:46:14 +01001199 PyInterpreterState *i;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001200 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 PyThreadState *t;
1202 for (t = i->tstate_head; t != NULL; t = t->next) {
Victor Stinner4386b902020-04-29 03:01:43 +02001203 PyFrameObject *frame = t->frame;
Victor Stinner71a35222020-03-26 22:46:14 +01001204 if (frame == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 continue;
Victor Stinner71a35222020-03-26 22:46:14 +01001206 }
1207 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1208 if (id == NULL) {
1209 goto fail;
1210 }
1211 int stat = PyDict_SetItem(result, id, (PyObject *)frame);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 Py_DECREF(id);
Victor Stinner71a35222020-03-26 22:46:14 +01001213 if (stat < 0) {
1214 goto fail;
1215 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 }
1217 }
Victor Stinner71a35222020-03-26 22:46:14 +01001218 goto done;
1219
1220fail:
1221 Py_CLEAR(result);
1222
1223done:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001224 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001226}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001227
Julien Danjou64366fa2020-11-02 15:16:25 +01001228PyObject *
1229_PyThread_CurrentExceptions(void)
1230{
1231 PyThreadState *tstate = _PyThreadState_GET();
1232
1233 _Py_EnsureTstateNotNULL(tstate);
1234
1235 if (_PySys_Audit(tstate, "sys._current_exceptions", NULL) < 0) {
1236 return NULL;
1237 }
1238
1239 PyObject *result = PyDict_New();
1240 if (result == NULL) {
1241 return NULL;
1242 }
1243
1244 /* for i in all interpreters:
1245 * for t in all of i's thread states:
1246 * if t's frame isn't NULL, map t's id to its frame
1247 * Because these lists can mutate even when the GIL is held, we
1248 * need to grab head_mutex for the duration.
1249 */
1250 _PyRuntimeState *runtime = tstate->interp->runtime;
1251 HEAD_LOCK(runtime);
1252 PyInterpreterState *i;
1253 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
1254 PyThreadState *t;
1255 for (t = i->tstate_head; t != NULL; t = t->next) {
1256 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(t);
1257 if (err_info == NULL) {
1258 continue;
1259 }
1260 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1261 if (id == NULL) {
1262 goto fail;
1263 }
1264 PyObject *exc_info = PyTuple_Pack(
1265 3,
1266 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
1267 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
1268 err_info->exc_traceback != NULL ? err_info->exc_traceback : Py_None);
1269 if (exc_info == NULL) {
1270 Py_DECREF(id);
1271 goto fail;
1272 }
1273 int stat = PyDict_SetItem(result, id, exc_info);
1274 Py_DECREF(id);
1275 Py_DECREF(exc_info);
1276 if (stat < 0) {
1277 goto fail;
1278 }
1279 }
1280 }
1281 goto done;
1282
1283fail:
1284 Py_CLEAR(result);
1285
1286done:
1287 HEAD_UNLOCK(runtime);
1288 return result;
1289}
1290
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001291/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001292
1293/* Keep this as a static, as it is not reliable! It can only
1294 ever be compared to the state for the *current* thread.
1295 * If not equal, then it doesn't matter that the actual
1296 value may change immediately after comparison, as it can't
1297 possibly change to the current thread's state.
1298 * If equal, then the current thread holds the lock, so the value can't
1299 change until we yield the lock.
1300*/
1301static int
1302PyThreadState_IsCurrent(PyThreadState *tstate)
1303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001305 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001306 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1307 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001308}
1309
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001310/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001311 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001312*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001313PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001314_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001315{
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001316 if (!_Py_IsMainInterpreter(tstate)) {
1317 /* Currently, PyGILState is shared by all interpreters. The main
1318 * interpreter is responsible to initialize it. */
1319 return _PyStatus_OK();
1320 }
1321
Victor Stinner8bb32302019-04-24 16:47:40 +02001322 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001323 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001324 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001325
Victor Stinner01b1cc12019-11-20 02:27:56 +01001326 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001327
1328 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001329 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001330 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001331 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001332 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1333 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001334
Victor Stinner8bb32302019-04-24 16:47:40 +02001335 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001336 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001337}
1338
Victor Stinner861d9ab2016-03-16 22:45:24 +01001339PyInterpreterState *
1340_PyGILState_GetInterpreterStateUnsafe(void)
1341{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001342 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001343}
1344
Tim Peters19717fa2004-10-09 17:38:29 +00001345void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001346_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001347{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001348 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001349 PyThread_tss_delete(&gilstate->autoTSSkey);
1350 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001351}
1352
Victor Stinner26881c82020-06-02 15:51:37 +02001353#ifdef HAVE_FORK
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001354/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001355 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001356 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001357 */
Victor Stinner26881c82020-06-02 15:51:37 +02001358PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001359_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001360{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001361 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001362 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001363
1364 PyThread_tss_delete(&gilstate->autoTSSkey);
1365 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner26881c82020-06-02 15:51:37 +02001366 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001367 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001368
Charles-François Natalia233df82011-11-22 19:49:51 +01001369 /* If the thread had an associated auto thread state, reassociate it with
1370 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001371 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001372 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001373 {
Victor Stinner26881c82020-06-02 15:51:37 +02001374 return _PyStatus_ERR("failed to set autoTSSkey");
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001375 }
Victor Stinner26881c82020-06-02 15:51:37 +02001376 return _PyStatus_OK();
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001377}
Victor Stinner26881c82020-06-02 15:51:37 +02001378#endif
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001379
Michael W. Hudson188d4362005-06-20 16:52:57 +00001380/* When a thread state is created for a thread by some mechanism other than
1381 PyGILState_Ensure, it's important that the GILState machinery knows about
1382 it so it doesn't try to create another thread state for the thread (this is
1383 a better fix for SF bug #1010677 than the first one attempted).
1384*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001385static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001386_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001387{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001388 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001389 threadstate created in Py_Initialize(). Don't do anything for now
1390 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001391 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001393 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001394
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001395 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 The only situation where you can legitimately have more than one
1398 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001399 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001400
Victor Stinner590cebe2013-12-13 11:08:56 +01001401 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1402 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001403
Victor Stinner590cebe2013-12-13 11:08:56 +01001404 The first thread state created for that given OS level thread will
1405 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001407 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1408 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001409 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001410 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001411 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 /* PyGILState_Release must not try to delete this thread state. */
1414 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001415}
1416
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001417/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001418static PyThreadState *
1419_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1420{
1421 if (gilstate->autoInterpreterState == NULL)
1422 return NULL;
1423 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1424}
1425
Tim Peters19717fa2004-10-09 17:38:29 +00001426PyThreadState *
1427PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001428{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001429 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001430}
1431
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001432int
1433PyGILState_Check(void)
1434{
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001435 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1436 if (!gilstate->check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001437 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001438 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001439
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001440 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1441 return 1;
1442 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001443
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001444 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1445 if (tstate == NULL) {
1446 return 0;
1447 }
1448
1449 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001450}
1451
Tim Peters19717fa2004-10-09 17:38:29 +00001452PyGILState_STATE
1453PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001454{
Victor Stinner175a7042020-03-10 00:37:48 +01001455 _PyRuntimeState *runtime = &_PyRuntime;
1456 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 /* Note that we do not auto-init Python here - apart from
1459 potential races with 2 threads auto-initializing, pep-311
1460 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001461 called Py_Initialize(). */
1462
1463 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1464 called by Py_Initialize() */
Victor Stinnere838a932020-05-05 19:56:48 +02001465#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinner175a7042020-03-10 00:37:48 +01001466 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinnere838a932020-05-05 19:56:48 +02001467#endif
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001468 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001469
Victor Stinner175a7042020-03-10 00:37:48 +01001470 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1471 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001473 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001474 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001475 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001477 }
1478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001479 /* This is our thread state! We'll need to delete it in the
1480 matching call to PyGILState_Release(). */
1481 tcur->gilstate_counter = 0;
1482 current = 0; /* new thread state is never current */
1483 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001484 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001486 }
1487
1488 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001490 }
1491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 /* Update our counter in the thread-state - no need for locks:
1493 - tcur will remain valid as we hold the GIL.
1494 - the counter is safe as we are the only thread "allowed"
1495 to modify this value
1496 */
1497 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001500}
1501
Tim Peters19717fa2004-10-09 17:38:29 +00001502void
1503PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001504{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001505 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001506 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1507 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 Py_FatalError("auto-releasing thread-state, "
1509 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001510 }
1511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 /* We must hold the GIL and have our thread state current */
1513 /* XXX - remove the check - the assert should be fine,
1514 but while this is very new (April 2003), the extra check
1515 by release-only users can't hurt.
1516 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001517 if (!PyThreadState_IsCurrent(tstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001518 _Py_FatalErrorFormat(__func__,
1519 "thread state %p must be current when releasing",
1520 tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001521 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001522 assert(PyThreadState_IsCurrent(tstate));
1523 --tstate->gilstate_counter;
1524 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 /* If we're going to destroy this thread-state, we must
1527 * clear it while the GIL is held, as destructors may run.
1528 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001529 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 /* can't have been locked when we created it */
1531 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001532 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 /* Delete the thread-state. Note this releases the GIL too!
1534 * It's vital that the GIL be held here, to avoid shutdown
1535 * races; see bugs 225673 and 1061968 (that nasty bug has a
1536 * habit of coming back).
1537 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001538 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1539 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 }
1541 /* Release the lock if necessary */
1542 else if (oldstate == PyGILState_UNLOCKED)
1543 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001544}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001545
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001546
Eric Snow7f8bfc92018-01-29 18:23:44 -07001547/**************************/
1548/* cross-interpreter data */
1549/**************************/
1550
1551/* cross-interpreter data */
1552
1553crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1554
1555/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1556 to keep the registry code separate. */
1557static crossinterpdatafunc
1558_lookup_getdata(PyObject *obj)
1559{
1560 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1561 if (getdata == NULL && PyErr_Occurred() == 0)
1562 PyErr_Format(PyExc_ValueError,
1563 "%S does not support cross-interpreter data", obj);
1564 return getdata;
1565}
1566
1567int
1568_PyObject_CheckCrossInterpreterData(PyObject *obj)
1569{
1570 crossinterpdatafunc getdata = _lookup_getdata(obj);
1571 if (getdata == NULL) {
1572 return -1;
1573 }
1574 return 0;
1575}
1576
1577static int
Victor Stinner71a35222020-03-26 22:46:14 +01001578_check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001579{
1580 // data->data can be anything, including NULL, so we don't check it.
1581
1582 // data->obj may be NULL, so we don't check it.
1583
1584 if (data->interp < 0) {
Victor Stinner71a35222020-03-26 22:46:14 +01001585 _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001586 return -1;
1587 }
1588
1589 if (data->new_object == NULL) {
Victor Stinner71a35222020-03-26 22:46:14 +01001590 _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001591 return -1;
1592 }
1593
1594 // data->free may be NULL, so we don't check it.
1595
1596 return 0;
1597}
1598
1599int
1600_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1601{
Victor Stinner71a35222020-03-26 22:46:14 +01001602 // PyThreadState_Get() aborts if tstate is NULL.
1603 PyThreadState *tstate = PyThreadState_Get();
1604 PyInterpreterState *interp = tstate->interp;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001605
1606 // Reset data before re-populating.
1607 *data = (_PyCrossInterpreterData){0};
1608 data->free = PyMem_RawFree; // Set a default that may be overridden.
1609
1610 // Call the "getdata" func for the object.
1611 Py_INCREF(obj);
1612 crossinterpdatafunc getdata = _lookup_getdata(obj);
1613 if (getdata == NULL) {
1614 Py_DECREF(obj);
1615 return -1;
1616 }
1617 int res = getdata(obj, data);
1618 Py_DECREF(obj);
1619 if (res != 0) {
1620 return -1;
1621 }
1622
1623 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001624 data->interp = interp->id;
Victor Stinner71a35222020-03-26 22:46:14 +01001625 if (_check_xidata(tstate, data) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001626 _PyCrossInterpreterData_Release(data);
1627 return -1;
1628 }
1629
1630 return 0;
1631}
1632
Victor Stinnere225beb2019-06-03 18:14:24 +02001633static void
Eric Snow63799132018-06-01 18:45:20 -06001634_release_xidata(void *arg)
1635{
1636 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1637 if (data->free != NULL) {
1638 data->free(data->data);
1639 }
1640 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001641}
1642
1643static void
1644_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1645 PyInterpreterState *interp,
1646 void (*func)(void *), void *arg)
1647{
1648 /* We would use Py_AddPendingCall() if it weren't specific to the
1649 * main interpreter (see bpo-33608). In the meantime we take a
1650 * naive approach.
1651 */
1652 PyThreadState *save_tstate = NULL;
1653 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1654 // XXX Using the "head" thread isn't strictly correct.
1655 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1656 // XXX Possible GILState issues?
1657 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1658 }
1659
1660 func(arg);
1661
1662 // Switch back.
1663 if (save_tstate != NULL) {
1664 _PyThreadState_Swap(gilstate, save_tstate);
1665 }
Eric Snow63799132018-06-01 18:45:20 -06001666}
1667
Eric Snow7f8bfc92018-01-29 18:23:44 -07001668void
1669_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1670{
1671 if (data->data == NULL && data->obj == NULL) {
1672 // Nothing to release!
1673 return;
1674 }
1675
Victor Stinnere225beb2019-06-03 18:14:24 +02001676 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001677 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1678 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001679 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001680 if (data->free != NULL) {
1681 // XXX Someone leaked some memory...
1682 }
1683 return;
1684 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001685
Eric Snow7f8bfc92018-01-29 18:23:44 -07001686 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001687 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1688 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001689}
1690
1691PyObject *
1692_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1693{
1694 return data->new_object(data);
1695}
1696
1697/* registry of {type -> crossinterpdatafunc} */
1698
1699/* For now we use a global registry of shareable classes. An
1700 alternative would be to add a tp_* slot for a class's
1701 crossinterpdatafunc. It would be simpler and more efficient. */
1702
1703static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001704_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1705 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001706{
1707 // Note that we effectively replace already registered classes
1708 // rather than failing.
1709 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1710 if (newhead == NULL)
1711 return -1;
1712 newhead->cls = cls;
1713 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001714 newhead->next = xidregistry->head;
1715 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001716 return 0;
1717}
1718
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001719static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001720
1721int
Eric Snowc11183c2019-03-15 16:35:46 -06001722_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001723 crossinterpdatafunc getdata)
1724{
1725 if (!PyType_Check(cls)) {
1726 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1727 return -1;
1728 }
1729 if (getdata == NULL) {
1730 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1731 return -1;
1732 }
1733
1734 // Make sure the class isn't ever deallocated.
1735 Py_INCREF((PyObject *)cls);
1736
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001737 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1738 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1739 if (xidregistry->head == NULL) {
1740 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001741 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001742 int res = _register_xidata(xidregistry, cls, getdata);
1743 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001744 return res;
1745}
1746
Eric Snow6d2cd902018-05-16 15:04:57 -04001747/* Cross-interpreter objects are looked up by exact match on the class.
1748 We can reassess this policy when we move from a global registry to a
1749 tp_* slot. */
1750
Eric Snow7f8bfc92018-01-29 18:23:44 -07001751crossinterpdatafunc
1752_PyCrossInterpreterData_Lookup(PyObject *obj)
1753{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001754 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001755 PyObject *cls = PyObject_Type(obj);
1756 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001757 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1758 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001759 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001760 _register_builtins_for_crossinterpreter_data(xidregistry);
1761 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001762 }
1763 for(; cur != NULL; cur = cur->next) {
1764 if (cur->cls == (PyTypeObject *)cls) {
1765 getdata = cur->getdata;
1766 break;
1767 }
1768 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001769 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001770 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001771 return getdata;
1772}
1773
1774/* cross-interpreter data for builtin types */
1775
Eric Snow6d2cd902018-05-16 15:04:57 -04001776struct _shared_bytes_data {
1777 char *bytes;
1778 Py_ssize_t len;
1779};
1780
Eric Snow7f8bfc92018-01-29 18:23:44 -07001781static PyObject *
1782_new_bytes_object(_PyCrossInterpreterData *data)
1783{
Eric Snow6d2cd902018-05-16 15:04:57 -04001784 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1785 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001786}
1787
1788static int
1789_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1790{
Eric Snow6d2cd902018-05-16 15:04:57 -04001791 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1792 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1793 return -1;
1794 }
1795 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001796 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001797 data->obj = obj; // Will be "released" (decref'ed) when data released.
1798 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001799 data->free = PyMem_Free;
1800 return 0;
1801}
1802
1803struct _shared_str_data {
1804 int kind;
1805 const void *buffer;
1806 Py_ssize_t len;
1807};
1808
1809static PyObject *
1810_new_str_object(_PyCrossInterpreterData *data)
1811{
1812 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1813 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1814}
1815
1816static int
1817_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1818{
1819 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1820 shared->kind = PyUnicode_KIND(obj);
1821 shared->buffer = PyUnicode_DATA(obj);
An Long29c11722020-06-13 20:26:01 +08001822 shared->len = PyUnicode_GET_LENGTH(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001823 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001824 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001825 data->obj = obj; // Will be "released" (decref'ed) when data released.
1826 data->new_object = _new_str_object;
1827 data->free = PyMem_Free;
1828 return 0;
1829}
1830
1831static PyObject *
1832_new_long_object(_PyCrossInterpreterData *data)
1833{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001834 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001835}
1836
1837static int
1838_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1839{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001840 /* Note that this means the size of shareable ints is bounded by
1841 * sys.maxsize. Hence on 32-bit architectures that is half the
1842 * size of maximum shareable ints on 64-bit.
1843 */
1844 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001845 if (value == -1 && PyErr_Occurred()) {
1846 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1847 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1848 }
1849 return -1;
1850 }
1851 data->data = (void *)value;
1852 data->obj = NULL;
1853 data->new_object = _new_long_object;
1854 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001855 return 0;
1856}
1857
1858static PyObject *
1859_new_none_object(_PyCrossInterpreterData *data)
1860{
1861 // XXX Singleton refcounts are problematic across interpreters...
1862 Py_INCREF(Py_None);
1863 return Py_None;
1864}
1865
1866static int
1867_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1868{
1869 data->data = NULL;
1870 // data->obj remains NULL
1871 data->new_object = _new_none_object;
1872 data->free = NULL; // There is nothing to free.
1873 return 0;
1874}
1875
1876static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001877_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001878{
1879 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001880 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001881 Py_FatalError("could not register None for cross-interpreter sharing");
1882 }
1883
Eric Snow6d2cd902018-05-16 15:04:57 -04001884 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001885 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001886 Py_FatalError("could not register int for cross-interpreter sharing");
1887 }
1888
Eric Snow7f8bfc92018-01-29 18:23:44 -07001889 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001890 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001891 Py_FatalError("could not register bytes for cross-interpreter sharing");
1892 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001893
1894 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001895 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001896 Py_FatalError("could not register str for cross-interpreter sharing");
1897 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001898}
1899
1900
Victor Stinner0b72b232020-03-12 23:18:39 +01001901_PyFrameEvalFunction
1902_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1903{
1904 return interp->eval_frame;
1905}
1906
1907
1908void
1909_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1910 _PyFrameEvalFunction eval_frame)
1911{
1912 interp->eval_frame = eval_frame;
1913}
1914
Victor Stinnerda7933e2020-04-13 03:04:28 +02001915
1916const PyConfig*
1917_PyInterpreterState_GetConfig(PyInterpreterState *interp)
1918{
1919 return &interp->config;
1920}
1921
1922
Victor Stinner048a3562020-11-05 00:45:56 +01001923int
1924_PyInterpreterState_GetConfigCopy(PyConfig *config)
Victor Stinnerda7933e2020-04-13 03:04:28 +02001925{
Victor Stinner048a3562020-11-05 00:45:56 +01001926 PyInterpreterState *interp = PyInterpreterState_Get();
1927
1928 PyStatus status = _PyConfig_Copy(config, &interp->config);
1929 if (PyStatus_Exception(status)) {
1930 _PyErr_SetFromPyStatus(status);
1931 return -1;
1932 }
1933 return 0;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001934}
1935
1936
1937const PyConfig*
1938_Py_GetConfig(void)
1939{
1940 assert(PyGILState_Check());
1941 PyThreadState *tstate = _PyThreadState_GET();
1942 return _PyInterpreterState_GetConfig(tstate->interp);
1943}
1944
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001945#ifdef __cplusplus
1946}
1947#endif