blob: ead25b08d7a83a6c4d9822283d1c871bebf36359 [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);
Victor Stinnerb8fa1352020-12-15 14:34:19 +0100306 _PyAtExit_Fini(interp);
Victor Stinnerfd957c12020-11-03 18:07:15 +0100307
308 // All Python types must be destroyed before the last GC collection. Python
309 // types create a reference cycle to themselves in their in their
310 // PyTypeObject.tp_mro member (the tuple contains the type).
Victor Stinnereba5bf22020-10-30 22:51:02 +0100311
312 /* Last garbage collection on this interpreter */
313 _PyGC_CollectNoFail(tstate);
Victor Stinnereba5bf22020-10-30 22:51:02 +0100314 _PyGC_Fini(tstate);
315
Hai Shi8ecc0c42020-08-13 05:23:30 +0800316 /* We don't clear sysdict and builtins until the end of this function.
317 Because clearing other attributes can execute arbitrary Python code
318 which requires sysdict and builtins. */
319 PyDict_Clear(interp->sysdict);
320 PyDict_Clear(interp->builtins);
321 Py_CLEAR(interp->sysdict);
322 Py_CLEAR(interp->builtins);
323
Eric Snow5be45a62019-03-08 22:47:07 -0700324 // XXX Once we have one allocator per interpreter (i.e.
325 // per-interpreter GC) we must ensure that all of the interpreter's
326 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000327}
328
329
Victor Stinnereba5bf22020-10-30 22:51:02 +0100330void
331PyInterpreterState_Clear(PyInterpreterState *interp)
332{
333 // Use the current Python thread state to call audit hooks and to collect
334 // garbage. It can be different than the current Python thread state
335 // of 'interp'.
336 PyThreadState *current_tstate = _PyThreadState_GET();
337
338 interpreter_clear(interp, current_tstate);
339}
340
341
342void
343_PyInterpreterState_Clear(PyThreadState *tstate)
344{
345 interpreter_clear(tstate->interp, tstate);
346}
347
348
Guido van Rossum25ce5661997-08-02 03:10:38 +0000349static void
Victor Stinner9da74302019-11-20 11:17:17 +0100350zapthreads(PyInterpreterState *interp, int check_current)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000351{
Victor Stinner9da74302019-11-20 11:17:17 +0100352 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 /* No need to lock the mutex here because this should only happen
354 when the threads are all really dead (XXX famous last words). */
Victor Stinner9da74302019-11-20 11:17:17 +0100355 while ((tstate = interp->tstate_head) != NULL) {
356 _PyThreadState_Delete(tstate, check_current);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000358}
359
360
Victor Stinner01b1cc12019-11-20 02:27:56 +0100361void
362PyInterpreterState_Delete(PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200363{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100364 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200365 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner9da74302019-11-20 11:17:17 +0100366 zapthreads(interp, 0);
367
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200368 _PyEval_FiniState(&interp->ceval);
369
Victor Stinner9da74302019-11-20 11:17:17 +0100370 /* Delete current thread. After this, many C API calls become crashy. */
371 _PyThreadState_Swap(&runtime->gilstate, NULL);
372
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200373 HEAD_LOCK(runtime);
374 PyInterpreterState **p;
375 for (p = &interpreters->head; ; p = &(*p)->next) {
376 if (*p == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100377 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200378 }
379 if (*p == interp) {
380 break;
381 }
382 }
383 if (interp->tstate_head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100384 Py_FatalError("remaining threads");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200385 }
386 *p = interp->next;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200387
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200388 if (interpreters->main == interp) {
389 interpreters->main = NULL;
390 if (interpreters->head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100391 Py_FatalError("remaining subinterpreters");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200392 }
393 }
394 HEAD_UNLOCK(runtime);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200395
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200396 if (interp->id_mutex != NULL) {
397 PyThread_free_lock(interp->id_mutex);
398 }
399 PyMem_RawFree(interp);
400}
401
402
Victor Stinner26881c82020-06-02 15:51:37 +0200403#ifdef HAVE_FORK
Eric Snow59032962018-09-14 14:17:20 -0700404/*
405 * Delete all interpreter states except the main interpreter. If there
406 * is a current interpreter state, it *must* be the main interpreter.
407 */
Victor Stinner26881c82020-06-02 15:51:37 +0200408PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200409_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700410{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200411 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200412 struct pyinterpreters *interpreters = &runtime->interpreters;
413
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200414 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200415 if (tstate != NULL && tstate->interp != interpreters->main) {
Victor Stinner26881c82020-06-02 15:51:37 +0200416 return _PyStatus_ERR("not main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700417 }
418
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200419 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200420 PyInterpreterState *interp = interpreters->head;
421 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100422 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200423 if (interp == interpreters->main) {
424 interpreters->main->next = NULL;
425 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100426 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700427 continue;
428 }
429
Victor Stinner01b1cc12019-11-20 02:27:56 +0100430 PyInterpreterState_Clear(interp); // XXX must activate?
Victor Stinner9da74302019-11-20 11:17:17 +0100431 zapthreads(interp, 1);
Eric Snow59032962018-09-14 14:17:20 -0700432 if (interp->id_mutex != NULL) {
433 PyThread_free_lock(interp->id_mutex);
434 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100435 PyInterpreterState *prev_interp = interp;
436 interp = interp->next;
437 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700438 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200439 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700440
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200441 if (interpreters->head == NULL) {
Victor Stinner26881c82020-06-02 15:51:37 +0200442 return _PyStatus_ERR("missing main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700443 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200444 _PyThreadState_Swap(gilstate, tstate);
Victor Stinner26881c82020-06-02 15:51:37 +0200445 return _PyStatus_OK();
Eric Snow59032962018-09-14 14:17:20 -0700446}
Victor Stinner26881c82020-06-02 15:51:37 +0200447#endif
Eric Snow59032962018-09-14 14:17:20 -0700448
449
Victor Stinnercaba55b2018-08-03 15:33:52 +0200450PyInterpreterState *
Victor Stinnerbe793732020-03-13 18:15:33 +0100451PyInterpreterState_Get(void)
Victor Stinnercaba55b2018-08-03 15:33:52 +0200452{
Victor Stinner50b48572018-11-01 01:51:40 +0100453 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200454 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200455 PyInterpreterState *interp = tstate->interp;
456 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100457 Py_FatalError("no current interpreter");
Victor Stinnercaba55b2018-08-03 15:33:52 +0200458 }
459 return interp;
460}
461
462
Eric Snowe3774162017-05-22 19:46:40 -0700463int64_t
464PyInterpreterState_GetID(PyInterpreterState *interp)
465{
466 if (interp == NULL) {
467 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
468 return -1;
469 }
470 return interp->id;
471}
472
473
Eric Snow5be45a62019-03-08 22:47:07 -0700474static PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200475interp_look_up_id(_PyRuntimeState *runtime, int64_t requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700476{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200477 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100478 while (interp != NULL) {
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200479 int64_t id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700480 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100481 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700482 }
483 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100484 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700485 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100486 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700487 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100488 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700489}
490
Eric Snow5be45a62019-03-08 22:47:07 -0700491PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200492_PyInterpreterState_LookUpID(int64_t requested_id)
Eric Snow5be45a62019-03-08 22:47:07 -0700493{
494 PyInterpreterState *interp = NULL;
495 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200496 _PyRuntimeState *runtime = &_PyRuntime;
497 HEAD_LOCK(runtime);
498 interp = interp_look_up_id(runtime, requested_id);
499 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700500 }
501 if (interp == NULL && !PyErr_Occurred()) {
502 PyErr_Format(PyExc_RuntimeError,
503 "unrecognized interpreter ID %lld", requested_id);
504 }
505 return interp;
506}
507
Eric Snow4c6955e2018-02-16 18:53:40 -0700508
509int
510_PyInterpreterState_IDInitref(PyInterpreterState *interp)
511{
512 if (interp->id_mutex != NULL) {
513 return 0;
514 }
515 interp->id_mutex = PyThread_allocate_lock();
516 if (interp->id_mutex == NULL) {
517 PyErr_SetString(PyExc_RuntimeError,
518 "failed to create init interpreter ID mutex");
519 return -1;
520 }
521 interp->id_refcount = 0;
522 return 0;
523}
524
525
526void
527_PyInterpreterState_IDIncref(PyInterpreterState *interp)
528{
529 if (interp->id_mutex == NULL) {
530 return;
531 }
532 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
533 interp->id_refcount += 1;
534 PyThread_release_lock(interp->id_mutex);
535}
536
537
538void
539_PyInterpreterState_IDDecref(PyInterpreterState *interp)
540{
541 if (interp->id_mutex == NULL) {
542 return;
543 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200544 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700545 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
546 assert(interp->id_refcount != 0);
547 interp->id_refcount -= 1;
548 int64_t refcount = interp->id_refcount;
549 PyThread_release_lock(interp->id_mutex);
550
Eric Snowc11183c2019-03-15 16:35:46 -0600551 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700552 // XXX Using the "head" thread isn't strictly correct.
553 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
554 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200555 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700556 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200557 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700558 }
559}
560
Eric Snowc11183c2019-03-15 16:35:46 -0600561int
562_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
563{
564 return interp->requires_idref;
565}
566
567void
568_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
569{
570 interp->requires_idref = required ? 1 : 0;
571}
572
Eric Snowc11183c2019-03-15 16:35:46 -0600573PyObject *
574_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
575{
576 if (interp->modules == NULL) {
577 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
578 return NULL;
579 }
580 return PyMapping_GetItemString(interp->modules, "__main__");
581}
582
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600583PyObject *
584PyInterpreterState_GetDict(PyInterpreterState *interp)
585{
586 if (interp->dict == NULL) {
587 interp->dict = PyDict_New();
588 if (interp->dict == NULL) {
589 PyErr_Clear();
590 }
591 }
592 /* Returning NULL means no per-interpreter dict is available. */
593 return interp->dict;
594}
595
Victor Stinner45b9be52010-03-03 23:28:07 +0000596static PyThreadState *
597new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000598{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100599 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200600 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200601 if (tstate == NULL) {
602 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000604
Victor Stinner8bb32302019-04-24 16:47:40 +0200605 tstate->interp = interp;
606
607 tstate->frame = NULL;
608 tstate->recursion_depth = 0;
Mark Shannon4e7a69b2020-12-02 13:30:55 +0000609 tstate->recursion_headroom = 0;
Victor Stinner8bb32302019-04-24 16:47:40 +0200610 tstate->stackcheck_counter = 0;
611 tstate->tracing = 0;
612 tstate->use_tracing = 0;
613 tstate->gilstate_counter = 0;
614 tstate->async_exc = NULL;
615 tstate->thread_id = PyThread_get_thread_ident();
616
617 tstate->dict = NULL;
618
619 tstate->curexc_type = NULL;
620 tstate->curexc_value = NULL;
621 tstate->curexc_traceback = NULL;
622
623 tstate->exc_state.exc_type = NULL;
624 tstate->exc_state.exc_value = NULL;
625 tstate->exc_state.exc_traceback = NULL;
626 tstate->exc_state.previous_item = NULL;
627 tstate->exc_info = &tstate->exc_state;
628
629 tstate->c_profilefunc = NULL;
630 tstate->c_tracefunc = NULL;
631 tstate->c_profileobj = NULL;
632 tstate->c_traceobj = NULL;
633
634 tstate->trash_delete_nesting = 0;
635 tstate->trash_delete_later = NULL;
636 tstate->on_delete = NULL;
637 tstate->on_delete_data = NULL;
638
639 tstate->coroutine_origin_tracking_depth = 0;
640
Victor Stinner8bb32302019-04-24 16:47:40 +0200641 tstate->async_gen_firstiter = NULL;
642 tstate->async_gen_finalizer = NULL;
643
644 tstate->context = NULL;
645 tstate->context_ver = 1;
646
Victor Stinner8bb32302019-04-24 16:47:40 +0200647 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100648 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200649 }
650
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200651 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100652 tstate->id = ++interp->tstate_next_unique_id;
Victor Stinner8bb32302019-04-24 16:47:40 +0200653 tstate->prev = NULL;
654 tstate->next = interp->tstate_head;
655 if (tstate->next)
656 tstate->next->prev = tstate;
657 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200658 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000661}
662
Victor Stinner45b9be52010-03-03 23:28:07 +0000663PyThreadState *
664PyThreadState_New(PyInterpreterState *interp)
665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000667}
668
669PyThreadState *
670_PyThreadState_Prealloc(PyInterpreterState *interp)
671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000673}
674
675void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100676_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000677{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100678 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000679}
680
Martin v. Löwis1a214512008-06-11 05:26:20 +0000681PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200682PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000683{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200684 Py_ssize_t index = module->m_base.m_index;
Victor Stinner81a7be32020-04-14 15:14:01 +0200685 PyInterpreterState *state = _PyInterpreterState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000687 if (module->m_slots) {
688 return NULL;
689 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 if (index == 0)
691 return NULL;
692 if (state->modules_by_index == NULL)
693 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200694 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 return NULL;
696 res = PyList_GET_ITEM(state->modules_by_index, index);
697 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000698}
699
700int
Victor Stinner82c83bd2019-11-22 18:52:27 +0100701_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000702{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300703 if (!def) {
Victor Stinner71a35222020-03-26 22:46:14 +0100704 assert(_PyErr_Occurred(tstate));
Berker Peksag4b7b5652016-08-22 18:05:56 +0300705 return -1;
706 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000707 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100708 _PyErr_SetString(tstate,
709 PyExc_SystemError,
710 "PyState_AddModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000711 return -1;
712 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100713
714 PyInterpreterState *interp = tstate->interp;
715 if (!interp->modules_by_index) {
716 interp->modules_by_index = PyList_New(0);
717 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100719 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100721
722 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
723 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100725 }
726 }
727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100729 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000731}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000732
Martin v. Löwis7800f752012-06-22 12:20:55 +0200733int
734PyState_AddModule(PyObject* module, struct PyModuleDef* def)
735{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200736 if (!def) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100737 Py_FatalError("module definition is NULL");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200738 return -1;
739 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100740
741 PyThreadState *tstate = _PyThreadState_GET();
742 PyInterpreterState *interp = tstate->interp;
743 Py_ssize_t index = def->m_base.m_index;
744 if (interp->modules_by_index &&
745 index < PyList_GET_SIZE(interp->modules_by_index) &&
746 module == PyList_GET_ITEM(interp->modules_by_index, index))
747 {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100748 _Py_FatalErrorFormat(__func__, "module %p already added", module);
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100749 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200750 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100751 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200752}
753
754int
755PyState_RemoveModule(struct PyModuleDef* def)
756{
Victor Stinner71a35222020-03-26 22:46:14 +0100757 PyThreadState *tstate = _PyThreadState_GET();
758 PyInterpreterState *interp = tstate->interp;
759
Nick Coghland5cacbb2015-05-23 22:24:10 +1000760 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100761 _PyErr_SetString(tstate,
762 PyExc_SystemError,
763 "PyState_RemoveModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000764 return -1;
765 }
Victor Stinner71a35222020-03-26 22:46:14 +0100766
767 Py_ssize_t index = def->m_base.m_index;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200768 if (index == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100769 Py_FatalError("invalid module index");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200770 }
Victor Stinner71a35222020-03-26 22:46:14 +0100771 if (interp->modules_by_index == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100772 Py_FatalError("Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200773 }
Victor Stinner71a35222020-03-26 22:46:14 +0100774 if (index > PyList_GET_SIZE(interp->modules_by_index)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100775 Py_FatalError("Module index out of bounds.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200776 }
Victor Stinner71a35222020-03-26 22:46:14 +0100777
Zackery Spytz2a893432018-12-05 00:14:00 -0700778 Py_INCREF(Py_None);
Victor Stinner71a35222020-03-26 22:46:14 +0100779 return PyList_SetItem(interp->modules_by_index, index, Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200780}
781
Victor Stinner048a3562020-11-05 00:45:56 +0100782// Used by finalize_modules()
Antoine Pitrou40322e62013-08-11 00:30:09 +0200783void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200784_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200785{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200786 if (!interp->modules_by_index) {
787 return;
788 }
789
790 Py_ssize_t i;
791 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
792 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
793 if (PyModule_Check(m)) {
794 /* cleanup the saved copy of module dicts */
795 PyModuleDef *md = PyModule_GetDef(m);
796 if (md) {
797 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200798 }
799 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200800 }
801
802 /* Setting modules_by_index to NULL could be dangerous, so we
803 clear the list instead. */
804 if (PyList_SetSlice(interp->modules_by_index,
805 0, PyList_GET_SIZE(interp->modules_by_index),
806 NULL)) {
807 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200808 }
809}
810
Guido van Rossuma027efa1997-05-05 20:56:21 +0000811void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000812PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000813{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200814 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200815
Victor Stinner5804f872020-03-24 16:32:26 +0100816 if (verbose && tstate->frame != NULL) {
817 /* bpo-20526: After the main thread calls
818 _PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
819 exit when trying to take the GIL. If a thread exit in the middle of
820 _PyEval_EvalFrameDefault(), tstate->frame is not reset to its
821 previous value. It is more likely with daemon threads, but it can
822 happen with regular threads if threading._shutdown() fails
823 (ex: interrupted by CTRL+C). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 fprintf(stderr,
825 "PyThreadState_Clear: warning: thread still has a frame\n");
Victor Stinner5804f872020-03-24 16:32:26 +0100826 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000827
Victor Stinner5804f872020-03-24 16:32:26 +0100828 /* Don't clear tstate->frame: it is a borrowed reference */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 Py_CLEAR(tstate->dict);
831 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 Py_CLEAR(tstate->curexc_type);
834 Py_CLEAR(tstate->curexc_value);
835 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000836
Mark Shannonae3087c2017-10-22 22:41:51 +0100837 Py_CLEAR(tstate->exc_state.exc_type);
838 Py_CLEAR(tstate->exc_state.exc_value);
839 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300840
Mark Shannonae3087c2017-10-22 22:41:51 +0100841 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200842 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100843 fprintf(stderr,
844 "PyThreadState_Clear: warning: thread still has a generator\n");
845 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 tstate->c_profilefunc = NULL;
848 tstate->c_tracefunc = NULL;
849 Py_CLEAR(tstate->c_profileobj);
850 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400851
Yury Selivanoveb636452016-09-08 22:01:51 -0700852 Py_CLEAR(tstate->async_gen_firstiter);
853 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500854
855 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100856
857 if (tstate->on_delete != NULL) {
858 tstate->on_delete(tstate->on_delete_data);
859 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000860}
861
862
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300863/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000864static void
Victor Stinner9da74302019-11-20 11:17:17 +0100865tstate_delete_common(PyThreadState *tstate,
866 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000867{
Victor Stinner3026cad2020-06-01 16:02:40 +0200868 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200869 PyInterpreterState *interp = tstate->interp;
870 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100871 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200872 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100873 _PyRuntimeState *runtime = interp->runtime;
874
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200875 HEAD_LOCK(runtime);
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100876 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200877 tstate->prev->next = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100878 }
879 else {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200880 interp->tstate_head = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100881 }
882 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200883 tstate->next->prev = tstate->prev;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100884 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200885 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100886
Victor Stinner9da74302019-11-20 11:17:17 +0100887 if (gilstate->autoInterpreterState &&
888 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
889 {
890 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
891 }
892}
893
894
895static void
896_PyThreadState_Delete(PyThreadState *tstate, int check_current)
897{
898 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
899 if (check_current) {
900 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100901 _Py_FatalErrorFormat(__func__, "tstate %p is still current", tstate);
Victor Stinner9da74302019-11-20 11:17:17 +0100902 }
903 }
904 tstate_delete_common(tstate, gilstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100905 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000906}
907
908
Victor Stinner01b1cc12019-11-20 02:27:56 +0100909void
910PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000911{
Victor Stinner9da74302019-11-20 11:17:17 +0100912 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200913}
914
915
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300916void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100917_PyThreadState_DeleteCurrent(PyThreadState *tstate)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200918{
Victor Stinner3026cad2020-06-01 16:02:40 +0200919 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100920 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner9da74302019-11-20 11:17:17 +0100921 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200922 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100923 _PyEval_ReleaseLock(tstate);
924 PyMem_RawFree(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000925}
Guido van Rossum29757862001-01-23 01:46:06 +0000926
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300927void
928PyThreadState_DeleteCurrent(void)
929{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100930 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
931 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
932 _PyThreadState_DeleteCurrent(tstate);
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300933}
934
Guido van Rossum29757862001-01-23 01:46:06 +0000935
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200936/*
937 * Delete all thread states except the one passed as argument.
938 * Note that, if there is a current thread state, it *must* be the one
939 * passed as argument. Also, this won't touch any other interpreters
940 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000941 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200942 */
943void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200944_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200945{
946 PyInterpreterState *interp = tstate->interp;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100947
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200948 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200949 /* Remove all thread states, except tstate, from the linked list of
950 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200951 without holding the lock. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100952 PyThreadState *list = interp->tstate_head;
953 if (list == tstate) {
954 list = tstate->next;
955 }
956 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200957 tstate->prev->next = tstate->next;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100958 }
959 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200960 tstate->next->prev = tstate->prev;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100961 }
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200962 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200963 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200964 HEAD_UNLOCK(runtime);
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100965
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200966 /* Clear and deallocate all stale thread states. Even if this
967 executes Python code, we should be safe since it executes
968 in the current thread, not one of the stale threads. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100969 PyThreadState *p, *next;
970 for (p = list; p; p = next) {
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200971 next = p->next;
972 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200973 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200974 }
975}
976
977
Victor Stinnere838a932020-05-05 19:56:48 +0200978#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
979PyThreadState*
980_PyThreadState_GetTSS(void) {
981 return PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
982}
983#endif
984
985
Guido van Rossuma027efa1997-05-05 20:56:21 +0000986PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100987_PyThreadState_UncheckedGet(void)
988{
Victor Stinner50b48572018-11-01 01:51:40 +0100989 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100990}
991
992
993PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000994PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000995{
Victor Stinner50b48572018-11-01 01:51:40 +0100996 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200997 _Py_EnsureTstateNotNULL(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000999}
1000
1001
Victor Stinner09532fe2019-05-10 23:39:09 +02001002PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001003_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +00001004{
Victor Stinnere838a932020-05-05 19:56:48 +02001005#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1006 PyThreadState *oldts = _PyThreadState_GetTSS();
1007#else
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001008 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Victor Stinnere838a932020-05-05 19:56:48 +02001009#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +00001010
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001011 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 /* It should not be possible for more than one thread state
1013 to be used for a thread. Check this the best we can in debug
1014 builds.
1015 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02001016#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 if (newts) {
1018 /* This can be called from PyEval_RestoreThread(). Similar
1019 to it, we need to ensure errno doesn't change.
1020 */
1021 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001022 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 if (check && check->interp == newts->interp && check != newts)
1024 Py_FatalError("Invalid thread state for this thread");
1025 errno = err;
1026 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001027#endif
Victor Stinnere838a932020-05-05 19:56:48 +02001028#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1029 PyThread_tss_set(&gilstate->autoTSSkey, newts);
1030#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +00001032}
Guido van Rossumede04391998-04-10 20:18:25 +00001033
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001034PyThreadState *
1035PyThreadState_Swap(PyThreadState *newts)
1036{
1037 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
1038}
1039
Guido van Rossumede04391998-04-10 20:18:25 +00001040/* An extension mechanism to store arbitrary additional per-thread state.
1041 PyThreadState_GetDict() returns a dictionary that can be used to hold such
1042 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001043 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
1044 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +00001045
1046PyObject *
Victor Stinner0e427c62020-03-25 21:22:55 +01001047_PyThreadState_GetDict(PyThreadState *tstate)
1048{
1049 assert(tstate != NULL);
1050 if (tstate->dict == NULL) {
1051 tstate->dict = PyDict_New();
1052 if (tstate->dict == NULL) {
1053 _PyErr_Clear(tstate);
1054 }
1055 }
1056 return tstate->dict;
1057}
1058
1059
1060PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001061PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +00001062{
Victor Stinner50b48572018-11-01 01:51:40 +01001063 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner0e427c62020-03-25 21:22:55 +01001064 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 }
Victor Stinner0e427c62020-03-25 21:22:55 +01001067 return _PyThreadState_GetDict(tstate);
Guido van Rossumede04391998-04-10 20:18:25 +00001068}
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001069
1070
Victor Stinner8fb02b62020-03-13 23:38:08 +01001071PyInterpreterState *
1072PyThreadState_GetInterpreter(PyThreadState *tstate)
1073{
1074 assert(tstate != NULL);
Victor Stinner8fb02b62020-03-13 23:38:08 +01001075 return tstate->interp;
1076}
1077
1078
Victor Stinner4386b902020-04-29 03:01:43 +02001079PyFrameObject*
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001080PyThreadState_GetFrame(PyThreadState *tstate)
1081{
1082 assert(tstate != NULL);
Victor Stinner4386b902020-04-29 03:01:43 +02001083 PyFrameObject *frame = tstate->frame;
1084 Py_XINCREF(frame);
1085 return frame;
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001086}
1087
1088
Victor Stinner5c3cda02020-03-25 21:23:53 +01001089uint64_t
1090PyThreadState_GetID(PyThreadState *tstate)
1091{
1092 assert(tstate != NULL);
1093 return tstate->id;
1094}
1095
1096
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001097/* Asynchronously raise an exception in a thread.
1098 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001099 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001100 to call this, or use ctypes. Must be called with the GIL held.
1101 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1102 match any known thread id). Can be called with exc=NULL to clear an
1103 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001104
1105int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001106PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1107{
Victor Stinner09532fe2019-05-10 23:39:09 +02001108 _PyRuntimeState *runtime = &_PyRuntime;
1109 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 /* Although the GIL is held, a few C API functions can be called
1112 * without the GIL held, and in particular some that create and
1113 * destroy thread and interpreter states. Those can mutate the
1114 * list of thread states we're traversing, so to prevent that we lock
1115 * head_mutex for the duration.
1116 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001117 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001118 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1119 if (tstate->thread_id != id) {
1120 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001122
1123 /* Tricky: we need to decref the current value
1124 * (if any) in tstate->async_exc, but that can in turn
1125 * allow arbitrary Python code to run, including
1126 * perhaps calls to this function. To prevent
1127 * deadlock, we need to release head_mutex before
1128 * the decref.
1129 */
1130 PyObject *old_exc = tstate->async_exc;
1131 Py_XINCREF(exc);
1132 tstate->async_exc = exc;
1133 HEAD_UNLOCK(runtime);
1134
1135 Py_XDECREF(old_exc);
1136 _PyEval_SignalAsyncExc(tstate);
1137 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001139 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001141}
1142
1143
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001144/* Routines for advanced debuggers, requested by David Beazley.
1145 Don't use unless you know what you are doing! */
1146
1147PyInterpreterState *
1148PyInterpreterState_Head(void)
1149{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001150 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001151}
1152
1153PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001154PyInterpreterState_Main(void)
1155{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001156 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001157}
1158
1159PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001160PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001162}
1163
1164PyThreadState *
1165PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001167}
1168
1169PyThreadState *
1170PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001172}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001173
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001174/* The implementation of sys._current_frames(). This is intended to be
1175 called with the GIL held, as it will be when called via
1176 sys._current_frames(). It's possible it would work fine even without
1177 the GIL held, but haven't thought enough about that.
1178*/
1179PyObject *
1180_PyThread_CurrentFrames(void)
1181{
Victor Stinner71a35222020-03-26 22:46:14 +01001182 PyThreadState *tstate = _PyThreadState_GET();
1183 if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001184 return NULL;
1185 }
1186
Victor Stinner71a35222020-03-26 22:46:14 +01001187 PyObject *result = PyDict_New();
1188 if (result == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 return NULL;
Victor Stinner71a35222020-03-26 22:46:14 +01001190 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 /* for i in all interpreters:
1193 * for t in all of i's thread states:
1194 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001195 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 * need to grab head_mutex for the duration.
1197 */
Victor Stinner71a35222020-03-26 22:46:14 +01001198 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001199 HEAD_LOCK(runtime);
Victor Stinner71a35222020-03-26 22:46:14 +01001200 PyInterpreterState *i;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001201 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 PyThreadState *t;
1203 for (t = i->tstate_head; t != NULL; t = t->next) {
Victor Stinner4386b902020-04-29 03:01:43 +02001204 PyFrameObject *frame = t->frame;
Victor Stinner71a35222020-03-26 22:46:14 +01001205 if (frame == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 continue;
Victor Stinner71a35222020-03-26 22:46:14 +01001207 }
1208 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1209 if (id == NULL) {
1210 goto fail;
1211 }
1212 int stat = PyDict_SetItem(result, id, (PyObject *)frame);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 Py_DECREF(id);
Victor Stinner71a35222020-03-26 22:46:14 +01001214 if (stat < 0) {
1215 goto fail;
1216 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 }
1218 }
Victor Stinner71a35222020-03-26 22:46:14 +01001219 goto done;
1220
1221fail:
1222 Py_CLEAR(result);
1223
1224done:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001225 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001227}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001228
Julien Danjou64366fa2020-11-02 15:16:25 +01001229PyObject *
1230_PyThread_CurrentExceptions(void)
1231{
1232 PyThreadState *tstate = _PyThreadState_GET();
1233
1234 _Py_EnsureTstateNotNULL(tstate);
1235
1236 if (_PySys_Audit(tstate, "sys._current_exceptions", NULL) < 0) {
1237 return NULL;
1238 }
1239
1240 PyObject *result = PyDict_New();
1241 if (result == NULL) {
1242 return NULL;
1243 }
1244
1245 /* for i in all interpreters:
1246 * for t in all of i's thread states:
1247 * if t's frame isn't NULL, map t's id to its frame
1248 * Because these lists can mutate even when the GIL is held, we
1249 * need to grab head_mutex for the duration.
1250 */
1251 _PyRuntimeState *runtime = tstate->interp->runtime;
1252 HEAD_LOCK(runtime);
1253 PyInterpreterState *i;
1254 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
1255 PyThreadState *t;
1256 for (t = i->tstate_head; t != NULL; t = t->next) {
1257 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(t);
1258 if (err_info == NULL) {
1259 continue;
1260 }
1261 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1262 if (id == NULL) {
1263 goto fail;
1264 }
1265 PyObject *exc_info = PyTuple_Pack(
1266 3,
1267 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
1268 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
1269 err_info->exc_traceback != NULL ? err_info->exc_traceback : Py_None);
1270 if (exc_info == NULL) {
1271 Py_DECREF(id);
1272 goto fail;
1273 }
1274 int stat = PyDict_SetItem(result, id, exc_info);
1275 Py_DECREF(id);
1276 Py_DECREF(exc_info);
1277 if (stat < 0) {
1278 goto fail;
1279 }
1280 }
1281 }
1282 goto done;
1283
1284fail:
1285 Py_CLEAR(result);
1286
1287done:
1288 HEAD_UNLOCK(runtime);
1289 return result;
1290}
1291
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001292/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001293
1294/* Keep this as a static, as it is not reliable! It can only
1295 ever be compared to the state for the *current* thread.
1296 * If not equal, then it doesn't matter that the actual
1297 value may change immediately after comparison, as it can't
1298 possibly change to the current thread's state.
1299 * If equal, then the current thread holds the lock, so the value can't
1300 change until we yield the lock.
1301*/
1302static int
1303PyThreadState_IsCurrent(PyThreadState *tstate)
1304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001306 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001307 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1308 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001309}
1310
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001311/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001312 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001313*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001314PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001315_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001316{
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001317 if (!_Py_IsMainInterpreter(tstate)) {
1318 /* Currently, PyGILState is shared by all interpreters. The main
1319 * interpreter is responsible to initialize it. */
1320 return _PyStatus_OK();
1321 }
1322
Victor Stinner8bb32302019-04-24 16:47:40 +02001323 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001324 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001325 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001326
Victor Stinner01b1cc12019-11-20 02:27:56 +01001327 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001328
1329 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001330 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001331 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001332 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001333 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1334 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001335
Victor Stinner8bb32302019-04-24 16:47:40 +02001336 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001337 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001338}
1339
Victor Stinner861d9ab2016-03-16 22:45:24 +01001340PyInterpreterState *
1341_PyGILState_GetInterpreterStateUnsafe(void)
1342{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001343 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001344}
1345
Tim Peters19717fa2004-10-09 17:38:29 +00001346void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001347_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001348{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001349 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001350 PyThread_tss_delete(&gilstate->autoTSSkey);
1351 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001352}
1353
Victor Stinner26881c82020-06-02 15:51:37 +02001354#ifdef HAVE_FORK
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001355/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001356 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001357 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001358 */
Victor Stinner26881c82020-06-02 15:51:37 +02001359PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001360_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001361{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001362 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001363 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001364
1365 PyThread_tss_delete(&gilstate->autoTSSkey);
1366 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner26881c82020-06-02 15:51:37 +02001367 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001368 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001369
Charles-François Natalia233df82011-11-22 19:49:51 +01001370 /* If the thread had an associated auto thread state, reassociate it with
1371 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001372 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001373 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001374 {
Victor Stinner26881c82020-06-02 15:51:37 +02001375 return _PyStatus_ERR("failed to set autoTSSkey");
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001376 }
Victor Stinner26881c82020-06-02 15:51:37 +02001377 return _PyStatus_OK();
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001378}
Victor Stinner26881c82020-06-02 15:51:37 +02001379#endif
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001380
Michael W. Hudson188d4362005-06-20 16:52:57 +00001381/* When a thread state is created for a thread by some mechanism other than
1382 PyGILState_Ensure, it's important that the GILState machinery knows about
1383 it so it doesn't try to create another thread state for the thread (this is
1384 a better fix for SF bug #1010677 than the first one attempted).
1385*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001386static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001387_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001388{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001389 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001390 threadstate created in Py_Initialize(). Don't do anything for now
1391 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001392 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001394 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001395
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001396 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 The only situation where you can legitimately have more than one
1399 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001400 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001401
Victor Stinner590cebe2013-12-13 11:08:56 +01001402 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1403 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001404
Victor Stinner590cebe2013-12-13 11:08:56 +01001405 The first thread state created for that given OS level thread will
1406 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001408 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1409 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001410 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001411 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001412 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 /* PyGILState_Release must not try to delete this thread state. */
1415 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001416}
1417
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001418/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001419static PyThreadState *
1420_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1421{
1422 if (gilstate->autoInterpreterState == NULL)
1423 return NULL;
1424 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1425}
1426
Tim Peters19717fa2004-10-09 17:38:29 +00001427PyThreadState *
1428PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001429{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001430 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001431}
1432
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001433int
1434PyGILState_Check(void)
1435{
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001436 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1437 if (!gilstate->check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001438 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001439 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001440
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001441 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1442 return 1;
1443 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001444
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001445 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1446 if (tstate == NULL) {
1447 return 0;
1448 }
1449
1450 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001451}
1452
Tim Peters19717fa2004-10-09 17:38:29 +00001453PyGILState_STATE
1454PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001455{
Victor Stinner175a7042020-03-10 00:37:48 +01001456 _PyRuntimeState *runtime = &_PyRuntime;
1457 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 /* Note that we do not auto-init Python here - apart from
1460 potential races with 2 threads auto-initializing, pep-311
1461 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001462 called Py_Initialize(). */
1463
1464 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1465 called by Py_Initialize() */
Victor Stinnere838a932020-05-05 19:56:48 +02001466#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinner175a7042020-03-10 00:37:48 +01001467 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinnere838a932020-05-05 19:56:48 +02001468#endif
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001469 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001470
Victor Stinner175a7042020-03-10 00:37:48 +01001471 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1472 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001474 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001475 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001476 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001478 }
1479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 /* This is our thread state! We'll need to delete it in the
1481 matching call to PyGILState_Release(). */
1482 tcur->gilstate_counter = 0;
1483 current = 0; /* new thread state is never current */
1484 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001485 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001487 }
1488
1489 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001491 }
1492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 /* Update our counter in the thread-state - no need for locks:
1494 - tcur will remain valid as we hold the GIL.
1495 - the counter is safe as we are the only thread "allowed"
1496 to modify this value
1497 */
1498 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001501}
1502
Tim Peters19717fa2004-10-09 17:38:29 +00001503void
1504PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001505{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001506 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001507 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1508 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 Py_FatalError("auto-releasing thread-state, "
1510 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001511 }
1512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 /* We must hold the GIL and have our thread state current */
1514 /* XXX - remove the check - the assert should be fine,
1515 but while this is very new (April 2003), the extra check
1516 by release-only users can't hurt.
1517 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001518 if (!PyThreadState_IsCurrent(tstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001519 _Py_FatalErrorFormat(__func__,
1520 "thread state %p must be current when releasing",
1521 tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001522 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001523 assert(PyThreadState_IsCurrent(tstate));
1524 --tstate->gilstate_counter;
1525 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 /* If we're going to destroy this thread-state, we must
1528 * clear it while the GIL is held, as destructors may run.
1529 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001530 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 /* can't have been locked when we created it */
1532 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001533 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 /* Delete the thread-state. Note this releases the GIL too!
1535 * It's vital that the GIL be held here, to avoid shutdown
1536 * races; see bugs 225673 and 1061968 (that nasty bug has a
1537 * habit of coming back).
1538 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001539 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1540 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 }
1542 /* Release the lock if necessary */
1543 else if (oldstate == PyGILState_UNLOCKED)
1544 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001545}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001546
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001547
Eric Snow7f8bfc92018-01-29 18:23:44 -07001548/**************************/
1549/* cross-interpreter data */
1550/**************************/
1551
1552/* cross-interpreter data */
1553
1554crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1555
1556/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1557 to keep the registry code separate. */
1558static crossinterpdatafunc
1559_lookup_getdata(PyObject *obj)
1560{
1561 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1562 if (getdata == NULL && PyErr_Occurred() == 0)
1563 PyErr_Format(PyExc_ValueError,
1564 "%S does not support cross-interpreter data", obj);
1565 return getdata;
1566}
1567
1568int
1569_PyObject_CheckCrossInterpreterData(PyObject *obj)
1570{
1571 crossinterpdatafunc getdata = _lookup_getdata(obj);
1572 if (getdata == NULL) {
1573 return -1;
1574 }
1575 return 0;
1576}
1577
1578static int
Victor Stinner71a35222020-03-26 22:46:14 +01001579_check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001580{
1581 // data->data can be anything, including NULL, so we don't check it.
1582
1583 // data->obj may be NULL, so we don't check it.
1584
1585 if (data->interp < 0) {
Victor Stinner71a35222020-03-26 22:46:14 +01001586 _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001587 return -1;
1588 }
1589
1590 if (data->new_object == NULL) {
Victor Stinner71a35222020-03-26 22:46:14 +01001591 _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001592 return -1;
1593 }
1594
1595 // data->free may be NULL, so we don't check it.
1596
1597 return 0;
1598}
1599
1600int
1601_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1602{
Victor Stinner71a35222020-03-26 22:46:14 +01001603 // PyThreadState_Get() aborts if tstate is NULL.
1604 PyThreadState *tstate = PyThreadState_Get();
1605 PyInterpreterState *interp = tstate->interp;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001606
1607 // Reset data before re-populating.
1608 *data = (_PyCrossInterpreterData){0};
1609 data->free = PyMem_RawFree; // Set a default that may be overridden.
1610
1611 // Call the "getdata" func for the object.
1612 Py_INCREF(obj);
1613 crossinterpdatafunc getdata = _lookup_getdata(obj);
1614 if (getdata == NULL) {
1615 Py_DECREF(obj);
1616 return -1;
1617 }
1618 int res = getdata(obj, data);
1619 Py_DECREF(obj);
1620 if (res != 0) {
1621 return -1;
1622 }
1623
1624 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001625 data->interp = interp->id;
Victor Stinner71a35222020-03-26 22:46:14 +01001626 if (_check_xidata(tstate, data) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001627 _PyCrossInterpreterData_Release(data);
1628 return -1;
1629 }
1630
1631 return 0;
1632}
1633
Victor Stinnere225beb2019-06-03 18:14:24 +02001634static void
Eric Snow63799132018-06-01 18:45:20 -06001635_release_xidata(void *arg)
1636{
1637 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1638 if (data->free != NULL) {
1639 data->free(data->data);
1640 }
1641 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001642}
1643
1644static void
1645_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1646 PyInterpreterState *interp,
1647 void (*func)(void *), void *arg)
1648{
1649 /* We would use Py_AddPendingCall() if it weren't specific to the
1650 * main interpreter (see bpo-33608). In the meantime we take a
1651 * naive approach.
1652 */
1653 PyThreadState *save_tstate = NULL;
1654 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1655 // XXX Using the "head" thread isn't strictly correct.
1656 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1657 // XXX Possible GILState issues?
1658 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1659 }
1660
1661 func(arg);
1662
1663 // Switch back.
1664 if (save_tstate != NULL) {
1665 _PyThreadState_Swap(gilstate, save_tstate);
1666 }
Eric Snow63799132018-06-01 18:45:20 -06001667}
1668
Eric Snow7f8bfc92018-01-29 18:23:44 -07001669void
1670_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1671{
1672 if (data->data == NULL && data->obj == NULL) {
1673 // Nothing to release!
1674 return;
1675 }
1676
Victor Stinnere225beb2019-06-03 18:14:24 +02001677 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001678 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1679 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001680 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001681 if (data->free != NULL) {
1682 // XXX Someone leaked some memory...
1683 }
1684 return;
1685 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001686
Eric Snow7f8bfc92018-01-29 18:23:44 -07001687 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001688 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1689 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001690}
1691
1692PyObject *
1693_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1694{
1695 return data->new_object(data);
1696}
1697
1698/* registry of {type -> crossinterpdatafunc} */
1699
1700/* For now we use a global registry of shareable classes. An
1701 alternative would be to add a tp_* slot for a class's
1702 crossinterpdatafunc. It would be simpler and more efficient. */
1703
1704static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001705_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1706 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001707{
1708 // Note that we effectively replace already registered classes
1709 // rather than failing.
1710 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1711 if (newhead == NULL)
1712 return -1;
1713 newhead->cls = cls;
1714 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001715 newhead->next = xidregistry->head;
1716 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001717 return 0;
1718}
1719
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001720static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001721
1722int
Eric Snowc11183c2019-03-15 16:35:46 -06001723_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001724 crossinterpdatafunc getdata)
1725{
1726 if (!PyType_Check(cls)) {
1727 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1728 return -1;
1729 }
1730 if (getdata == NULL) {
1731 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1732 return -1;
1733 }
1734
1735 // Make sure the class isn't ever deallocated.
1736 Py_INCREF((PyObject *)cls);
1737
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001738 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1739 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1740 if (xidregistry->head == NULL) {
1741 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001742 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001743 int res = _register_xidata(xidregistry, cls, getdata);
1744 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001745 return res;
1746}
1747
Eric Snow6d2cd902018-05-16 15:04:57 -04001748/* Cross-interpreter objects are looked up by exact match on the class.
1749 We can reassess this policy when we move from a global registry to a
1750 tp_* slot. */
1751
Eric Snow7f8bfc92018-01-29 18:23:44 -07001752crossinterpdatafunc
1753_PyCrossInterpreterData_Lookup(PyObject *obj)
1754{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001755 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001756 PyObject *cls = PyObject_Type(obj);
1757 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001758 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1759 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001760 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001761 _register_builtins_for_crossinterpreter_data(xidregistry);
1762 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001763 }
1764 for(; cur != NULL; cur = cur->next) {
1765 if (cur->cls == (PyTypeObject *)cls) {
1766 getdata = cur->getdata;
1767 break;
1768 }
1769 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001770 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001771 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001772 return getdata;
1773}
1774
1775/* cross-interpreter data for builtin types */
1776
Eric Snow6d2cd902018-05-16 15:04:57 -04001777struct _shared_bytes_data {
1778 char *bytes;
1779 Py_ssize_t len;
1780};
1781
Eric Snow7f8bfc92018-01-29 18:23:44 -07001782static PyObject *
1783_new_bytes_object(_PyCrossInterpreterData *data)
1784{
Eric Snow6d2cd902018-05-16 15:04:57 -04001785 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1786 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001787}
1788
1789static int
1790_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1791{
Eric Snow6d2cd902018-05-16 15:04:57 -04001792 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1793 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1794 return -1;
1795 }
1796 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001797 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001798 data->obj = obj; // Will be "released" (decref'ed) when data released.
1799 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001800 data->free = PyMem_Free;
1801 return 0;
1802}
1803
1804struct _shared_str_data {
1805 int kind;
1806 const void *buffer;
1807 Py_ssize_t len;
1808};
1809
1810static PyObject *
1811_new_str_object(_PyCrossInterpreterData *data)
1812{
1813 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1814 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1815}
1816
1817static int
1818_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1819{
1820 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1821 shared->kind = PyUnicode_KIND(obj);
1822 shared->buffer = PyUnicode_DATA(obj);
An Long29c11722020-06-13 20:26:01 +08001823 shared->len = PyUnicode_GET_LENGTH(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001824 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001825 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001826 data->obj = obj; // Will be "released" (decref'ed) when data released.
1827 data->new_object = _new_str_object;
1828 data->free = PyMem_Free;
1829 return 0;
1830}
1831
1832static PyObject *
1833_new_long_object(_PyCrossInterpreterData *data)
1834{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001835 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001836}
1837
1838static int
1839_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1840{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001841 /* Note that this means the size of shareable ints is bounded by
1842 * sys.maxsize. Hence on 32-bit architectures that is half the
1843 * size of maximum shareable ints on 64-bit.
1844 */
1845 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001846 if (value == -1 && PyErr_Occurred()) {
1847 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1848 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1849 }
1850 return -1;
1851 }
1852 data->data = (void *)value;
1853 data->obj = NULL;
1854 data->new_object = _new_long_object;
1855 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001856 return 0;
1857}
1858
1859static PyObject *
1860_new_none_object(_PyCrossInterpreterData *data)
1861{
1862 // XXX Singleton refcounts are problematic across interpreters...
1863 Py_INCREF(Py_None);
1864 return Py_None;
1865}
1866
1867static int
1868_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1869{
1870 data->data = NULL;
1871 // data->obj remains NULL
1872 data->new_object = _new_none_object;
1873 data->free = NULL; // There is nothing to free.
1874 return 0;
1875}
1876
1877static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001878_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001879{
1880 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001881 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001882 Py_FatalError("could not register None for cross-interpreter sharing");
1883 }
1884
Eric Snow6d2cd902018-05-16 15:04:57 -04001885 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001886 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001887 Py_FatalError("could not register int for cross-interpreter sharing");
1888 }
1889
Eric Snow7f8bfc92018-01-29 18:23:44 -07001890 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001891 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001892 Py_FatalError("could not register bytes for cross-interpreter sharing");
1893 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001894
1895 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001896 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001897 Py_FatalError("could not register str for cross-interpreter sharing");
1898 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001899}
1900
1901
Victor Stinner0b72b232020-03-12 23:18:39 +01001902_PyFrameEvalFunction
1903_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1904{
1905 return interp->eval_frame;
1906}
1907
1908
1909void
1910_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1911 _PyFrameEvalFunction eval_frame)
1912{
1913 interp->eval_frame = eval_frame;
1914}
1915
Victor Stinnerda7933e2020-04-13 03:04:28 +02001916
1917const PyConfig*
1918_PyInterpreterState_GetConfig(PyInterpreterState *interp)
1919{
1920 return &interp->config;
1921}
1922
1923
Victor Stinner048a3562020-11-05 00:45:56 +01001924int
1925_PyInterpreterState_GetConfigCopy(PyConfig *config)
Victor Stinnerda7933e2020-04-13 03:04:28 +02001926{
Victor Stinner048a3562020-11-05 00:45:56 +01001927 PyInterpreterState *interp = PyInterpreterState_Get();
1928
1929 PyStatus status = _PyConfig_Copy(config, &interp->config);
1930 if (PyStatus_Exception(status)) {
1931 _PyErr_SetFromPyStatus(status);
1932 return -1;
1933 }
1934 return 0;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001935}
1936
1937
1938const PyConfig*
1939_Py_GetConfig(void)
1940{
1941 assert(PyGILState_Check());
1942 PyThreadState *tstate = _PyThreadState_GET();
1943 return _PyInterpreterState_GetConfig(tstate->interp);
1944}
1945
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001946#ifdef __cplusplus
1947}
1948#endif