blob: 119fe31a84ba12eae719058638e2998ff6b1fb52 [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
Victor Stinner23ef89d2020-03-18 02:26:04 +010042static void
43ensure_tstate_not_null(const char *func, PyThreadState *tstate)
44{
45 if (tstate == NULL) {
46 _Py_FatalErrorFunc(func,
47 "current thread state is NULL (released GIL?)");
48 }
49}
50
51
Victor Stinner10c8e6a2019-04-26 01:53:18 +020052/* Forward declarations */
53static PyThreadState *_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate);
Victor Stinner9da74302019-11-20 11:17:17 +010054static void _PyThreadState_Delete(PyThreadState *tstate, int check_current);
Victor Stinner10c8e6a2019-04-26 01:53:18 +020055
56
Victor Stinner331a6a52019-05-27 16:39:22 +020057static PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010058_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060059{
Steve Dowerb82e17e2019-05-23 08:45:22 -070060 /* We preserve the hook across init, because there is
61 currently no public API to set it between runtime
62 initialization and interpreter initialization. */
63 void *open_code_hook = runtime->open_code_hook;
64 void *open_code_userdata = runtime->open_code_userdata;
65 _Py_AuditHookEntry *audit_hook_head = runtime->audit_hook_head;
66
Eric Snow2ebc5ce2017-09-07 23:51:28 -060067 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010068
Steve Dowerb82e17e2019-05-23 08:45:22 -070069 runtime->open_code_hook = open_code_hook;
70 runtime->open_code_userdata = open_code_userdata;
71 runtime->audit_hook_head = audit_hook_head;
72
Victor Stinnerdab84232020-03-17 18:56:44 +010073 _PyEval_InitRuntimeState(&runtime->ceval);
Victor Stinner441b10c2019-09-28 04:28:35 +020074
Victor Stinner3c30a762019-10-01 10:56:37 +020075 PyPreConfig_InitPythonConfig(&runtime->preconfig);
Michael W. Hudson188d4362005-06-20 16:52:57 +000076
Eric Snow2ebc5ce2017-09-07 23:51:28 -060077 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080078
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090079 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
80 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081 Py_tss_t initial = Py_tss_NEEDS_INIT;
82 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000083
Eric Snow2ebc5ce2017-09-07 23:51:28 -060084 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080085 if (runtime->interpreters.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020086 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080087 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060088 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070089
90 runtime->xidregistry.mutex = PyThread_allocate_lock();
91 if (runtime->xidregistry.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020092 return _PyStatus_ERR("Can't initialize threads for cross-interpreter data registry");
Eric Snow7f8bfc92018-01-29 18:23:44 -070093 }
94
Eric Snow8479a342019-03-08 23:44:33 -070095 // Set it to the ID of the main thread of the main interpreter.
96 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070097
Victor Stinner331a6a52019-05-27 16:39:22 +020098 return _PyStatus_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060099}
Eric Snow05351c12017-09-05 21:43:08 -0700100
Victor Stinner331a6a52019-05-27 16:39:22 +0200101PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +0100102_PyRuntimeState_Init(_PyRuntimeState *runtime)
103{
104 /* Force default allocator, since _PyRuntimeState_Fini() must
105 use the same allocator than this function. */
106 PyMemAllocatorEx old_alloc;
107 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
108
Victor Stinner331a6a52019-05-27 16:39:22 +0200109 PyStatus status = _PyRuntimeState_Init_impl(runtime);
Victor Stinner5d39e042017-11-29 17:20:38 +0100110
111 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinner331a6a52019-05-27 16:39:22 +0200112 return status;
Victor Stinner5d39e042017-11-29 17:20:38 +0100113}
114
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600115void
116_PyRuntimeState_Fini(_PyRuntimeState *runtime)
117{
Victor Stinner5d39e042017-11-29 17:20:38 +0100118 /* Force the allocator used by _PyRuntimeState_Init(). */
119 PyMemAllocatorEx old_alloc;
120 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -0800121
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600122 if (runtime->interpreters.mutex != NULL) {
123 PyThread_free_lock(runtime->interpreters.mutex);
124 runtime->interpreters.mutex = NULL;
125 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800126
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100127 if (runtime->xidregistry.mutex != NULL) {
128 PyThread_free_lock(runtime->xidregistry.mutex);
129 runtime->xidregistry.mutex = NULL;
130 }
131
Victor Stinnerccb04422017-11-16 03:20:31 -0800132 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600133}
134
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900135#ifdef HAVE_FORK
Eric Snow8479a342019-03-08 23:44:33 -0700136/* This function is called from PyOS_AfterFork_Child to ensure that
137 * newly created child processes do not share locks with the parent.
138 */
139
140void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200141_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700142{
143 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200144 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700145
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200146 /* Force default allocator, since _PyRuntimeState_Fini() must
147 use the same allocator than this function. */
148 PyMemAllocatorEx old_alloc;
149 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
150
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900151 int interp_mutex = _PyThread_at_fork_reinit(&runtime->interpreters.mutex);
152 int main_interp_id_mutex = _PyThread_at_fork_reinit(&runtime->interpreters.main->id_mutex);
153 int xidregistry_mutex = _PyThread_at_fork_reinit(&runtime->xidregistry.mutex);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200154
155 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
156
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900157 if (interp_mutex < 0) {
Eric Snow8479a342019-03-08 23:44:33 -0700158 Py_FatalError("Can't initialize lock for runtime interpreters");
159 }
160
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900161 if (main_interp_id_mutex < 0) {
Eric Snow8479a342019-03-08 23:44:33 -0700162 Py_FatalError("Can't initialize ID lock for main interpreter");
163 }
164
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900165 if (xidregistry_mutex < 0) {
Eric Snow8479a342019-03-08 23:44:33 -0700166 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
167 }
168}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900169#endif
Eric Snow8479a342019-03-08 23:44:33 -0700170
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200171#define HEAD_LOCK(runtime) \
172 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
173#define HEAD_UNLOCK(runtime) \
174 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700175
Victor Stinner8bb32302019-04-24 16:47:40 +0200176/* Forward declaration */
177static void _PyGILState_NoteThreadState(
178 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000179
Victor Stinner331a6a52019-05-27 16:39:22 +0200180PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600181_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700182{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200183 struct pyinterpreters *interpreters = &runtime->interpreters;
184 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100185
186 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
187 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200188 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100189 /* Force default allocator, since _PyRuntimeState_Fini() must
190 use the same allocator than this function. */
191 PyMemAllocatorEx old_alloc;
192 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
193
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200194 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100195
196 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
197
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200198 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200199 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800200 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600201 }
Victor Stinner5d926472018-03-06 14:31:37 +0100202
Victor Stinner331a6a52019-05-27 16:39:22 +0200203 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700204}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000205
206PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000207PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000208{
Victor Stinner71a35222020-03-26 22:46:14 +0100209 PyThreadState *tstate = _PyThreadState_GET();
210 /* tstate is NULL when Py_InitializeFromConfig() calls
211 PyInterpreterState_New() to create the main interpreter. */
212 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_New", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700213 return NULL;
214 }
215
Andy Lester7668a8b2020-03-24 23:26:44 -0500216 PyInterpreterState *interp = PyMem_RawCalloc(1, sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100217 if (interp == NULL) {
218 return NULL;
219 }
220
Eric Snow4c6955e2018-02-16 18:53:40 -0700221 interp->id_refcount = -1;
Victor Stinner022be022019-05-22 23:58:50 +0200222
Victor Stinner71a35222020-03-26 22:46:14 +0100223 /* Don't get runtime from tstate since tstate can be NULL */
Victor Stinner01b1cc12019-11-20 02:27:56 +0100224 _PyRuntimeState *runtime = &_PyRuntime;
225 interp->runtime = runtime;
226
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200227 if (_PyEval_InitState(&interp->ceval) < 0) {
228 goto out_of_memory;
229 }
230
Victor Stinner72474072019-11-20 12:25:50 +0100231 _PyGC_InitState(&interp->gc);
Victor Stinner8462a492019-10-01 12:06:16 +0200232 PyConfig_InitPythonConfig(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200233
Victor Stinnerd4341102017-11-23 00:12:09 +0100234 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000235#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300236#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100237 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000238#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100239 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000240#endif
241#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000242
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200243 struct pyinterpreters *interpreters = &runtime->interpreters;
244
245 HEAD_LOCK(runtime);
246 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100247 /* overflow or Py_Initialize() not called! */
Victor Stinner71a35222020-03-26 22:46:14 +0100248 if (tstate != NULL) {
249 _PyErr_SetString(tstate, PyExc_RuntimeError,
250 "failed to get an interpreter ID");
251 }
Pablo Galindo95d630e2018-08-31 22:49:29 +0100252 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100253 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100254 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200255 else {
256 interp->id = interpreters->next_id;
257 interpreters->next_id += 1;
258 interp->next = interpreters->head;
259 if (interpreters->main == NULL) {
260 interpreters->main = interp;
261 }
262 interpreters->head = interp;
263 }
264 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000265
Pablo Galindo95d630e2018-08-31 22:49:29 +0100266 if (interp == NULL) {
267 return NULL;
268 }
269
Yury Selivanovf23746a2018-01-22 19:11:18 -0500270 interp->tstate_next_unique_id = 0;
271
Steve Dowerb82e17e2019-05-23 08:45:22 -0700272 interp->audit_hooks = NULL;
273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 return interp;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200275
276out_of_memory:
277 if (tstate != NULL) {
278 _PyErr_NoMemory(tstate);
279 }
280
281 PyMem_RawFree(interp);
282 return NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000283}
284
285
Victor Stinner01b1cc12019-11-20 02:27:56 +0100286void
287PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000288{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100289 _PyRuntimeState *runtime = interp->runtime;
290
Victor Stinner71a35222020-03-26 22:46:14 +0100291 /* Use the current Python thread state to call audit hooks,
292 not the current Python thread state of 'interp'. */
293 PyThreadState *tstate = _PyThreadState_GET();
294 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_Clear", NULL) < 0) {
295 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700296 }
297
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200298 HEAD_LOCK(runtime);
299 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200301 }
302 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700303
304 Py_CLEAR(interp->audit_hooks);
305
Victor Stinner331a6a52019-05-27 16:39:22 +0200306 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 Py_CLEAR(interp->codec_search_path);
308 Py_CLEAR(interp->codec_search_cache);
309 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700310 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 Py_CLEAR(interp->sysdict);
313 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200314 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400315 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300316 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600317 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200318#ifdef HAVE_FORK
319 Py_CLEAR(interp->before_forkers);
320 Py_CLEAR(interp->after_forkers_parent);
321 Py_CLEAR(interp->after_forkers_child);
322#endif
Victor Stinner7b3c2522020-03-07 00:24:23 +0100323 if (_PyRuntimeState_GetFinalizing(runtime) == NULL) {
Eric Snow86ea5812019-05-10 13:29:55 -0400324 _PyWarnings_Fini(interp);
325 }
Eric Snow5be45a62019-03-08 22:47:07 -0700326 // XXX Once we have one allocator per interpreter (i.e.
327 // per-interpreter GC) we must ensure that all of the interpreter's
328 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000329}
330
331
332static void
Victor Stinner9da74302019-11-20 11:17:17 +0100333zapthreads(PyInterpreterState *interp, int check_current)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000334{
Victor Stinner9da74302019-11-20 11:17:17 +0100335 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 /* No need to lock the mutex here because this should only happen
337 when the threads are all really dead (XXX famous last words). */
Victor Stinner9da74302019-11-20 11:17:17 +0100338 while ((tstate = interp->tstate_head) != NULL) {
339 _PyThreadState_Delete(tstate, check_current);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000341}
342
343
Victor Stinner01b1cc12019-11-20 02:27:56 +0100344void
345PyInterpreterState_Delete(PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200346{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100347 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200348 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner9da74302019-11-20 11:17:17 +0100349 zapthreads(interp, 0);
350
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200351 _PyEval_FiniState(&interp->ceval);
352
Victor Stinner9da74302019-11-20 11:17:17 +0100353 /* Delete current thread. After this, many C API calls become crashy. */
354 _PyThreadState_Swap(&runtime->gilstate, NULL);
355
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200356 HEAD_LOCK(runtime);
357 PyInterpreterState **p;
358 for (p = &interpreters->head; ; p = &(*p)->next) {
359 if (*p == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100360 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200361 }
362 if (*p == interp) {
363 break;
364 }
365 }
366 if (interp->tstate_head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100367 Py_FatalError("remaining threads");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200368 }
369 *p = interp->next;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200370
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200371 if (interpreters->main == interp) {
372 interpreters->main = NULL;
373 if (interpreters->head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100374 Py_FatalError("remaining subinterpreters");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200375 }
376 }
377 HEAD_UNLOCK(runtime);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200378
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200379 if (interp->id_mutex != NULL) {
380 PyThread_free_lock(interp->id_mutex);
381 }
382 PyMem_RawFree(interp);
383}
384
385
Eric Snow59032962018-09-14 14:17:20 -0700386/*
387 * Delete all interpreter states except the main interpreter. If there
388 * is a current interpreter state, it *must* be the main interpreter.
389 */
390void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200391_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700392{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200393 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200394 struct pyinterpreters *interpreters = &runtime->interpreters;
395
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200396 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200397 if (tstate != NULL && tstate->interp != interpreters->main) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100398 Py_FatalError("not main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700399 }
400
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200401 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200402 PyInterpreterState *interp = interpreters->head;
403 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100404 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200405 if (interp == interpreters->main) {
406 interpreters->main->next = NULL;
407 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100408 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700409 continue;
410 }
411
Victor Stinner01b1cc12019-11-20 02:27:56 +0100412 PyInterpreterState_Clear(interp); // XXX must activate?
Victor Stinner9da74302019-11-20 11:17:17 +0100413 zapthreads(interp, 1);
Eric Snow59032962018-09-14 14:17:20 -0700414 if (interp->id_mutex != NULL) {
415 PyThread_free_lock(interp->id_mutex);
416 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100417 PyInterpreterState *prev_interp = interp;
418 interp = interp->next;
419 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700420 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200421 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700422
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200423 if (interpreters->head == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100424 Py_FatalError("missing main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700425 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200426 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700427}
428
429
Victor Stinnercaba55b2018-08-03 15:33:52 +0200430PyInterpreterState *
Victor Stinnerbe793732020-03-13 18:15:33 +0100431PyInterpreterState_Get(void)
Victor Stinnercaba55b2018-08-03 15:33:52 +0200432{
Victor Stinner50b48572018-11-01 01:51:40 +0100433 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner23ef89d2020-03-18 02:26:04 +0100434 ensure_tstate_not_null(__func__, tstate);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200435 PyInterpreterState *interp = tstate->interp;
436 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100437 Py_FatalError("no current interpreter");
Victor Stinnercaba55b2018-08-03 15:33:52 +0200438 }
439 return interp;
440}
441
442
Eric Snowe3774162017-05-22 19:46:40 -0700443int64_t
444PyInterpreterState_GetID(PyInterpreterState *interp)
445{
446 if (interp == NULL) {
447 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
448 return -1;
449 }
450 return interp->id;
451}
452
453
Eric Snow5be45a62019-03-08 22:47:07 -0700454static PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200455interp_look_up_id(_PyRuntimeState *runtime, int64_t requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700456{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200457 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100458 while (interp != NULL) {
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200459 int64_t id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700460 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100461 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700462 }
463 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100464 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700465 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100466 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700467 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100468 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700469}
470
Eric Snow5be45a62019-03-08 22:47:07 -0700471PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200472_PyInterpreterState_LookUpID(int64_t requested_id)
Eric Snow5be45a62019-03-08 22:47:07 -0700473{
474 PyInterpreterState *interp = NULL;
475 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200476 _PyRuntimeState *runtime = &_PyRuntime;
477 HEAD_LOCK(runtime);
478 interp = interp_look_up_id(runtime, requested_id);
479 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700480 }
481 if (interp == NULL && !PyErr_Occurred()) {
482 PyErr_Format(PyExc_RuntimeError,
483 "unrecognized interpreter ID %lld", requested_id);
484 }
485 return interp;
486}
487
Eric Snow4c6955e2018-02-16 18:53:40 -0700488
489int
490_PyInterpreterState_IDInitref(PyInterpreterState *interp)
491{
492 if (interp->id_mutex != NULL) {
493 return 0;
494 }
495 interp->id_mutex = PyThread_allocate_lock();
496 if (interp->id_mutex == NULL) {
497 PyErr_SetString(PyExc_RuntimeError,
498 "failed to create init interpreter ID mutex");
499 return -1;
500 }
501 interp->id_refcount = 0;
502 return 0;
503}
504
505
506void
507_PyInterpreterState_IDIncref(PyInterpreterState *interp)
508{
509 if (interp->id_mutex == NULL) {
510 return;
511 }
512 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
513 interp->id_refcount += 1;
514 PyThread_release_lock(interp->id_mutex);
515}
516
517
518void
519_PyInterpreterState_IDDecref(PyInterpreterState *interp)
520{
521 if (interp->id_mutex == NULL) {
522 return;
523 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200524 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700525 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
526 assert(interp->id_refcount != 0);
527 interp->id_refcount -= 1;
528 int64_t refcount = interp->id_refcount;
529 PyThread_release_lock(interp->id_mutex);
530
Eric Snowc11183c2019-03-15 16:35:46 -0600531 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700532 // XXX Using the "head" thread isn't strictly correct.
533 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
534 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200535 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700536 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200537 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700538 }
539}
540
Eric Snowc11183c2019-03-15 16:35:46 -0600541int
542_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
543{
544 return interp->requires_idref;
545}
546
547void
548_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
549{
550 interp->requires_idref = required ? 1 : 0;
551}
552
Eric Snowc11183c2019-03-15 16:35:46 -0600553PyObject *
554_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
555{
556 if (interp->modules == NULL) {
557 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
558 return NULL;
559 }
560 return PyMapping_GetItemString(interp->modules, "__main__");
561}
562
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600563PyObject *
564PyInterpreterState_GetDict(PyInterpreterState *interp)
565{
566 if (interp->dict == NULL) {
567 interp->dict = PyDict_New();
568 if (interp->dict == NULL) {
569 PyErr_Clear();
570 }
571 }
572 /* Returning NULL means no per-interpreter dict is available. */
573 return interp->dict;
574}
575
Victor Stinner45b9be52010-03-03 23:28:07 +0000576static PyThreadState *
577new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000578{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100579 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200580 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200581 if (tstate == NULL) {
582 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000584
Victor Stinner8bb32302019-04-24 16:47:40 +0200585 tstate->interp = interp;
586
587 tstate->frame = NULL;
588 tstate->recursion_depth = 0;
589 tstate->overflowed = 0;
590 tstate->recursion_critical = 0;
591 tstate->stackcheck_counter = 0;
592 tstate->tracing = 0;
593 tstate->use_tracing = 0;
594 tstate->gilstate_counter = 0;
595 tstate->async_exc = NULL;
596 tstate->thread_id = PyThread_get_thread_ident();
597
598 tstate->dict = NULL;
599
600 tstate->curexc_type = NULL;
601 tstate->curexc_value = NULL;
602 tstate->curexc_traceback = NULL;
603
604 tstate->exc_state.exc_type = NULL;
605 tstate->exc_state.exc_value = NULL;
606 tstate->exc_state.exc_traceback = NULL;
607 tstate->exc_state.previous_item = NULL;
608 tstate->exc_info = &tstate->exc_state;
609
610 tstate->c_profilefunc = NULL;
611 tstate->c_tracefunc = NULL;
612 tstate->c_profileobj = NULL;
613 tstate->c_traceobj = NULL;
614
615 tstate->trash_delete_nesting = 0;
616 tstate->trash_delete_later = NULL;
617 tstate->on_delete = NULL;
618 tstate->on_delete_data = NULL;
619
620 tstate->coroutine_origin_tracking_depth = 0;
621
Victor Stinner8bb32302019-04-24 16:47:40 +0200622 tstate->async_gen_firstiter = NULL;
623 tstate->async_gen_finalizer = NULL;
624
625 tstate->context = NULL;
626 tstate->context_ver = 1;
627
Victor Stinner8bb32302019-04-24 16:47:40 +0200628 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100629 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200630 }
631
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200632 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100633 tstate->id = ++interp->tstate_next_unique_id;
Victor Stinner8bb32302019-04-24 16:47:40 +0200634 tstate->prev = NULL;
635 tstate->next = interp->tstate_head;
636 if (tstate->next)
637 tstate->next->prev = tstate;
638 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200639 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000642}
643
Victor Stinner45b9be52010-03-03 23:28:07 +0000644PyThreadState *
645PyThreadState_New(PyInterpreterState *interp)
646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000648}
649
650PyThreadState *
651_PyThreadState_Prealloc(PyInterpreterState *interp)
652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000654}
655
656void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100657_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000658{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100659 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000660}
661
Martin v. Löwis1a214512008-06-11 05:26:20 +0000662PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200663PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000664{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200665 Py_ssize_t index = module->m_base.m_index;
Victor Stinner81a7be32020-04-14 15:14:01 +0200666 PyInterpreterState *state = _PyInterpreterState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000668 if (module->m_slots) {
669 return NULL;
670 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 if (index == 0)
672 return NULL;
673 if (state->modules_by_index == NULL)
674 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200675 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 return NULL;
677 res = PyList_GET_ITEM(state->modules_by_index, index);
678 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000679}
680
681int
Victor Stinner82c83bd2019-11-22 18:52:27 +0100682_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000683{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300684 if (!def) {
Victor Stinner71a35222020-03-26 22:46:14 +0100685 assert(_PyErr_Occurred(tstate));
Berker Peksag4b7b5652016-08-22 18:05:56 +0300686 return -1;
687 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000688 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100689 _PyErr_SetString(tstate,
690 PyExc_SystemError,
691 "PyState_AddModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000692 return -1;
693 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100694
695 PyInterpreterState *interp = tstate->interp;
696 if (!interp->modules_by_index) {
697 interp->modules_by_index = PyList_New(0);
698 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100700 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100702
703 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
704 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100706 }
707 }
708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100710 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000712}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000713
Martin v. Löwis7800f752012-06-22 12:20:55 +0200714int
715PyState_AddModule(PyObject* module, struct PyModuleDef* def)
716{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200717 if (!def) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100718 Py_FatalError("module definition is NULL");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200719 return -1;
720 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100721
722 PyThreadState *tstate = _PyThreadState_GET();
723 PyInterpreterState *interp = tstate->interp;
724 Py_ssize_t index = def->m_base.m_index;
725 if (interp->modules_by_index &&
726 index < PyList_GET_SIZE(interp->modules_by_index) &&
727 module == PyList_GET_ITEM(interp->modules_by_index, index))
728 {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100729 _Py_FatalErrorFormat(__func__, "module %p already added", module);
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100730 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200731 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100732 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200733}
734
735int
736PyState_RemoveModule(struct PyModuleDef* def)
737{
Victor Stinner71a35222020-03-26 22:46:14 +0100738 PyThreadState *tstate = _PyThreadState_GET();
739 PyInterpreterState *interp = tstate->interp;
740
Nick Coghland5cacbb2015-05-23 22:24:10 +1000741 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100742 _PyErr_SetString(tstate,
743 PyExc_SystemError,
744 "PyState_RemoveModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000745 return -1;
746 }
Victor Stinner71a35222020-03-26 22:46:14 +0100747
748 Py_ssize_t index = def->m_base.m_index;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200749 if (index == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100750 Py_FatalError("invalid module index");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200751 }
Victor Stinner71a35222020-03-26 22:46:14 +0100752 if (interp->modules_by_index == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100753 Py_FatalError("Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200754 }
Victor Stinner71a35222020-03-26 22:46:14 +0100755 if (index > PyList_GET_SIZE(interp->modules_by_index)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100756 Py_FatalError("Module index out of bounds.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200757 }
Victor Stinner71a35222020-03-26 22:46:14 +0100758
Zackery Spytz2a893432018-12-05 00:14:00 -0700759 Py_INCREF(Py_None);
Victor Stinner71a35222020-03-26 22:46:14 +0100760 return PyList_SetItem(interp->modules_by_index, index, Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200761}
762
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200763/* Used by PyImport_Cleanup() */
Antoine Pitrou40322e62013-08-11 00:30:09 +0200764void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200765_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200766{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200767 if (!interp->modules_by_index) {
768 return;
769 }
770
771 Py_ssize_t i;
772 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
773 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
774 if (PyModule_Check(m)) {
775 /* cleanup the saved copy of module dicts */
776 PyModuleDef *md = PyModule_GetDef(m);
777 if (md) {
778 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200779 }
780 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200781 }
782
783 /* Setting modules_by_index to NULL could be dangerous, so we
784 clear the list instead. */
785 if (PyList_SetSlice(interp->modules_by_index,
786 0, PyList_GET_SIZE(interp->modules_by_index),
787 NULL)) {
788 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200789 }
790}
791
Guido van Rossuma027efa1997-05-05 20:56:21 +0000792void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000793PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000794{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200795 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200796
Victor Stinner5804f872020-03-24 16:32:26 +0100797 if (verbose && tstate->frame != NULL) {
798 /* bpo-20526: After the main thread calls
799 _PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
800 exit when trying to take the GIL. If a thread exit in the middle of
801 _PyEval_EvalFrameDefault(), tstate->frame is not reset to its
802 previous value. It is more likely with daemon threads, but it can
803 happen with regular threads if threading._shutdown() fails
804 (ex: interrupted by CTRL+C). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 fprintf(stderr,
806 "PyThreadState_Clear: warning: thread still has a frame\n");
Victor Stinner5804f872020-03-24 16:32:26 +0100807 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000808
Victor Stinner5804f872020-03-24 16:32:26 +0100809 /* Don't clear tstate->frame: it is a borrowed reference */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 Py_CLEAR(tstate->dict);
812 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 Py_CLEAR(tstate->curexc_type);
815 Py_CLEAR(tstate->curexc_value);
816 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000817
Mark Shannonae3087c2017-10-22 22:41:51 +0100818 Py_CLEAR(tstate->exc_state.exc_type);
819 Py_CLEAR(tstate->exc_state.exc_value);
820 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300821
Mark Shannonae3087c2017-10-22 22:41:51 +0100822 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200823 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100824 fprintf(stderr,
825 "PyThreadState_Clear: warning: thread still has a generator\n");
826 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 tstate->c_profilefunc = NULL;
829 tstate->c_tracefunc = NULL;
830 Py_CLEAR(tstate->c_profileobj);
831 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400832
Yury Selivanoveb636452016-09-08 22:01:51 -0700833 Py_CLEAR(tstate->async_gen_firstiter);
834 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500835
836 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100837
838 if (tstate->on_delete != NULL) {
839 tstate->on_delete(tstate->on_delete_data);
840 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000841}
842
843
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300844/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000845static void
Victor Stinner9da74302019-11-20 11:17:17 +0100846tstate_delete_common(PyThreadState *tstate,
847 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000848{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100849 ensure_tstate_not_null(__func__, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200850 PyInterpreterState *interp = tstate->interp;
851 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100852 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200853 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100854 _PyRuntimeState *runtime = interp->runtime;
855
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200856 HEAD_LOCK(runtime);
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100857 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200858 tstate->prev->next = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100859 }
860 else {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200861 interp->tstate_head = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100862 }
863 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200864 tstate->next->prev = tstate->prev;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100865 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200866 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100867
Victor Stinner9da74302019-11-20 11:17:17 +0100868 if (gilstate->autoInterpreterState &&
869 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
870 {
871 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
872 }
873}
874
875
876static void
877_PyThreadState_Delete(PyThreadState *tstate, int check_current)
878{
879 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
880 if (check_current) {
881 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100882 _Py_FatalErrorFormat(__func__, "tstate %p is still current", tstate);
Victor Stinner9da74302019-11-20 11:17:17 +0100883 }
884 }
885 tstate_delete_common(tstate, gilstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100886 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000887}
888
889
Victor Stinner01b1cc12019-11-20 02:27:56 +0100890void
891PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000892{
Victor Stinner9da74302019-11-20 11:17:17 +0100893 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200894}
895
896
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300897void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100898_PyThreadState_DeleteCurrent(PyThreadState *tstate)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200899{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100900 ensure_tstate_not_null(__func__, tstate);
901 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner9da74302019-11-20 11:17:17 +0100902 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200903 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100904 _PyEval_ReleaseLock(tstate);
905 PyMem_RawFree(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000906}
Guido van Rossum29757862001-01-23 01:46:06 +0000907
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300908void
909PyThreadState_DeleteCurrent(void)
910{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100911 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
912 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
913 _PyThreadState_DeleteCurrent(tstate);
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300914}
915
Guido van Rossum29757862001-01-23 01:46:06 +0000916
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200917/*
918 * Delete all thread states except the one passed as argument.
919 * Note that, if there is a current thread state, it *must* be the one
920 * passed as argument. Also, this won't touch any other interpreters
921 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000922 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200923 */
924void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200925_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200926{
927 PyInterpreterState *interp = tstate->interp;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100928
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200929 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200930 /* Remove all thread states, except tstate, from the linked list of
931 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200932 without holding the lock. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100933 PyThreadState *list = interp->tstate_head;
934 if (list == tstate) {
935 list = tstate->next;
936 }
937 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200938 tstate->prev->next = tstate->next;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100939 }
940 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200941 tstate->next->prev = tstate->prev;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100942 }
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200943 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200944 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200945 HEAD_UNLOCK(runtime);
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100946
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200947 /* Clear and deallocate all stale thread states. Even if this
948 executes Python code, we should be safe since it executes
949 in the current thread, not one of the stale threads. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100950 PyThreadState *p, *next;
951 for (p = list; p; p = next) {
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200952 next = p->next;
953 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200954 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200955 }
956}
957
958
Victor Stinnere838a932020-05-05 19:56:48 +0200959#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
960PyThreadState*
961_PyThreadState_GetTSS(void) {
962 return PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
963}
964#endif
965
966
Guido van Rossuma027efa1997-05-05 20:56:21 +0000967PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100968_PyThreadState_UncheckedGet(void)
969{
Victor Stinner50b48572018-11-01 01:51:40 +0100970 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100971}
972
973
974PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000975PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000976{
Victor Stinner50b48572018-11-01 01:51:40 +0100977 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner23ef89d2020-03-18 02:26:04 +0100978 ensure_tstate_not_null(__func__, tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000980}
981
982
Victor Stinner09532fe2019-05-10 23:39:09 +0200983PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200984_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000985{
Victor Stinnere838a932020-05-05 19:56:48 +0200986#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
987 PyThreadState *oldts = _PyThreadState_GetTSS();
988#else
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200989 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Victor Stinnere838a932020-05-05 19:56:48 +0200990#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000991
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200992 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 /* It should not be possible for more than one thread state
994 to be used for a thread. Check this the best we can in debug
995 builds.
996 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200997#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 if (newts) {
999 /* This can be called from PyEval_RestoreThread(). Similar
1000 to it, we need to ensure errno doesn't change.
1001 */
1002 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001003 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 if (check && check->interp == newts->interp && check != newts)
1005 Py_FatalError("Invalid thread state for this thread");
1006 errno = err;
1007 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001008#endif
Victor Stinnere838a932020-05-05 19:56:48 +02001009#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1010 PyThread_tss_set(&gilstate->autoTSSkey, newts);
1011#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +00001013}
Guido van Rossumede04391998-04-10 20:18:25 +00001014
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001015PyThreadState *
1016PyThreadState_Swap(PyThreadState *newts)
1017{
1018 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
1019}
1020
Guido van Rossumede04391998-04-10 20:18:25 +00001021/* An extension mechanism to store arbitrary additional per-thread state.
1022 PyThreadState_GetDict() returns a dictionary that can be used to hold such
1023 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001024 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
1025 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +00001026
1027PyObject *
Victor Stinner0e427c62020-03-25 21:22:55 +01001028_PyThreadState_GetDict(PyThreadState *tstate)
1029{
1030 assert(tstate != NULL);
1031 if (tstate->dict == NULL) {
1032 tstate->dict = PyDict_New();
1033 if (tstate->dict == NULL) {
1034 _PyErr_Clear(tstate);
1035 }
1036 }
1037 return tstate->dict;
1038}
1039
1040
1041PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001042PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +00001043{
Victor Stinner50b48572018-11-01 01:51:40 +01001044 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner0e427c62020-03-25 21:22:55 +01001045 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 }
Victor Stinner0e427c62020-03-25 21:22:55 +01001048 return _PyThreadState_GetDict(tstate);
Guido van Rossumede04391998-04-10 20:18:25 +00001049}
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001050
1051
Victor Stinner8fb02b62020-03-13 23:38:08 +01001052PyInterpreterState *
1053PyThreadState_GetInterpreter(PyThreadState *tstate)
1054{
1055 assert(tstate != NULL);
Victor Stinner8fb02b62020-03-13 23:38:08 +01001056 return tstate->interp;
1057}
1058
1059
Victor Stinner4386b902020-04-29 03:01:43 +02001060PyFrameObject*
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001061PyThreadState_GetFrame(PyThreadState *tstate)
1062{
1063 assert(tstate != NULL);
Victor Stinner4386b902020-04-29 03:01:43 +02001064 PyFrameObject *frame = tstate->frame;
1065 Py_XINCREF(frame);
1066 return frame;
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001067}
1068
1069
Victor Stinner5c3cda02020-03-25 21:23:53 +01001070uint64_t
1071PyThreadState_GetID(PyThreadState *tstate)
1072{
1073 assert(tstate != NULL);
1074 return tstate->id;
1075}
1076
1077
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001078/* Asynchronously raise an exception in a thread.
1079 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001080 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001081 to call this, or use ctypes. Must be called with the GIL held.
1082 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1083 match any known thread id). Can be called with exc=NULL to clear an
1084 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001085
1086int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001087PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1088{
Victor Stinner09532fe2019-05-10 23:39:09 +02001089 _PyRuntimeState *runtime = &_PyRuntime;
1090 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 /* Although the GIL is held, a few C API functions can be called
1093 * without the GIL held, and in particular some that create and
1094 * destroy thread and interpreter states. Those can mutate the
1095 * list of thread states we're traversing, so to prevent that we lock
1096 * head_mutex for the duration.
1097 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001098 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001099 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1100 if (tstate->thread_id != id) {
1101 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001103
1104 /* Tricky: we need to decref the current value
1105 * (if any) in tstate->async_exc, but that can in turn
1106 * allow arbitrary Python code to run, including
1107 * perhaps calls to this function. To prevent
1108 * deadlock, we need to release head_mutex before
1109 * the decref.
1110 */
1111 PyObject *old_exc = tstate->async_exc;
1112 Py_XINCREF(exc);
1113 tstate->async_exc = exc;
1114 HEAD_UNLOCK(runtime);
1115
1116 Py_XDECREF(old_exc);
1117 _PyEval_SignalAsyncExc(tstate);
1118 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001120 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001122}
1123
1124
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001125/* Routines for advanced debuggers, requested by David Beazley.
1126 Don't use unless you know what you are doing! */
1127
1128PyInterpreterState *
1129PyInterpreterState_Head(void)
1130{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001131 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001132}
1133
1134PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001135PyInterpreterState_Main(void)
1136{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001137 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001138}
1139
1140PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001141PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001143}
1144
1145PyThreadState *
1146PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001148}
1149
1150PyThreadState *
1151PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001153}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001154
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001155/* The implementation of sys._current_frames(). This is intended to be
1156 called with the GIL held, as it will be when called via
1157 sys._current_frames(). It's possible it would work fine even without
1158 the GIL held, but haven't thought enough about that.
1159*/
1160PyObject *
1161_PyThread_CurrentFrames(void)
1162{
Victor Stinner71a35222020-03-26 22:46:14 +01001163 PyThreadState *tstate = _PyThreadState_GET();
1164 if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001165 return NULL;
1166 }
1167
Victor Stinner71a35222020-03-26 22:46:14 +01001168 PyObject *result = PyDict_New();
1169 if (result == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 return NULL;
Victor Stinner71a35222020-03-26 22:46:14 +01001171 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 /* for i in all interpreters:
1174 * for t in all of i's thread states:
1175 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001176 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 * need to grab head_mutex for the duration.
1178 */
Victor Stinner71a35222020-03-26 22:46:14 +01001179 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001180 HEAD_LOCK(runtime);
Victor Stinner71a35222020-03-26 22:46:14 +01001181 PyInterpreterState *i;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001182 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 PyThreadState *t;
1184 for (t = i->tstate_head; t != NULL; t = t->next) {
Victor Stinner4386b902020-04-29 03:01:43 +02001185 PyFrameObject *frame = t->frame;
Victor Stinner71a35222020-03-26 22:46:14 +01001186 if (frame == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 continue;
Victor Stinner71a35222020-03-26 22:46:14 +01001188 }
1189 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1190 if (id == NULL) {
1191 goto fail;
1192 }
1193 int stat = PyDict_SetItem(result, id, (PyObject *)frame);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 Py_DECREF(id);
Victor Stinner71a35222020-03-26 22:46:14 +01001195 if (stat < 0) {
1196 goto fail;
1197 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 }
1199 }
Victor Stinner71a35222020-03-26 22:46:14 +01001200 goto done;
1201
1202fail:
1203 Py_CLEAR(result);
1204
1205done:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001206 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001208}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001209
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001210/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001211
1212/* Keep this as a static, as it is not reliable! It can only
1213 ever be compared to the state for the *current* thread.
1214 * If not equal, then it doesn't matter that the actual
1215 value may change immediately after comparison, as it can't
1216 possibly change to the current thread's state.
1217 * If equal, then the current thread holds the lock, so the value can't
1218 change until we yield the lock.
1219*/
1220static int
1221PyThreadState_IsCurrent(PyThreadState *tstate)
1222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001224 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001225 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1226 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001227}
1228
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001229/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001230 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001231*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001232PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001233_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001234{
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001235 if (!_Py_IsMainInterpreter(tstate)) {
1236 /* Currently, PyGILState is shared by all interpreters. The main
1237 * interpreter is responsible to initialize it. */
1238 return _PyStatus_OK();
1239 }
1240
Victor Stinner8bb32302019-04-24 16:47:40 +02001241 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001242 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001243 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001244
Victor Stinner01b1cc12019-11-20 02:27:56 +01001245 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001246
1247 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001248 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001249 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001250 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001251 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1252 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001253
Victor Stinner8bb32302019-04-24 16:47:40 +02001254 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001255 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001256}
1257
Victor Stinner861d9ab2016-03-16 22:45:24 +01001258PyInterpreterState *
1259_PyGILState_GetInterpreterStateUnsafe(void)
1260{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001261 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001262}
1263
Tim Peters19717fa2004-10-09 17:38:29 +00001264void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001265_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001266{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001267 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001268 PyThread_tss_delete(&gilstate->autoTSSkey);
1269 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001270}
1271
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001272/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001273 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001274 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001275 */
1276void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001277_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001278{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001279 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001280 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001281
1282 PyThread_tss_delete(&gilstate->autoTSSkey);
1283 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001284 Py_FatalError("Could not allocate TSS entry");
1285 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001286
Charles-François Natalia233df82011-11-22 19:49:51 +01001287 /* If the thread had an associated auto thread state, reassociate it with
1288 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001289 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001290 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001291 {
1292 Py_FatalError("Couldn't create autoTSSkey mapping");
1293 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001294}
1295
Michael W. Hudson188d4362005-06-20 16:52:57 +00001296/* When a thread state is created for a thread by some mechanism other than
1297 PyGILState_Ensure, it's important that the GILState machinery knows about
1298 it so it doesn't try to create another thread state for the thread (this is
1299 a better fix for SF bug #1010677 than the first one attempted).
1300*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001301static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001302_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001303{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001304 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001305 threadstate created in Py_Initialize(). Don't do anything for now
1306 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001307 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001309 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001310
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001311 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 The only situation where you can legitimately have more than one
1314 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001315 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001316
Victor Stinner590cebe2013-12-13 11:08:56 +01001317 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1318 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001319
Victor Stinner590cebe2013-12-13 11:08:56 +01001320 The first thread state created for that given OS level thread will
1321 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001323 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1324 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001325 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001326 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001327 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 /* PyGILState_Release must not try to delete this thread state. */
1330 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001331}
1332
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001333/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001334static PyThreadState *
1335_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1336{
1337 if (gilstate->autoInterpreterState == NULL)
1338 return NULL;
1339 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1340}
1341
Tim Peters19717fa2004-10-09 17:38:29 +00001342PyThreadState *
1343PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001344{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001345 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001346}
1347
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001348int
1349PyGILState_Check(void)
1350{
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001351 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1352 if (!gilstate->check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001353 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001354 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001355
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001356 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1357 return 1;
1358 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001359
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001360 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1361 if (tstate == NULL) {
1362 return 0;
1363 }
1364
1365 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001366}
1367
Tim Peters19717fa2004-10-09 17:38:29 +00001368PyGILState_STATE
1369PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001370{
Victor Stinner175a7042020-03-10 00:37:48 +01001371 _PyRuntimeState *runtime = &_PyRuntime;
1372 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 /* Note that we do not auto-init Python here - apart from
1375 potential races with 2 threads auto-initializing, pep-311
1376 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001377 called Py_Initialize(). */
1378
1379 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1380 called by Py_Initialize() */
Victor Stinnere838a932020-05-05 19:56:48 +02001381#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinner175a7042020-03-10 00:37:48 +01001382 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinnere838a932020-05-05 19:56:48 +02001383#endif
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001384 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001385
Victor Stinner175a7042020-03-10 00:37:48 +01001386 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1387 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001389 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001390 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001391 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001393 }
1394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 /* This is our thread state! We'll need to delete it in the
1396 matching call to PyGILState_Release(). */
1397 tcur->gilstate_counter = 0;
1398 current = 0; /* new thread state is never current */
1399 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001400 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001402 }
1403
1404 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001406 }
1407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 /* Update our counter in the thread-state - no need for locks:
1409 - tcur will remain valid as we hold the GIL.
1410 - the counter is safe as we are the only thread "allowed"
1411 to modify this value
1412 */
1413 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001416}
1417
Tim Peters19717fa2004-10-09 17:38:29 +00001418void
1419PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001420{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001421 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001422 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1423 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 Py_FatalError("auto-releasing thread-state, "
1425 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001426 }
1427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 /* We must hold the GIL and have our thread state current */
1429 /* XXX - remove the check - the assert should be fine,
1430 but while this is very new (April 2003), the extra check
1431 by release-only users can't hurt.
1432 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001433 if (!PyThreadState_IsCurrent(tstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001434 _Py_FatalErrorFormat(__func__,
1435 "thread state %p must be current when releasing",
1436 tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001437 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001438 assert(PyThreadState_IsCurrent(tstate));
1439 --tstate->gilstate_counter;
1440 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 /* If we're going to destroy this thread-state, we must
1443 * clear it while the GIL is held, as destructors may run.
1444 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001445 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 /* can't have been locked when we created it */
1447 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001448 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 /* Delete the thread-state. Note this releases the GIL too!
1450 * It's vital that the GIL be held here, to avoid shutdown
1451 * races; see bugs 225673 and 1061968 (that nasty bug has a
1452 * habit of coming back).
1453 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001454 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1455 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 }
1457 /* Release the lock if necessary */
1458 else if (oldstate == PyGILState_UNLOCKED)
1459 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001460}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001461
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001462
Eric Snow7f8bfc92018-01-29 18:23:44 -07001463/**************************/
1464/* cross-interpreter data */
1465/**************************/
1466
1467/* cross-interpreter data */
1468
1469crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1470
1471/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1472 to keep the registry code separate. */
1473static crossinterpdatafunc
1474_lookup_getdata(PyObject *obj)
1475{
1476 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1477 if (getdata == NULL && PyErr_Occurred() == 0)
1478 PyErr_Format(PyExc_ValueError,
1479 "%S does not support cross-interpreter data", obj);
1480 return getdata;
1481}
1482
1483int
1484_PyObject_CheckCrossInterpreterData(PyObject *obj)
1485{
1486 crossinterpdatafunc getdata = _lookup_getdata(obj);
1487 if (getdata == NULL) {
1488 return -1;
1489 }
1490 return 0;
1491}
1492
1493static int
Victor Stinner71a35222020-03-26 22:46:14 +01001494_check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001495{
1496 // data->data can be anything, including NULL, so we don't check it.
1497
1498 // data->obj may be NULL, so we don't check it.
1499
1500 if (data->interp < 0) {
Victor Stinner71a35222020-03-26 22:46:14 +01001501 _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001502 return -1;
1503 }
1504
1505 if (data->new_object == NULL) {
Victor Stinner71a35222020-03-26 22:46:14 +01001506 _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001507 return -1;
1508 }
1509
1510 // data->free may be NULL, so we don't check it.
1511
1512 return 0;
1513}
1514
1515int
1516_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1517{
Victor Stinner71a35222020-03-26 22:46:14 +01001518 // PyThreadState_Get() aborts if tstate is NULL.
1519 PyThreadState *tstate = PyThreadState_Get();
1520 PyInterpreterState *interp = tstate->interp;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001521
1522 // Reset data before re-populating.
1523 *data = (_PyCrossInterpreterData){0};
1524 data->free = PyMem_RawFree; // Set a default that may be overridden.
1525
1526 // Call the "getdata" func for the object.
1527 Py_INCREF(obj);
1528 crossinterpdatafunc getdata = _lookup_getdata(obj);
1529 if (getdata == NULL) {
1530 Py_DECREF(obj);
1531 return -1;
1532 }
1533 int res = getdata(obj, data);
1534 Py_DECREF(obj);
1535 if (res != 0) {
1536 return -1;
1537 }
1538
1539 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001540 data->interp = interp->id;
Victor Stinner71a35222020-03-26 22:46:14 +01001541 if (_check_xidata(tstate, data) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001542 _PyCrossInterpreterData_Release(data);
1543 return -1;
1544 }
1545
1546 return 0;
1547}
1548
Victor Stinnere225beb2019-06-03 18:14:24 +02001549static void
Eric Snow63799132018-06-01 18:45:20 -06001550_release_xidata(void *arg)
1551{
1552 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1553 if (data->free != NULL) {
1554 data->free(data->data);
1555 }
1556 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001557}
1558
1559static void
1560_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1561 PyInterpreterState *interp,
1562 void (*func)(void *), void *arg)
1563{
1564 /* We would use Py_AddPendingCall() if it weren't specific to the
1565 * main interpreter (see bpo-33608). In the meantime we take a
1566 * naive approach.
1567 */
1568 PyThreadState *save_tstate = NULL;
1569 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1570 // XXX Using the "head" thread isn't strictly correct.
1571 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1572 // XXX Possible GILState issues?
1573 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1574 }
1575
1576 func(arg);
1577
1578 // Switch back.
1579 if (save_tstate != NULL) {
1580 _PyThreadState_Swap(gilstate, save_tstate);
1581 }
Eric Snow63799132018-06-01 18:45:20 -06001582}
1583
Eric Snow7f8bfc92018-01-29 18:23:44 -07001584void
1585_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1586{
1587 if (data->data == NULL && data->obj == NULL) {
1588 // Nothing to release!
1589 return;
1590 }
1591
Victor Stinnere225beb2019-06-03 18:14:24 +02001592 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001593 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1594 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001595 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001596 if (data->free != NULL) {
1597 // XXX Someone leaked some memory...
1598 }
1599 return;
1600 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001601
Eric Snow7f8bfc92018-01-29 18:23:44 -07001602 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001603 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1604 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001605}
1606
1607PyObject *
1608_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1609{
1610 return data->new_object(data);
1611}
1612
1613/* registry of {type -> crossinterpdatafunc} */
1614
1615/* For now we use a global registry of shareable classes. An
1616 alternative would be to add a tp_* slot for a class's
1617 crossinterpdatafunc. It would be simpler and more efficient. */
1618
1619static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001620_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1621 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001622{
1623 // Note that we effectively replace already registered classes
1624 // rather than failing.
1625 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1626 if (newhead == NULL)
1627 return -1;
1628 newhead->cls = cls;
1629 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001630 newhead->next = xidregistry->head;
1631 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001632 return 0;
1633}
1634
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001635static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001636
1637int
Eric Snowc11183c2019-03-15 16:35:46 -06001638_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001639 crossinterpdatafunc getdata)
1640{
1641 if (!PyType_Check(cls)) {
1642 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1643 return -1;
1644 }
1645 if (getdata == NULL) {
1646 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1647 return -1;
1648 }
1649
1650 // Make sure the class isn't ever deallocated.
1651 Py_INCREF((PyObject *)cls);
1652
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001653 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1654 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1655 if (xidregistry->head == NULL) {
1656 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001657 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001658 int res = _register_xidata(xidregistry, cls, getdata);
1659 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001660 return res;
1661}
1662
Eric Snow6d2cd902018-05-16 15:04:57 -04001663/* Cross-interpreter objects are looked up by exact match on the class.
1664 We can reassess this policy when we move from a global registry to a
1665 tp_* slot. */
1666
Eric Snow7f8bfc92018-01-29 18:23:44 -07001667crossinterpdatafunc
1668_PyCrossInterpreterData_Lookup(PyObject *obj)
1669{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001670 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001671 PyObject *cls = PyObject_Type(obj);
1672 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001673 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1674 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001675 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001676 _register_builtins_for_crossinterpreter_data(xidregistry);
1677 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001678 }
1679 for(; cur != NULL; cur = cur->next) {
1680 if (cur->cls == (PyTypeObject *)cls) {
1681 getdata = cur->getdata;
1682 break;
1683 }
1684 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001685 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001686 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001687 return getdata;
1688}
1689
1690/* cross-interpreter data for builtin types */
1691
Eric Snow6d2cd902018-05-16 15:04:57 -04001692struct _shared_bytes_data {
1693 char *bytes;
1694 Py_ssize_t len;
1695};
1696
Eric Snow7f8bfc92018-01-29 18:23:44 -07001697static PyObject *
1698_new_bytes_object(_PyCrossInterpreterData *data)
1699{
Eric Snow6d2cd902018-05-16 15:04:57 -04001700 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1701 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001702}
1703
1704static int
1705_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1706{
Eric Snow6d2cd902018-05-16 15:04:57 -04001707 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1708 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1709 return -1;
1710 }
1711 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001712 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001713 data->obj = obj; // Will be "released" (decref'ed) when data released.
1714 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001715 data->free = PyMem_Free;
1716 return 0;
1717}
1718
1719struct _shared_str_data {
1720 int kind;
1721 const void *buffer;
1722 Py_ssize_t len;
1723};
1724
1725static PyObject *
1726_new_str_object(_PyCrossInterpreterData *data)
1727{
1728 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1729 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1730}
1731
1732static int
1733_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1734{
1735 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1736 shared->kind = PyUnicode_KIND(obj);
1737 shared->buffer = PyUnicode_DATA(obj);
1738 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1739 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001740 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001741 data->obj = obj; // Will be "released" (decref'ed) when data released.
1742 data->new_object = _new_str_object;
1743 data->free = PyMem_Free;
1744 return 0;
1745}
1746
1747static PyObject *
1748_new_long_object(_PyCrossInterpreterData *data)
1749{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001750 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001751}
1752
1753static int
1754_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1755{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001756 /* Note that this means the size of shareable ints is bounded by
1757 * sys.maxsize. Hence on 32-bit architectures that is half the
1758 * size of maximum shareable ints on 64-bit.
1759 */
1760 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001761 if (value == -1 && PyErr_Occurred()) {
1762 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1763 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1764 }
1765 return -1;
1766 }
1767 data->data = (void *)value;
1768 data->obj = NULL;
1769 data->new_object = _new_long_object;
1770 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001771 return 0;
1772}
1773
1774static PyObject *
1775_new_none_object(_PyCrossInterpreterData *data)
1776{
1777 // XXX Singleton refcounts are problematic across interpreters...
1778 Py_INCREF(Py_None);
1779 return Py_None;
1780}
1781
1782static int
1783_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1784{
1785 data->data = NULL;
1786 // data->obj remains NULL
1787 data->new_object = _new_none_object;
1788 data->free = NULL; // There is nothing to free.
1789 return 0;
1790}
1791
1792static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001793_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001794{
1795 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001796 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001797 Py_FatalError("could not register None for cross-interpreter sharing");
1798 }
1799
Eric Snow6d2cd902018-05-16 15:04:57 -04001800 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001801 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001802 Py_FatalError("could not register int for cross-interpreter sharing");
1803 }
1804
Eric Snow7f8bfc92018-01-29 18:23:44 -07001805 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001806 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001807 Py_FatalError("could not register bytes for cross-interpreter sharing");
1808 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001809
1810 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001811 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001812 Py_FatalError("could not register str for cross-interpreter sharing");
1813 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001814}
1815
1816
Victor Stinner0b72b232020-03-12 23:18:39 +01001817_PyFrameEvalFunction
1818_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1819{
1820 return interp->eval_frame;
1821}
1822
1823
1824void
1825_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1826 _PyFrameEvalFunction eval_frame)
1827{
1828 interp->eval_frame = eval_frame;
1829}
1830
Victor Stinnerda7933e2020-04-13 03:04:28 +02001831
1832const PyConfig*
1833_PyInterpreterState_GetConfig(PyInterpreterState *interp)
1834{
1835 return &interp->config;
1836}
1837
1838
1839PyStatus
1840_PyInterpreterState_SetConfig(PyInterpreterState *interp,
1841 const PyConfig *config)
1842{
1843 return _PyConfig_Copy(&interp->config, config);
1844}
1845
1846
1847const PyConfig*
1848_Py_GetConfig(void)
1849{
1850 assert(PyGILState_Check());
1851 PyThreadState *tstate = _PyThreadState_GET();
1852 return _PyInterpreterState_GetConfig(tstate->interp);
1853}
1854
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001855#ifdef __cplusplus
1856}
1857#endif