blob: f92c55e7471697ce8b59fa3b7e0d768e84a36d6c [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
127 * newly created child processes do not share locks with the parent.
128 */
129
130void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200131_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700132{
133 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200134 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700135
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200136 /* Force default allocator, since _PyRuntimeState_Fini() must
137 use the same allocator than this function. */
138 PyMemAllocatorEx old_alloc;
139 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
140
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900141 int interp_mutex = _PyThread_at_fork_reinit(&runtime->interpreters.mutex);
142 int main_interp_id_mutex = _PyThread_at_fork_reinit(&runtime->interpreters.main->id_mutex);
143 int xidregistry_mutex = _PyThread_at_fork_reinit(&runtime->xidregistry.mutex);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200144
145 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
146
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900147 if (interp_mutex < 0) {
Eric Snow8479a342019-03-08 23:44:33 -0700148 Py_FatalError("Can't initialize lock for runtime interpreters");
149 }
150
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900151 if (main_interp_id_mutex < 0) {
Eric Snow8479a342019-03-08 23:44:33 -0700152 Py_FatalError("Can't initialize ID lock for main interpreter");
153 }
154
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900155 if (xidregistry_mutex < 0) {
Eric Snow8479a342019-03-08 23:44:33 -0700156 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
157 }
158}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900159#endif
Eric Snow8479a342019-03-08 23:44:33 -0700160
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200161#define HEAD_LOCK(runtime) \
162 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
163#define HEAD_UNLOCK(runtime) \
164 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700165
Victor Stinner8bb32302019-04-24 16:47:40 +0200166/* Forward declaration */
167static void _PyGILState_NoteThreadState(
168 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000169
Victor Stinner331a6a52019-05-27 16:39:22 +0200170PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600171_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700172{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200173 struct pyinterpreters *interpreters = &runtime->interpreters;
174 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100175
176 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
177 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200178 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100179 /* Force default allocator, since _PyRuntimeState_Fini() must
180 use the same allocator than this function. */
181 PyMemAllocatorEx old_alloc;
182 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
183
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200184 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100185
186 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
187
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200188 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200189 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800190 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600191 }
Victor Stinner5d926472018-03-06 14:31:37 +0100192
Victor Stinner331a6a52019-05-27 16:39:22 +0200193 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700194}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000195
196PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000197PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000198{
Victor Stinner71a35222020-03-26 22:46:14 +0100199 PyThreadState *tstate = _PyThreadState_GET();
200 /* tstate is NULL when Py_InitializeFromConfig() calls
201 PyInterpreterState_New() to create the main interpreter. */
202 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_New", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700203 return NULL;
204 }
205
Andy Lester7668a8b2020-03-24 23:26:44 -0500206 PyInterpreterState *interp = PyMem_RawCalloc(1, sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100207 if (interp == NULL) {
208 return NULL;
209 }
210
Eric Snow4c6955e2018-02-16 18:53:40 -0700211 interp->id_refcount = -1;
Victor Stinner022be022019-05-22 23:58:50 +0200212
Victor Stinner71a35222020-03-26 22:46:14 +0100213 /* Don't get runtime from tstate since tstate can be NULL */
Victor Stinner01b1cc12019-11-20 02:27:56 +0100214 _PyRuntimeState *runtime = &_PyRuntime;
215 interp->runtime = runtime;
216
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200217 if (_PyEval_InitState(&interp->ceval) < 0) {
218 goto out_of_memory;
219 }
220
Victor Stinner72474072019-11-20 12:25:50 +0100221 _PyGC_InitState(&interp->gc);
Victor Stinner8462a492019-10-01 12:06:16 +0200222 PyConfig_InitPythonConfig(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200223
Victor Stinnerd4341102017-11-23 00:12:09 +0100224 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000225#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300226#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100227 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000228#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100229 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000230#endif
231#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000232
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200233 struct pyinterpreters *interpreters = &runtime->interpreters;
234
235 HEAD_LOCK(runtime);
236 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100237 /* overflow or Py_Initialize() not called! */
Victor Stinner71a35222020-03-26 22:46:14 +0100238 if (tstate != NULL) {
239 _PyErr_SetString(tstate, PyExc_RuntimeError,
240 "failed to get an interpreter ID");
241 }
Pablo Galindo95d630e2018-08-31 22:49:29 +0100242 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100243 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100244 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200245 else {
246 interp->id = interpreters->next_id;
247 interpreters->next_id += 1;
248 interp->next = interpreters->head;
249 if (interpreters->main == NULL) {
250 interpreters->main = interp;
251 }
252 interpreters->head = interp;
253 }
254 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000255
Pablo Galindo95d630e2018-08-31 22:49:29 +0100256 if (interp == NULL) {
257 return NULL;
258 }
259
Yury Selivanovf23746a2018-01-22 19:11:18 -0500260 interp->tstate_next_unique_id = 0;
261
Steve Dowerb82e17e2019-05-23 08:45:22 -0700262 interp->audit_hooks = NULL;
263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 return interp;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200265
266out_of_memory:
267 if (tstate != NULL) {
268 _PyErr_NoMemory(tstate);
269 }
270
271 PyMem_RawFree(interp);
272 return NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000273}
274
275
Victor Stinner01b1cc12019-11-20 02:27:56 +0100276void
277PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000278{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100279 _PyRuntimeState *runtime = interp->runtime;
280
Victor Stinner71a35222020-03-26 22:46:14 +0100281 /* Use the current Python thread state to call audit hooks,
282 not the current Python thread state of 'interp'. */
283 PyThreadState *tstate = _PyThreadState_GET();
284 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_Clear", NULL) < 0) {
285 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700286 }
287
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200288 HEAD_LOCK(runtime);
289 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200291 }
292 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700293
294 Py_CLEAR(interp->audit_hooks);
295
Victor Stinner331a6a52019-05-27 16:39:22 +0200296 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 Py_CLEAR(interp->codec_search_path);
298 Py_CLEAR(interp->codec_search_cache);
299 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700300 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 Py_CLEAR(interp->sysdict);
303 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200304 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400305 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300306 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600307 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200308#ifdef HAVE_FORK
309 Py_CLEAR(interp->before_forkers);
310 Py_CLEAR(interp->after_forkers_parent);
311 Py_CLEAR(interp->after_forkers_child);
312#endif
Victor Stinner7b3c2522020-03-07 00:24:23 +0100313 if (_PyRuntimeState_GetFinalizing(runtime) == NULL) {
Eric Snow86ea5812019-05-10 13:29:55 -0400314 _PyWarnings_Fini(interp);
315 }
Eric Snow5be45a62019-03-08 22:47:07 -0700316 // XXX Once we have one allocator per interpreter (i.e.
317 // per-interpreter GC) we must ensure that all of the interpreter's
318 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000319}
320
321
322static void
Victor Stinner9da74302019-11-20 11:17:17 +0100323zapthreads(PyInterpreterState *interp, int check_current)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000324{
Victor Stinner9da74302019-11-20 11:17:17 +0100325 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 /* No need to lock the mutex here because this should only happen
327 when the threads are all really dead (XXX famous last words). */
Victor Stinner9da74302019-11-20 11:17:17 +0100328 while ((tstate = interp->tstate_head) != NULL) {
329 _PyThreadState_Delete(tstate, check_current);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000331}
332
333
Victor Stinner01b1cc12019-11-20 02:27:56 +0100334void
335PyInterpreterState_Delete(PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200336{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100337 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200338 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner9da74302019-11-20 11:17:17 +0100339 zapthreads(interp, 0);
340
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200341 _PyEval_FiniState(&interp->ceval);
342
Victor Stinner9da74302019-11-20 11:17:17 +0100343 /* Delete current thread. After this, many C API calls become crashy. */
344 _PyThreadState_Swap(&runtime->gilstate, NULL);
345
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200346 HEAD_LOCK(runtime);
347 PyInterpreterState **p;
348 for (p = &interpreters->head; ; p = &(*p)->next) {
349 if (*p == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100350 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200351 }
352 if (*p == interp) {
353 break;
354 }
355 }
356 if (interp->tstate_head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100357 Py_FatalError("remaining threads");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200358 }
359 *p = interp->next;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200360
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200361 if (interpreters->main == interp) {
362 interpreters->main = NULL;
363 if (interpreters->head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100364 Py_FatalError("remaining subinterpreters");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200365 }
366 }
367 HEAD_UNLOCK(runtime);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200368
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200369 if (interp->id_mutex != NULL) {
370 PyThread_free_lock(interp->id_mutex);
371 }
372 PyMem_RawFree(interp);
373}
374
375
Eric Snow59032962018-09-14 14:17:20 -0700376/*
377 * Delete all interpreter states except the main interpreter. If there
378 * is a current interpreter state, it *must* be the main interpreter.
379 */
380void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200381_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700382{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200383 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200384 struct pyinterpreters *interpreters = &runtime->interpreters;
385
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200386 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200387 if (tstate != NULL && tstate->interp != interpreters->main) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100388 Py_FatalError("not main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700389 }
390
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200391 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200392 PyInterpreterState *interp = interpreters->head;
393 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100394 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200395 if (interp == interpreters->main) {
396 interpreters->main->next = NULL;
397 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100398 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700399 continue;
400 }
401
Victor Stinner01b1cc12019-11-20 02:27:56 +0100402 PyInterpreterState_Clear(interp); // XXX must activate?
Victor Stinner9da74302019-11-20 11:17:17 +0100403 zapthreads(interp, 1);
Eric Snow59032962018-09-14 14:17:20 -0700404 if (interp->id_mutex != NULL) {
405 PyThread_free_lock(interp->id_mutex);
406 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100407 PyInterpreterState *prev_interp = interp;
408 interp = interp->next;
409 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700410 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200411 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700412
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200413 if (interpreters->head == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100414 Py_FatalError("missing main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700415 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200416 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700417}
418
419
Victor Stinnercaba55b2018-08-03 15:33:52 +0200420PyInterpreterState *
Victor Stinnerbe793732020-03-13 18:15:33 +0100421PyInterpreterState_Get(void)
Victor Stinnercaba55b2018-08-03 15:33:52 +0200422{
Victor Stinner50b48572018-11-01 01:51:40 +0100423 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200424 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200425 PyInterpreterState *interp = tstate->interp;
426 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100427 Py_FatalError("no current interpreter");
Victor Stinnercaba55b2018-08-03 15:33:52 +0200428 }
429 return interp;
430}
431
432
Eric Snowe3774162017-05-22 19:46:40 -0700433int64_t
434PyInterpreterState_GetID(PyInterpreterState *interp)
435{
436 if (interp == NULL) {
437 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
438 return -1;
439 }
440 return interp->id;
441}
442
443
Eric Snow5be45a62019-03-08 22:47:07 -0700444static PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200445interp_look_up_id(_PyRuntimeState *runtime, int64_t requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700446{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200447 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100448 while (interp != NULL) {
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200449 int64_t id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700450 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100451 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700452 }
453 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100454 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700455 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100456 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700457 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100458 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700459}
460
Eric Snow5be45a62019-03-08 22:47:07 -0700461PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200462_PyInterpreterState_LookUpID(int64_t requested_id)
Eric Snow5be45a62019-03-08 22:47:07 -0700463{
464 PyInterpreterState *interp = NULL;
465 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200466 _PyRuntimeState *runtime = &_PyRuntime;
467 HEAD_LOCK(runtime);
468 interp = interp_look_up_id(runtime, requested_id);
469 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700470 }
471 if (interp == NULL && !PyErr_Occurred()) {
472 PyErr_Format(PyExc_RuntimeError,
473 "unrecognized interpreter ID %lld", requested_id);
474 }
475 return interp;
476}
477
Eric Snow4c6955e2018-02-16 18:53:40 -0700478
479int
480_PyInterpreterState_IDInitref(PyInterpreterState *interp)
481{
482 if (interp->id_mutex != NULL) {
483 return 0;
484 }
485 interp->id_mutex = PyThread_allocate_lock();
486 if (interp->id_mutex == NULL) {
487 PyErr_SetString(PyExc_RuntimeError,
488 "failed to create init interpreter ID mutex");
489 return -1;
490 }
491 interp->id_refcount = 0;
492 return 0;
493}
494
495
496void
497_PyInterpreterState_IDIncref(PyInterpreterState *interp)
498{
499 if (interp->id_mutex == NULL) {
500 return;
501 }
502 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
503 interp->id_refcount += 1;
504 PyThread_release_lock(interp->id_mutex);
505}
506
507
508void
509_PyInterpreterState_IDDecref(PyInterpreterState *interp)
510{
511 if (interp->id_mutex == NULL) {
512 return;
513 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200514 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700515 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
516 assert(interp->id_refcount != 0);
517 interp->id_refcount -= 1;
518 int64_t refcount = interp->id_refcount;
519 PyThread_release_lock(interp->id_mutex);
520
Eric Snowc11183c2019-03-15 16:35:46 -0600521 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700522 // XXX Using the "head" thread isn't strictly correct.
523 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
524 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200525 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700526 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200527 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700528 }
529}
530
Eric Snowc11183c2019-03-15 16:35:46 -0600531int
532_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
533{
534 return interp->requires_idref;
535}
536
537void
538_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
539{
540 interp->requires_idref = required ? 1 : 0;
541}
542
Eric Snowc11183c2019-03-15 16:35:46 -0600543PyObject *
544_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
545{
546 if (interp->modules == NULL) {
547 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
548 return NULL;
549 }
550 return PyMapping_GetItemString(interp->modules, "__main__");
551}
552
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600553PyObject *
554PyInterpreterState_GetDict(PyInterpreterState *interp)
555{
556 if (interp->dict == NULL) {
557 interp->dict = PyDict_New();
558 if (interp->dict == NULL) {
559 PyErr_Clear();
560 }
561 }
562 /* Returning NULL means no per-interpreter dict is available. */
563 return interp->dict;
564}
565
Victor Stinner45b9be52010-03-03 23:28:07 +0000566static PyThreadState *
567new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000568{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100569 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200570 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200571 if (tstate == NULL) {
572 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574
Victor Stinner8bb32302019-04-24 16:47:40 +0200575 tstate->interp = interp;
576
577 tstate->frame = NULL;
578 tstate->recursion_depth = 0;
579 tstate->overflowed = 0;
580 tstate->recursion_critical = 0;
581 tstate->stackcheck_counter = 0;
582 tstate->tracing = 0;
583 tstate->use_tracing = 0;
584 tstate->gilstate_counter = 0;
585 tstate->async_exc = NULL;
586 tstate->thread_id = PyThread_get_thread_ident();
587
588 tstate->dict = NULL;
589
590 tstate->curexc_type = NULL;
591 tstate->curexc_value = NULL;
592 tstate->curexc_traceback = NULL;
593
594 tstate->exc_state.exc_type = NULL;
595 tstate->exc_state.exc_value = NULL;
596 tstate->exc_state.exc_traceback = NULL;
597 tstate->exc_state.previous_item = NULL;
598 tstate->exc_info = &tstate->exc_state;
599
600 tstate->c_profilefunc = NULL;
601 tstate->c_tracefunc = NULL;
602 tstate->c_profileobj = NULL;
603 tstate->c_traceobj = NULL;
604
605 tstate->trash_delete_nesting = 0;
606 tstate->trash_delete_later = NULL;
607 tstate->on_delete = NULL;
608 tstate->on_delete_data = NULL;
609
610 tstate->coroutine_origin_tracking_depth = 0;
611
Victor Stinner8bb32302019-04-24 16:47:40 +0200612 tstate->async_gen_firstiter = NULL;
613 tstate->async_gen_finalizer = NULL;
614
615 tstate->context = NULL;
616 tstate->context_ver = 1;
617
Victor Stinner8bb32302019-04-24 16:47:40 +0200618 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100619 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200620 }
621
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200622 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100623 tstate->id = ++interp->tstate_next_unique_id;
Victor Stinner8bb32302019-04-24 16:47:40 +0200624 tstate->prev = NULL;
625 tstate->next = interp->tstate_head;
626 if (tstate->next)
627 tstate->next->prev = tstate;
628 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200629 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000632}
633
Victor Stinner45b9be52010-03-03 23:28:07 +0000634PyThreadState *
635PyThreadState_New(PyInterpreterState *interp)
636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000638}
639
640PyThreadState *
641_PyThreadState_Prealloc(PyInterpreterState *interp)
642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000644}
645
646void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100647_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000648{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100649 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000650}
651
Martin v. Löwis1a214512008-06-11 05:26:20 +0000652PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200653PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000654{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200655 Py_ssize_t index = module->m_base.m_index;
Victor Stinner81a7be32020-04-14 15:14:01 +0200656 PyInterpreterState *state = _PyInterpreterState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000658 if (module->m_slots) {
659 return NULL;
660 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 if (index == 0)
662 return NULL;
663 if (state->modules_by_index == NULL)
664 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200665 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 return NULL;
667 res = PyList_GET_ITEM(state->modules_by_index, index);
668 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000669}
670
671int
Victor Stinner82c83bd2019-11-22 18:52:27 +0100672_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000673{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300674 if (!def) {
Victor Stinner71a35222020-03-26 22:46:14 +0100675 assert(_PyErr_Occurred(tstate));
Berker Peksag4b7b5652016-08-22 18:05:56 +0300676 return -1;
677 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000678 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100679 _PyErr_SetString(tstate,
680 PyExc_SystemError,
681 "PyState_AddModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000682 return -1;
683 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100684
685 PyInterpreterState *interp = tstate->interp;
686 if (!interp->modules_by_index) {
687 interp->modules_by_index = PyList_New(0);
688 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100690 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100692
693 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
694 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100696 }
697 }
698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100700 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000702}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000703
Martin v. Löwis7800f752012-06-22 12:20:55 +0200704int
705PyState_AddModule(PyObject* module, struct PyModuleDef* def)
706{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200707 if (!def) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100708 Py_FatalError("module definition is NULL");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200709 return -1;
710 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100711
712 PyThreadState *tstate = _PyThreadState_GET();
713 PyInterpreterState *interp = tstate->interp;
714 Py_ssize_t index = def->m_base.m_index;
715 if (interp->modules_by_index &&
716 index < PyList_GET_SIZE(interp->modules_by_index) &&
717 module == PyList_GET_ITEM(interp->modules_by_index, index))
718 {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100719 _Py_FatalErrorFormat(__func__, "module %p already added", module);
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100720 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200721 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100722 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200723}
724
725int
726PyState_RemoveModule(struct PyModuleDef* def)
727{
Victor Stinner71a35222020-03-26 22:46:14 +0100728 PyThreadState *tstate = _PyThreadState_GET();
729 PyInterpreterState *interp = tstate->interp;
730
Nick Coghland5cacbb2015-05-23 22:24:10 +1000731 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100732 _PyErr_SetString(tstate,
733 PyExc_SystemError,
734 "PyState_RemoveModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000735 return -1;
736 }
Victor Stinner71a35222020-03-26 22:46:14 +0100737
738 Py_ssize_t index = def->m_base.m_index;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200739 if (index == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100740 Py_FatalError("invalid module index");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200741 }
Victor Stinner71a35222020-03-26 22:46:14 +0100742 if (interp->modules_by_index == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100743 Py_FatalError("Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200744 }
Victor Stinner71a35222020-03-26 22:46:14 +0100745 if (index > PyList_GET_SIZE(interp->modules_by_index)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100746 Py_FatalError("Module index out of bounds.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200747 }
Victor Stinner71a35222020-03-26 22:46:14 +0100748
Zackery Spytz2a893432018-12-05 00:14:00 -0700749 Py_INCREF(Py_None);
Victor Stinner71a35222020-03-26 22:46:14 +0100750 return PyList_SetItem(interp->modules_by_index, index, Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200751}
752
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200753/* Used by PyImport_Cleanup() */
Antoine Pitrou40322e62013-08-11 00:30:09 +0200754void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200755_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200756{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200757 if (!interp->modules_by_index) {
758 return;
759 }
760
761 Py_ssize_t i;
762 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
763 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
764 if (PyModule_Check(m)) {
765 /* cleanup the saved copy of module dicts */
766 PyModuleDef *md = PyModule_GetDef(m);
767 if (md) {
768 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200769 }
770 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200771 }
772
773 /* Setting modules_by_index to NULL could be dangerous, so we
774 clear the list instead. */
775 if (PyList_SetSlice(interp->modules_by_index,
776 0, PyList_GET_SIZE(interp->modules_by_index),
777 NULL)) {
778 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200779 }
780}
781
Guido van Rossuma027efa1997-05-05 20:56:21 +0000782void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000783PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000784{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200785 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200786
Victor Stinner5804f872020-03-24 16:32:26 +0100787 if (verbose && tstate->frame != NULL) {
788 /* bpo-20526: After the main thread calls
789 _PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
790 exit when trying to take the GIL. If a thread exit in the middle of
791 _PyEval_EvalFrameDefault(), tstate->frame is not reset to its
792 previous value. It is more likely with daemon threads, but it can
793 happen with regular threads if threading._shutdown() fails
794 (ex: interrupted by CTRL+C). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 fprintf(stderr,
796 "PyThreadState_Clear: warning: thread still has a frame\n");
Victor Stinner5804f872020-03-24 16:32:26 +0100797 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000798
Victor Stinner5804f872020-03-24 16:32:26 +0100799 /* Don't clear tstate->frame: it is a borrowed reference */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 Py_CLEAR(tstate->dict);
802 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 Py_CLEAR(tstate->curexc_type);
805 Py_CLEAR(tstate->curexc_value);
806 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000807
Mark Shannonae3087c2017-10-22 22:41:51 +0100808 Py_CLEAR(tstate->exc_state.exc_type);
809 Py_CLEAR(tstate->exc_state.exc_value);
810 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300811
Mark Shannonae3087c2017-10-22 22:41:51 +0100812 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200813 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100814 fprintf(stderr,
815 "PyThreadState_Clear: warning: thread still has a generator\n");
816 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 tstate->c_profilefunc = NULL;
819 tstate->c_tracefunc = NULL;
820 Py_CLEAR(tstate->c_profileobj);
821 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400822
Yury Selivanoveb636452016-09-08 22:01:51 -0700823 Py_CLEAR(tstate->async_gen_firstiter);
824 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500825
826 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100827
828 if (tstate->on_delete != NULL) {
829 tstate->on_delete(tstate->on_delete_data);
830 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000831}
832
833
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300834/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000835static void
Victor Stinner9da74302019-11-20 11:17:17 +0100836tstate_delete_common(PyThreadState *tstate,
837 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000838{
Victor Stinner3026cad2020-06-01 16:02:40 +0200839 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200840 PyInterpreterState *interp = tstate->interp;
841 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100842 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200843 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100844 _PyRuntimeState *runtime = interp->runtime;
845
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200846 HEAD_LOCK(runtime);
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100847 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200848 tstate->prev->next = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100849 }
850 else {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200851 interp->tstate_head = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100852 }
853 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200854 tstate->next->prev = tstate->prev;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100855 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200856 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100857
Victor Stinner9da74302019-11-20 11:17:17 +0100858 if (gilstate->autoInterpreterState &&
859 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
860 {
861 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
862 }
863}
864
865
866static void
867_PyThreadState_Delete(PyThreadState *tstate, int check_current)
868{
869 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
870 if (check_current) {
871 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100872 _Py_FatalErrorFormat(__func__, "tstate %p is still current", tstate);
Victor Stinner9da74302019-11-20 11:17:17 +0100873 }
874 }
875 tstate_delete_common(tstate, gilstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100876 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000877}
878
879
Victor Stinner01b1cc12019-11-20 02:27:56 +0100880void
881PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000882{
Victor Stinner9da74302019-11-20 11:17:17 +0100883 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200884}
885
886
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300887void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100888_PyThreadState_DeleteCurrent(PyThreadState *tstate)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200889{
Victor Stinner3026cad2020-06-01 16:02:40 +0200890 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100891 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner9da74302019-11-20 11:17:17 +0100892 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200893 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100894 _PyEval_ReleaseLock(tstate);
895 PyMem_RawFree(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000896}
Guido van Rossum29757862001-01-23 01:46:06 +0000897
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300898void
899PyThreadState_DeleteCurrent(void)
900{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100901 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
902 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
903 _PyThreadState_DeleteCurrent(tstate);
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300904}
905
Guido van Rossum29757862001-01-23 01:46:06 +0000906
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200907/*
908 * Delete all thread states except the one passed as argument.
909 * Note that, if there is a current thread state, it *must* be the one
910 * passed as argument. Also, this won't touch any other interpreters
911 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000912 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200913 */
914void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200915_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200916{
917 PyInterpreterState *interp = tstate->interp;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100918
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200919 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200920 /* Remove all thread states, except tstate, from the linked list of
921 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200922 without holding the lock. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100923 PyThreadState *list = interp->tstate_head;
924 if (list == tstate) {
925 list = tstate->next;
926 }
927 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200928 tstate->prev->next = tstate->next;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100929 }
930 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200931 tstate->next->prev = tstate->prev;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100932 }
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200933 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200934 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200935 HEAD_UNLOCK(runtime);
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100936
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200937 /* Clear and deallocate all stale thread states. Even if this
938 executes Python code, we should be safe since it executes
939 in the current thread, not one of the stale threads. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100940 PyThreadState *p, *next;
941 for (p = list; p; p = next) {
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200942 next = p->next;
943 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200944 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200945 }
946}
947
948
Victor Stinnere838a932020-05-05 19:56:48 +0200949#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
950PyThreadState*
951_PyThreadState_GetTSS(void) {
952 return PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
953}
954#endif
955
956
Guido van Rossuma027efa1997-05-05 20:56:21 +0000957PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100958_PyThreadState_UncheckedGet(void)
959{
Victor Stinner50b48572018-11-01 01:51:40 +0100960 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100961}
962
963
964PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000965PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000966{
Victor Stinner50b48572018-11-01 01:51:40 +0100967 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200968 _Py_EnsureTstateNotNULL(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000970}
971
972
Victor Stinner09532fe2019-05-10 23:39:09 +0200973PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200974_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000975{
Victor Stinnere838a932020-05-05 19:56:48 +0200976#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
977 PyThreadState *oldts = _PyThreadState_GetTSS();
978#else
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200979 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Victor Stinnere838a932020-05-05 19:56:48 +0200980#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000981
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200982 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 /* It should not be possible for more than one thread state
984 to be used for a thread. Check this the best we can in debug
985 builds.
986 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200987#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 if (newts) {
989 /* This can be called from PyEval_RestoreThread(). Similar
990 to it, we need to ensure errno doesn't change.
991 */
992 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200993 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 if (check && check->interp == newts->interp && check != newts)
995 Py_FatalError("Invalid thread state for this thread");
996 errno = err;
997 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000998#endif
Victor Stinnere838a932020-05-05 19:56:48 +0200999#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1000 PyThread_tss_set(&gilstate->autoTSSkey, newts);
1001#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +00001003}
Guido van Rossumede04391998-04-10 20:18:25 +00001004
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001005PyThreadState *
1006PyThreadState_Swap(PyThreadState *newts)
1007{
1008 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
1009}
1010
Guido van Rossumede04391998-04-10 20:18:25 +00001011/* An extension mechanism to store arbitrary additional per-thread state.
1012 PyThreadState_GetDict() returns a dictionary that can be used to hold such
1013 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001014 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
1015 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +00001016
1017PyObject *
Victor Stinner0e427c62020-03-25 21:22:55 +01001018_PyThreadState_GetDict(PyThreadState *tstate)
1019{
1020 assert(tstate != NULL);
1021 if (tstate->dict == NULL) {
1022 tstate->dict = PyDict_New();
1023 if (tstate->dict == NULL) {
1024 _PyErr_Clear(tstate);
1025 }
1026 }
1027 return tstate->dict;
1028}
1029
1030
1031PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001032PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +00001033{
Victor Stinner50b48572018-11-01 01:51:40 +01001034 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner0e427c62020-03-25 21:22:55 +01001035 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 }
Victor Stinner0e427c62020-03-25 21:22:55 +01001038 return _PyThreadState_GetDict(tstate);
Guido van Rossumede04391998-04-10 20:18:25 +00001039}
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001040
1041
Victor Stinner8fb02b62020-03-13 23:38:08 +01001042PyInterpreterState *
1043PyThreadState_GetInterpreter(PyThreadState *tstate)
1044{
1045 assert(tstate != NULL);
Victor Stinner8fb02b62020-03-13 23:38:08 +01001046 return tstate->interp;
1047}
1048
1049
Victor Stinner4386b902020-04-29 03:01:43 +02001050PyFrameObject*
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001051PyThreadState_GetFrame(PyThreadState *tstate)
1052{
1053 assert(tstate != NULL);
Victor Stinner4386b902020-04-29 03:01:43 +02001054 PyFrameObject *frame = tstate->frame;
1055 Py_XINCREF(frame);
1056 return frame;
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001057}
1058
1059
Victor Stinner5c3cda02020-03-25 21:23:53 +01001060uint64_t
1061PyThreadState_GetID(PyThreadState *tstate)
1062{
1063 assert(tstate != NULL);
1064 return tstate->id;
1065}
1066
1067
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001068/* Asynchronously raise an exception in a thread.
1069 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001070 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001071 to call this, or use ctypes. Must be called with the GIL held.
1072 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1073 match any known thread id). Can be called with exc=NULL to clear an
1074 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001075
1076int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001077PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1078{
Victor Stinner09532fe2019-05-10 23:39:09 +02001079 _PyRuntimeState *runtime = &_PyRuntime;
1080 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 /* Although the GIL is held, a few C API functions can be called
1083 * without the GIL held, and in particular some that create and
1084 * destroy thread and interpreter states. Those can mutate the
1085 * list of thread states we're traversing, so to prevent that we lock
1086 * head_mutex for the duration.
1087 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001088 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001089 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1090 if (tstate->thread_id != id) {
1091 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001093
1094 /* Tricky: we need to decref the current value
1095 * (if any) in tstate->async_exc, but that can in turn
1096 * allow arbitrary Python code to run, including
1097 * perhaps calls to this function. To prevent
1098 * deadlock, we need to release head_mutex before
1099 * the decref.
1100 */
1101 PyObject *old_exc = tstate->async_exc;
1102 Py_XINCREF(exc);
1103 tstate->async_exc = exc;
1104 HEAD_UNLOCK(runtime);
1105
1106 Py_XDECREF(old_exc);
1107 _PyEval_SignalAsyncExc(tstate);
1108 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001110 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001112}
1113
1114
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001115/* Routines for advanced debuggers, requested by David Beazley.
1116 Don't use unless you know what you are doing! */
1117
1118PyInterpreterState *
1119PyInterpreterState_Head(void)
1120{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001121 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001122}
1123
1124PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001125PyInterpreterState_Main(void)
1126{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001127 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001128}
1129
1130PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001131PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001133}
1134
1135PyThreadState *
1136PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001138}
1139
1140PyThreadState *
1141PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001143}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001144
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001145/* The implementation of sys._current_frames(). This is intended to be
1146 called with the GIL held, as it will be when called via
1147 sys._current_frames(). It's possible it would work fine even without
1148 the GIL held, but haven't thought enough about that.
1149*/
1150PyObject *
1151_PyThread_CurrentFrames(void)
1152{
Victor Stinner71a35222020-03-26 22:46:14 +01001153 PyThreadState *tstate = _PyThreadState_GET();
1154 if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001155 return NULL;
1156 }
1157
Victor Stinner71a35222020-03-26 22:46:14 +01001158 PyObject *result = PyDict_New();
1159 if (result == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 return NULL;
Victor Stinner71a35222020-03-26 22:46:14 +01001161 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 /* for i in all interpreters:
1164 * for t in all of i's thread states:
1165 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001166 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 * need to grab head_mutex for the duration.
1168 */
Victor Stinner71a35222020-03-26 22:46:14 +01001169 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001170 HEAD_LOCK(runtime);
Victor Stinner71a35222020-03-26 22:46:14 +01001171 PyInterpreterState *i;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001172 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 PyThreadState *t;
1174 for (t = i->tstate_head; t != NULL; t = t->next) {
Victor Stinner4386b902020-04-29 03:01:43 +02001175 PyFrameObject *frame = t->frame;
Victor Stinner71a35222020-03-26 22:46:14 +01001176 if (frame == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 continue;
Victor Stinner71a35222020-03-26 22:46:14 +01001178 }
1179 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1180 if (id == NULL) {
1181 goto fail;
1182 }
1183 int stat = PyDict_SetItem(result, id, (PyObject *)frame);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 Py_DECREF(id);
Victor Stinner71a35222020-03-26 22:46:14 +01001185 if (stat < 0) {
1186 goto fail;
1187 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 }
1189 }
Victor Stinner71a35222020-03-26 22:46:14 +01001190 goto done;
1191
1192fail:
1193 Py_CLEAR(result);
1194
1195done:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001196 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001198}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001199
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001200/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001201
1202/* Keep this as a static, as it is not reliable! It can only
1203 ever be compared to the state for the *current* thread.
1204 * If not equal, then it doesn't matter that the actual
1205 value may change immediately after comparison, as it can't
1206 possibly change to the current thread's state.
1207 * If equal, then the current thread holds the lock, so the value can't
1208 change until we yield the lock.
1209*/
1210static int
1211PyThreadState_IsCurrent(PyThreadState *tstate)
1212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001214 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001215 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1216 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001217}
1218
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001219/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001220 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001221*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001222PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001223_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001224{
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001225 if (!_Py_IsMainInterpreter(tstate)) {
1226 /* Currently, PyGILState is shared by all interpreters. The main
1227 * interpreter is responsible to initialize it. */
1228 return _PyStatus_OK();
1229 }
1230
Victor Stinner8bb32302019-04-24 16:47:40 +02001231 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001232 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001233 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001234
Victor Stinner01b1cc12019-11-20 02:27:56 +01001235 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001236
1237 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001238 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001239 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001240 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001241 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1242 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001243
Victor Stinner8bb32302019-04-24 16:47:40 +02001244 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001245 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001246}
1247
Victor Stinner861d9ab2016-03-16 22:45:24 +01001248PyInterpreterState *
1249_PyGILState_GetInterpreterStateUnsafe(void)
1250{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001251 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001252}
1253
Tim Peters19717fa2004-10-09 17:38:29 +00001254void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001255_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001256{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001257 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001258 PyThread_tss_delete(&gilstate->autoTSSkey);
1259 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001260}
1261
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001262/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001263 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001264 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001265 */
1266void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001267_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001268{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001269 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001270 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001271
1272 PyThread_tss_delete(&gilstate->autoTSSkey);
1273 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001274 Py_FatalError("Could not allocate TSS entry");
1275 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001276
Charles-François Natalia233df82011-11-22 19:49:51 +01001277 /* If the thread had an associated auto thread state, reassociate it with
1278 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001279 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001280 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001281 {
1282 Py_FatalError("Couldn't create autoTSSkey mapping");
1283 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001284}
1285
Michael W. Hudson188d4362005-06-20 16:52:57 +00001286/* When a thread state is created for a thread by some mechanism other than
1287 PyGILState_Ensure, it's important that the GILState machinery knows about
1288 it so it doesn't try to create another thread state for the thread (this is
1289 a better fix for SF bug #1010677 than the first one attempted).
1290*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001291static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001292_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001293{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001294 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001295 threadstate created in Py_Initialize(). Don't do anything for now
1296 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001297 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001299 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001300
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001301 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 The only situation where you can legitimately have more than one
1304 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001305 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001306
Victor Stinner590cebe2013-12-13 11:08:56 +01001307 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1308 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001309
Victor Stinner590cebe2013-12-13 11:08:56 +01001310 The first thread state created for that given OS level thread will
1311 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001313 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1314 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001315 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001316 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001317 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 /* PyGILState_Release must not try to delete this thread state. */
1320 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001321}
1322
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001323/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001324static PyThreadState *
1325_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1326{
1327 if (gilstate->autoInterpreterState == NULL)
1328 return NULL;
1329 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1330}
1331
Tim Peters19717fa2004-10-09 17:38:29 +00001332PyThreadState *
1333PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001334{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001335 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001336}
1337
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001338int
1339PyGILState_Check(void)
1340{
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001341 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1342 if (!gilstate->check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001343 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001344 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001345
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001346 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1347 return 1;
1348 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001349
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001350 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1351 if (tstate == NULL) {
1352 return 0;
1353 }
1354
1355 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001356}
1357
Tim Peters19717fa2004-10-09 17:38:29 +00001358PyGILState_STATE
1359PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001360{
Victor Stinner175a7042020-03-10 00:37:48 +01001361 _PyRuntimeState *runtime = &_PyRuntime;
1362 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 /* Note that we do not auto-init Python here - apart from
1365 potential races with 2 threads auto-initializing, pep-311
1366 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001367 called Py_Initialize(). */
1368
1369 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1370 called by Py_Initialize() */
Victor Stinnere838a932020-05-05 19:56:48 +02001371#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinner175a7042020-03-10 00:37:48 +01001372 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinnere838a932020-05-05 19:56:48 +02001373#endif
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001374 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001375
Victor Stinner175a7042020-03-10 00:37:48 +01001376 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1377 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001379 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001380 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001381 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001383 }
1384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 /* This is our thread state! We'll need to delete it in the
1386 matching call to PyGILState_Release(). */
1387 tcur->gilstate_counter = 0;
1388 current = 0; /* new thread state is never current */
1389 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001390 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001392 }
1393
1394 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001396 }
1397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 /* Update our counter in the thread-state - no need for locks:
1399 - tcur will remain valid as we hold the GIL.
1400 - the counter is safe as we are the only thread "allowed"
1401 to modify this value
1402 */
1403 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001406}
1407
Tim Peters19717fa2004-10-09 17:38:29 +00001408void
1409PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001410{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001411 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001412 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1413 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 Py_FatalError("auto-releasing thread-state, "
1415 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001416 }
1417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 /* We must hold the GIL and have our thread state current */
1419 /* XXX - remove the check - the assert should be fine,
1420 but while this is very new (April 2003), the extra check
1421 by release-only users can't hurt.
1422 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001423 if (!PyThreadState_IsCurrent(tstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001424 _Py_FatalErrorFormat(__func__,
1425 "thread state %p must be current when releasing",
1426 tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001427 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001428 assert(PyThreadState_IsCurrent(tstate));
1429 --tstate->gilstate_counter;
1430 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 /* If we're going to destroy this thread-state, we must
1433 * clear it while the GIL is held, as destructors may run.
1434 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001435 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 /* can't have been locked when we created it */
1437 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001438 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 /* Delete the thread-state. Note this releases the GIL too!
1440 * It's vital that the GIL be held here, to avoid shutdown
1441 * races; see bugs 225673 and 1061968 (that nasty bug has a
1442 * habit of coming back).
1443 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001444 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1445 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 }
1447 /* Release the lock if necessary */
1448 else if (oldstate == PyGILState_UNLOCKED)
1449 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001450}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001451
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001452
Eric Snow7f8bfc92018-01-29 18:23:44 -07001453/**************************/
1454/* cross-interpreter data */
1455/**************************/
1456
1457/* cross-interpreter data */
1458
1459crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1460
1461/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1462 to keep the registry code separate. */
1463static crossinterpdatafunc
1464_lookup_getdata(PyObject *obj)
1465{
1466 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1467 if (getdata == NULL && PyErr_Occurred() == 0)
1468 PyErr_Format(PyExc_ValueError,
1469 "%S does not support cross-interpreter data", obj);
1470 return getdata;
1471}
1472
1473int
1474_PyObject_CheckCrossInterpreterData(PyObject *obj)
1475{
1476 crossinterpdatafunc getdata = _lookup_getdata(obj);
1477 if (getdata == NULL) {
1478 return -1;
1479 }
1480 return 0;
1481}
1482
1483static int
Victor Stinner71a35222020-03-26 22:46:14 +01001484_check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001485{
1486 // data->data can be anything, including NULL, so we don't check it.
1487
1488 // data->obj may be NULL, so we don't check it.
1489
1490 if (data->interp < 0) {
Victor Stinner71a35222020-03-26 22:46:14 +01001491 _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001492 return -1;
1493 }
1494
1495 if (data->new_object == NULL) {
Victor Stinner71a35222020-03-26 22:46:14 +01001496 _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001497 return -1;
1498 }
1499
1500 // data->free may be NULL, so we don't check it.
1501
1502 return 0;
1503}
1504
1505int
1506_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1507{
Victor Stinner71a35222020-03-26 22:46:14 +01001508 // PyThreadState_Get() aborts if tstate is NULL.
1509 PyThreadState *tstate = PyThreadState_Get();
1510 PyInterpreterState *interp = tstate->interp;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001511
1512 // Reset data before re-populating.
1513 *data = (_PyCrossInterpreterData){0};
1514 data->free = PyMem_RawFree; // Set a default that may be overridden.
1515
1516 // Call the "getdata" func for the object.
1517 Py_INCREF(obj);
1518 crossinterpdatafunc getdata = _lookup_getdata(obj);
1519 if (getdata == NULL) {
1520 Py_DECREF(obj);
1521 return -1;
1522 }
1523 int res = getdata(obj, data);
1524 Py_DECREF(obj);
1525 if (res != 0) {
1526 return -1;
1527 }
1528
1529 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001530 data->interp = interp->id;
Victor Stinner71a35222020-03-26 22:46:14 +01001531 if (_check_xidata(tstate, data) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001532 _PyCrossInterpreterData_Release(data);
1533 return -1;
1534 }
1535
1536 return 0;
1537}
1538
Victor Stinnere225beb2019-06-03 18:14:24 +02001539static void
Eric Snow63799132018-06-01 18:45:20 -06001540_release_xidata(void *arg)
1541{
1542 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1543 if (data->free != NULL) {
1544 data->free(data->data);
1545 }
1546 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001547}
1548
1549static void
1550_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1551 PyInterpreterState *interp,
1552 void (*func)(void *), void *arg)
1553{
1554 /* We would use Py_AddPendingCall() if it weren't specific to the
1555 * main interpreter (see bpo-33608). In the meantime we take a
1556 * naive approach.
1557 */
1558 PyThreadState *save_tstate = NULL;
1559 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1560 // XXX Using the "head" thread isn't strictly correct.
1561 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1562 // XXX Possible GILState issues?
1563 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1564 }
1565
1566 func(arg);
1567
1568 // Switch back.
1569 if (save_tstate != NULL) {
1570 _PyThreadState_Swap(gilstate, save_tstate);
1571 }
Eric Snow63799132018-06-01 18:45:20 -06001572}
1573
Eric Snow7f8bfc92018-01-29 18:23:44 -07001574void
1575_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1576{
1577 if (data->data == NULL && data->obj == NULL) {
1578 // Nothing to release!
1579 return;
1580 }
1581
Victor Stinnere225beb2019-06-03 18:14:24 +02001582 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001583 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1584 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001585 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001586 if (data->free != NULL) {
1587 // XXX Someone leaked some memory...
1588 }
1589 return;
1590 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001591
Eric Snow7f8bfc92018-01-29 18:23:44 -07001592 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001593 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1594 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001595}
1596
1597PyObject *
1598_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1599{
1600 return data->new_object(data);
1601}
1602
1603/* registry of {type -> crossinterpdatafunc} */
1604
1605/* For now we use a global registry of shareable classes. An
1606 alternative would be to add a tp_* slot for a class's
1607 crossinterpdatafunc. It would be simpler and more efficient. */
1608
1609static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001610_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1611 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001612{
1613 // Note that we effectively replace already registered classes
1614 // rather than failing.
1615 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1616 if (newhead == NULL)
1617 return -1;
1618 newhead->cls = cls;
1619 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001620 newhead->next = xidregistry->head;
1621 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001622 return 0;
1623}
1624
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001625static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001626
1627int
Eric Snowc11183c2019-03-15 16:35:46 -06001628_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001629 crossinterpdatafunc getdata)
1630{
1631 if (!PyType_Check(cls)) {
1632 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1633 return -1;
1634 }
1635 if (getdata == NULL) {
1636 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1637 return -1;
1638 }
1639
1640 // Make sure the class isn't ever deallocated.
1641 Py_INCREF((PyObject *)cls);
1642
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001643 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1644 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1645 if (xidregistry->head == NULL) {
1646 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001647 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001648 int res = _register_xidata(xidregistry, cls, getdata);
1649 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001650 return res;
1651}
1652
Eric Snow6d2cd902018-05-16 15:04:57 -04001653/* Cross-interpreter objects are looked up by exact match on the class.
1654 We can reassess this policy when we move from a global registry to a
1655 tp_* slot. */
1656
Eric Snow7f8bfc92018-01-29 18:23:44 -07001657crossinterpdatafunc
1658_PyCrossInterpreterData_Lookup(PyObject *obj)
1659{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001660 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001661 PyObject *cls = PyObject_Type(obj);
1662 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001663 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1664 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001665 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001666 _register_builtins_for_crossinterpreter_data(xidregistry);
1667 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001668 }
1669 for(; cur != NULL; cur = cur->next) {
1670 if (cur->cls == (PyTypeObject *)cls) {
1671 getdata = cur->getdata;
1672 break;
1673 }
1674 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001675 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001676 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001677 return getdata;
1678}
1679
1680/* cross-interpreter data for builtin types */
1681
Eric Snow6d2cd902018-05-16 15:04:57 -04001682struct _shared_bytes_data {
1683 char *bytes;
1684 Py_ssize_t len;
1685};
1686
Eric Snow7f8bfc92018-01-29 18:23:44 -07001687static PyObject *
1688_new_bytes_object(_PyCrossInterpreterData *data)
1689{
Eric Snow6d2cd902018-05-16 15:04:57 -04001690 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1691 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001692}
1693
1694static int
1695_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1696{
Eric Snow6d2cd902018-05-16 15:04:57 -04001697 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1698 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1699 return -1;
1700 }
1701 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001702 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001703 data->obj = obj; // Will be "released" (decref'ed) when data released.
1704 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001705 data->free = PyMem_Free;
1706 return 0;
1707}
1708
1709struct _shared_str_data {
1710 int kind;
1711 const void *buffer;
1712 Py_ssize_t len;
1713};
1714
1715static PyObject *
1716_new_str_object(_PyCrossInterpreterData *data)
1717{
1718 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1719 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1720}
1721
1722static int
1723_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1724{
1725 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1726 shared->kind = PyUnicode_KIND(obj);
1727 shared->buffer = PyUnicode_DATA(obj);
1728 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1729 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001730 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001731 data->obj = obj; // Will be "released" (decref'ed) when data released.
1732 data->new_object = _new_str_object;
1733 data->free = PyMem_Free;
1734 return 0;
1735}
1736
1737static PyObject *
1738_new_long_object(_PyCrossInterpreterData *data)
1739{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001740 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001741}
1742
1743static int
1744_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1745{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001746 /* Note that this means the size of shareable ints is bounded by
1747 * sys.maxsize. Hence on 32-bit architectures that is half the
1748 * size of maximum shareable ints on 64-bit.
1749 */
1750 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001751 if (value == -1 && PyErr_Occurred()) {
1752 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1753 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1754 }
1755 return -1;
1756 }
1757 data->data = (void *)value;
1758 data->obj = NULL;
1759 data->new_object = _new_long_object;
1760 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001761 return 0;
1762}
1763
1764static PyObject *
1765_new_none_object(_PyCrossInterpreterData *data)
1766{
1767 // XXX Singleton refcounts are problematic across interpreters...
1768 Py_INCREF(Py_None);
1769 return Py_None;
1770}
1771
1772static int
1773_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1774{
1775 data->data = NULL;
1776 // data->obj remains NULL
1777 data->new_object = _new_none_object;
1778 data->free = NULL; // There is nothing to free.
1779 return 0;
1780}
1781
1782static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001783_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001784{
1785 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001786 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001787 Py_FatalError("could not register None for cross-interpreter sharing");
1788 }
1789
Eric Snow6d2cd902018-05-16 15:04:57 -04001790 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001791 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001792 Py_FatalError("could not register int for cross-interpreter sharing");
1793 }
1794
Eric Snow7f8bfc92018-01-29 18:23:44 -07001795 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001796 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001797 Py_FatalError("could not register bytes for cross-interpreter sharing");
1798 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001799
1800 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001801 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001802 Py_FatalError("could not register str for cross-interpreter sharing");
1803 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001804}
1805
1806
Victor Stinner0b72b232020-03-12 23:18:39 +01001807_PyFrameEvalFunction
1808_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1809{
1810 return interp->eval_frame;
1811}
1812
1813
1814void
1815_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1816 _PyFrameEvalFunction eval_frame)
1817{
1818 interp->eval_frame = eval_frame;
1819}
1820
Victor Stinnerda7933e2020-04-13 03:04:28 +02001821
1822const PyConfig*
1823_PyInterpreterState_GetConfig(PyInterpreterState *interp)
1824{
1825 return &interp->config;
1826}
1827
1828
1829PyStatus
1830_PyInterpreterState_SetConfig(PyInterpreterState *interp,
1831 const PyConfig *config)
1832{
1833 return _PyConfig_Copy(&interp->config, config);
1834}
1835
1836
1837const PyConfig*
1838_Py_GetConfig(void)
1839{
1840 assert(PyGILState_Check());
1841 PyThreadState *tstate = _PyThreadState_GET();
1842 return _PyInterpreterState_GetConfig(tstate->interp);
1843}
1844
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001845#ifdef __cplusplus
1846}
1847#endif