blob: dd95750027241b8522509f4bbc3c743e0666e3df [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
Guido van Rossuma027efa1997-05-05 20:56:21 +0000959PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100960_PyThreadState_UncheckedGet(void)
961{
Victor Stinner50b48572018-11-01 01:51:40 +0100962 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100963}
964
965
966PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000967PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000968{
Victor Stinner50b48572018-11-01 01:51:40 +0100969 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner23ef89d2020-03-18 02:26:04 +0100970 ensure_tstate_not_null(__func__, tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000972}
973
974
Victor Stinner09532fe2019-05-10 23:39:09 +0200975PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200976_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000977{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200978 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000979
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200980 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 /* It should not be possible for more than one thread state
982 to be used for a thread. Check this the best we can in debug
983 builds.
984 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200985#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (newts) {
987 /* This can be called from PyEval_RestoreThread(). Similar
988 to it, we need to ensure errno doesn't change.
989 */
990 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200991 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 if (check && check->interp == newts->interp && check != newts)
993 Py_FatalError("Invalid thread state for this thread");
994 errno = err;
995 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000996#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000998}
Guido van Rossumede04391998-04-10 20:18:25 +0000999
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001000PyThreadState *
1001PyThreadState_Swap(PyThreadState *newts)
1002{
1003 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
1004}
1005
Guido van Rossumede04391998-04-10 20:18:25 +00001006/* An extension mechanism to store arbitrary additional per-thread state.
1007 PyThreadState_GetDict() returns a dictionary that can be used to hold such
1008 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001009 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
1010 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +00001011
1012PyObject *
Victor Stinner0e427c62020-03-25 21:22:55 +01001013_PyThreadState_GetDict(PyThreadState *tstate)
1014{
1015 assert(tstate != NULL);
1016 if (tstate->dict == NULL) {
1017 tstate->dict = PyDict_New();
1018 if (tstate->dict == NULL) {
1019 _PyErr_Clear(tstate);
1020 }
1021 }
1022 return tstate->dict;
1023}
1024
1025
1026PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001027PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +00001028{
Victor Stinner50b48572018-11-01 01:51:40 +01001029 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner0e427c62020-03-25 21:22:55 +01001030 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 }
Victor Stinner0e427c62020-03-25 21:22:55 +01001033 return _PyThreadState_GetDict(tstate);
Guido van Rossumede04391998-04-10 20:18:25 +00001034}
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001035
1036
Victor Stinner8fb02b62020-03-13 23:38:08 +01001037PyInterpreterState *
1038PyThreadState_GetInterpreter(PyThreadState *tstate)
1039{
1040 assert(tstate != NULL);
Victor Stinner8fb02b62020-03-13 23:38:08 +01001041 return tstate->interp;
1042}
1043
1044
Victor Stinner4386b902020-04-29 03:01:43 +02001045PyFrameObject*
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001046PyThreadState_GetFrame(PyThreadState *tstate)
1047{
1048 assert(tstate != NULL);
Victor Stinner4386b902020-04-29 03:01:43 +02001049 PyFrameObject *frame = tstate->frame;
1050 Py_XINCREF(frame);
1051 return frame;
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001052}
1053
1054
Victor Stinner5c3cda02020-03-25 21:23:53 +01001055uint64_t
1056PyThreadState_GetID(PyThreadState *tstate)
1057{
1058 assert(tstate != NULL);
1059 return tstate->id;
1060}
1061
1062
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001063/* Asynchronously raise an exception in a thread.
1064 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001065 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001066 to call this, or use ctypes. Must be called with the GIL held.
1067 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1068 match any known thread id). Can be called with exc=NULL to clear an
1069 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001070
1071int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001072PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1073{
Victor Stinner09532fe2019-05-10 23:39:09 +02001074 _PyRuntimeState *runtime = &_PyRuntime;
1075 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 /* Although the GIL is held, a few C API functions can be called
1078 * without the GIL held, and in particular some that create and
1079 * destroy thread and interpreter states. Those can mutate the
1080 * list of thread states we're traversing, so to prevent that we lock
1081 * head_mutex for the duration.
1082 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001083 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001084 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1085 if (tstate->thread_id != id) {
1086 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001088
1089 /* Tricky: we need to decref the current value
1090 * (if any) in tstate->async_exc, but that can in turn
1091 * allow arbitrary Python code to run, including
1092 * perhaps calls to this function. To prevent
1093 * deadlock, we need to release head_mutex before
1094 * the decref.
1095 */
1096 PyObject *old_exc = tstate->async_exc;
1097 Py_XINCREF(exc);
1098 tstate->async_exc = exc;
1099 HEAD_UNLOCK(runtime);
1100
1101 Py_XDECREF(old_exc);
1102 _PyEval_SignalAsyncExc(tstate);
1103 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001105 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001107}
1108
1109
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001110/* Routines for advanced debuggers, requested by David Beazley.
1111 Don't use unless you know what you are doing! */
1112
1113PyInterpreterState *
1114PyInterpreterState_Head(void)
1115{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001116 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001117}
1118
1119PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001120PyInterpreterState_Main(void)
1121{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001122 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001123}
1124
1125PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001126PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001128}
1129
1130PyThreadState *
1131PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001133}
1134
1135PyThreadState *
1136PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001138}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001139
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001140/* The implementation of sys._current_frames(). This is intended to be
1141 called with the GIL held, as it will be when called via
1142 sys._current_frames(). It's possible it would work fine even without
1143 the GIL held, but haven't thought enough about that.
1144*/
1145PyObject *
1146_PyThread_CurrentFrames(void)
1147{
Victor Stinner71a35222020-03-26 22:46:14 +01001148 PyThreadState *tstate = _PyThreadState_GET();
1149 if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001150 return NULL;
1151 }
1152
Victor Stinner71a35222020-03-26 22:46:14 +01001153 PyObject *result = PyDict_New();
1154 if (result == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 return NULL;
Victor Stinner71a35222020-03-26 22:46:14 +01001156 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 /* for i in all interpreters:
1159 * for t in all of i's thread states:
1160 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001161 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 * need to grab head_mutex for the duration.
1163 */
Victor Stinner71a35222020-03-26 22:46:14 +01001164 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001165 HEAD_LOCK(runtime);
Victor Stinner71a35222020-03-26 22:46:14 +01001166 PyInterpreterState *i;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001167 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 PyThreadState *t;
1169 for (t = i->tstate_head; t != NULL; t = t->next) {
Victor Stinner4386b902020-04-29 03:01:43 +02001170 PyFrameObject *frame = t->frame;
Victor Stinner71a35222020-03-26 22:46:14 +01001171 if (frame == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 continue;
Victor Stinner71a35222020-03-26 22:46:14 +01001173 }
1174 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1175 if (id == NULL) {
1176 goto fail;
1177 }
1178 int stat = PyDict_SetItem(result, id, (PyObject *)frame);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 Py_DECREF(id);
Victor Stinner71a35222020-03-26 22:46:14 +01001180 if (stat < 0) {
1181 goto fail;
1182 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 }
1184 }
Victor Stinner71a35222020-03-26 22:46:14 +01001185 goto done;
1186
1187fail:
1188 Py_CLEAR(result);
1189
1190done:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001191 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001193}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001194
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001195/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001196
1197/* Keep this as a static, as it is not reliable! It can only
1198 ever be compared to the state for the *current* thread.
1199 * If not equal, then it doesn't matter that the actual
1200 value may change immediately after comparison, as it can't
1201 possibly change to the current thread's state.
1202 * If equal, then the current thread holds the lock, so the value can't
1203 change until we yield the lock.
1204*/
1205static int
1206PyThreadState_IsCurrent(PyThreadState *tstate)
1207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001209 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001210 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1211 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001212}
1213
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001214/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001215 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001216*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001217PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001218_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001219{
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001220 if (!_Py_IsMainInterpreter(tstate)) {
1221 /* Currently, PyGILState is shared by all interpreters. The main
1222 * interpreter is responsible to initialize it. */
1223 return _PyStatus_OK();
1224 }
1225
Victor Stinner8bb32302019-04-24 16:47:40 +02001226 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001227 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001228 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001229
Victor Stinner01b1cc12019-11-20 02:27:56 +01001230 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001231
1232 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001233 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001234 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001235 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001236 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1237 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001238
Victor Stinner8bb32302019-04-24 16:47:40 +02001239 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001240 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001241}
1242
Victor Stinner861d9ab2016-03-16 22:45:24 +01001243PyInterpreterState *
1244_PyGILState_GetInterpreterStateUnsafe(void)
1245{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001246 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001247}
1248
Tim Peters19717fa2004-10-09 17:38:29 +00001249void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001250_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001251{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001252 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001253 PyThread_tss_delete(&gilstate->autoTSSkey);
1254 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001255}
1256
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001257/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001258 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001259 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001260 */
1261void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001262_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001263{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001264 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001265 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001266
1267 PyThread_tss_delete(&gilstate->autoTSSkey);
1268 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001269 Py_FatalError("Could not allocate TSS entry");
1270 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001271
Charles-François Natalia233df82011-11-22 19:49:51 +01001272 /* If the thread had an associated auto thread state, reassociate it with
1273 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001274 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001275 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001276 {
1277 Py_FatalError("Couldn't create autoTSSkey mapping");
1278 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001279}
1280
Michael W. Hudson188d4362005-06-20 16:52:57 +00001281/* When a thread state is created for a thread by some mechanism other than
1282 PyGILState_Ensure, it's important that the GILState machinery knows about
1283 it so it doesn't try to create another thread state for the thread (this is
1284 a better fix for SF bug #1010677 than the first one attempted).
1285*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001286static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001287_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001288{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001289 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001290 threadstate created in Py_Initialize(). Don't do anything for now
1291 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001292 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001294 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001295
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001296 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 The only situation where you can legitimately have more than one
1299 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001300 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001301
Victor Stinner590cebe2013-12-13 11:08:56 +01001302 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1303 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001304
Victor Stinner590cebe2013-12-13 11:08:56 +01001305 The first thread state created for that given OS level thread will
1306 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001308 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1309 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001310 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001311 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001312 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 /* PyGILState_Release must not try to delete this thread state. */
1315 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001316}
1317
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001318/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001319static PyThreadState *
1320_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1321{
1322 if (gilstate->autoInterpreterState == NULL)
1323 return NULL;
1324 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1325}
1326
Tim Peters19717fa2004-10-09 17:38:29 +00001327PyThreadState *
1328PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001329{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001330 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001331}
1332
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001333int
1334PyGILState_Check(void)
1335{
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001336 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1337 if (!gilstate->check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001338 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001339 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001340
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001341 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1342 return 1;
1343 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001344
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001345 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1346 if (tstate == NULL) {
1347 return 0;
1348 }
1349
1350 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001351}
1352
Tim Peters19717fa2004-10-09 17:38:29 +00001353PyGILState_STATE
1354PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001355{
Victor Stinner175a7042020-03-10 00:37:48 +01001356 _PyRuntimeState *runtime = &_PyRuntime;
1357 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 /* Note that we do not auto-init Python here - apart from
1360 potential races with 2 threads auto-initializing, pep-311
1361 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001362 called Py_Initialize(). */
1363
1364 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1365 called by Py_Initialize() */
1366 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001367 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001368
Victor Stinner175a7042020-03-10 00:37:48 +01001369 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1370 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001372 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001373 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001374 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001376 }
1377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 /* This is our thread state! We'll need to delete it in the
1379 matching call to PyGILState_Release(). */
1380 tcur->gilstate_counter = 0;
1381 current = 0; /* new thread state is never current */
1382 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001383 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001385 }
1386
1387 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001389 }
1390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 /* Update our counter in the thread-state - no need for locks:
1392 - tcur will remain valid as we hold the GIL.
1393 - the counter is safe as we are the only thread "allowed"
1394 to modify this value
1395 */
1396 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001399}
1400
Tim Peters19717fa2004-10-09 17:38:29 +00001401void
1402PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001403{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001404 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001405 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1406 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 Py_FatalError("auto-releasing thread-state, "
1408 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001409 }
1410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 /* We must hold the GIL and have our thread state current */
1412 /* XXX - remove the check - the assert should be fine,
1413 but while this is very new (April 2003), the extra check
1414 by release-only users can't hurt.
1415 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001416 if (!PyThreadState_IsCurrent(tstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001417 _Py_FatalErrorFormat(__func__,
1418 "thread state %p must be current when releasing",
1419 tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001420 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001421 assert(PyThreadState_IsCurrent(tstate));
1422 --tstate->gilstate_counter;
1423 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 /* If we're going to destroy this thread-state, we must
1426 * clear it while the GIL is held, as destructors may run.
1427 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001428 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 /* can't have been locked when we created it */
1430 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001431 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 /* Delete the thread-state. Note this releases the GIL too!
1433 * It's vital that the GIL be held here, to avoid shutdown
1434 * races; see bugs 225673 and 1061968 (that nasty bug has a
1435 * habit of coming back).
1436 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001437 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1438 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 }
1440 /* Release the lock if necessary */
1441 else if (oldstate == PyGILState_UNLOCKED)
1442 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001443}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001444
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001445
Eric Snow7f8bfc92018-01-29 18:23:44 -07001446/**************************/
1447/* cross-interpreter data */
1448/**************************/
1449
1450/* cross-interpreter data */
1451
1452crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1453
1454/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1455 to keep the registry code separate. */
1456static crossinterpdatafunc
1457_lookup_getdata(PyObject *obj)
1458{
1459 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1460 if (getdata == NULL && PyErr_Occurred() == 0)
1461 PyErr_Format(PyExc_ValueError,
1462 "%S does not support cross-interpreter data", obj);
1463 return getdata;
1464}
1465
1466int
1467_PyObject_CheckCrossInterpreterData(PyObject *obj)
1468{
1469 crossinterpdatafunc getdata = _lookup_getdata(obj);
1470 if (getdata == NULL) {
1471 return -1;
1472 }
1473 return 0;
1474}
1475
1476static int
Victor Stinner71a35222020-03-26 22:46:14 +01001477_check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001478{
1479 // data->data can be anything, including NULL, so we don't check it.
1480
1481 // data->obj may be NULL, so we don't check it.
1482
1483 if (data->interp < 0) {
Victor Stinner71a35222020-03-26 22:46:14 +01001484 _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001485 return -1;
1486 }
1487
1488 if (data->new_object == NULL) {
Victor Stinner71a35222020-03-26 22:46:14 +01001489 _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001490 return -1;
1491 }
1492
1493 // data->free may be NULL, so we don't check it.
1494
1495 return 0;
1496}
1497
1498int
1499_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1500{
Victor Stinner71a35222020-03-26 22:46:14 +01001501 // PyThreadState_Get() aborts if tstate is NULL.
1502 PyThreadState *tstate = PyThreadState_Get();
1503 PyInterpreterState *interp = tstate->interp;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001504
1505 // Reset data before re-populating.
1506 *data = (_PyCrossInterpreterData){0};
1507 data->free = PyMem_RawFree; // Set a default that may be overridden.
1508
1509 // Call the "getdata" func for the object.
1510 Py_INCREF(obj);
1511 crossinterpdatafunc getdata = _lookup_getdata(obj);
1512 if (getdata == NULL) {
1513 Py_DECREF(obj);
1514 return -1;
1515 }
1516 int res = getdata(obj, data);
1517 Py_DECREF(obj);
1518 if (res != 0) {
1519 return -1;
1520 }
1521
1522 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001523 data->interp = interp->id;
Victor Stinner71a35222020-03-26 22:46:14 +01001524 if (_check_xidata(tstate, data) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001525 _PyCrossInterpreterData_Release(data);
1526 return -1;
1527 }
1528
1529 return 0;
1530}
1531
Victor Stinnere225beb2019-06-03 18:14:24 +02001532static void
Eric Snow63799132018-06-01 18:45:20 -06001533_release_xidata(void *arg)
1534{
1535 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1536 if (data->free != NULL) {
1537 data->free(data->data);
1538 }
1539 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001540}
1541
1542static void
1543_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1544 PyInterpreterState *interp,
1545 void (*func)(void *), void *arg)
1546{
1547 /* We would use Py_AddPendingCall() if it weren't specific to the
1548 * main interpreter (see bpo-33608). In the meantime we take a
1549 * naive approach.
1550 */
1551 PyThreadState *save_tstate = NULL;
1552 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1553 // XXX Using the "head" thread isn't strictly correct.
1554 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1555 // XXX Possible GILState issues?
1556 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1557 }
1558
1559 func(arg);
1560
1561 // Switch back.
1562 if (save_tstate != NULL) {
1563 _PyThreadState_Swap(gilstate, save_tstate);
1564 }
Eric Snow63799132018-06-01 18:45:20 -06001565}
1566
Eric Snow7f8bfc92018-01-29 18:23:44 -07001567void
1568_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1569{
1570 if (data->data == NULL && data->obj == NULL) {
1571 // Nothing to release!
1572 return;
1573 }
1574
Victor Stinnere225beb2019-06-03 18:14:24 +02001575 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001576 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1577 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001578 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001579 if (data->free != NULL) {
1580 // XXX Someone leaked some memory...
1581 }
1582 return;
1583 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001584
Eric Snow7f8bfc92018-01-29 18:23:44 -07001585 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001586 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1587 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001588}
1589
1590PyObject *
1591_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1592{
1593 return data->new_object(data);
1594}
1595
1596/* registry of {type -> crossinterpdatafunc} */
1597
1598/* For now we use a global registry of shareable classes. An
1599 alternative would be to add a tp_* slot for a class's
1600 crossinterpdatafunc. It would be simpler and more efficient. */
1601
1602static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001603_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1604 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001605{
1606 // Note that we effectively replace already registered classes
1607 // rather than failing.
1608 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1609 if (newhead == NULL)
1610 return -1;
1611 newhead->cls = cls;
1612 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001613 newhead->next = xidregistry->head;
1614 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001615 return 0;
1616}
1617
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001618static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001619
1620int
Eric Snowc11183c2019-03-15 16:35:46 -06001621_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001622 crossinterpdatafunc getdata)
1623{
1624 if (!PyType_Check(cls)) {
1625 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1626 return -1;
1627 }
1628 if (getdata == NULL) {
1629 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1630 return -1;
1631 }
1632
1633 // Make sure the class isn't ever deallocated.
1634 Py_INCREF((PyObject *)cls);
1635
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001636 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1637 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1638 if (xidregistry->head == NULL) {
1639 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001640 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001641 int res = _register_xidata(xidregistry, cls, getdata);
1642 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001643 return res;
1644}
1645
Eric Snow6d2cd902018-05-16 15:04:57 -04001646/* Cross-interpreter objects are looked up by exact match on the class.
1647 We can reassess this policy when we move from a global registry to a
1648 tp_* slot. */
1649
Eric Snow7f8bfc92018-01-29 18:23:44 -07001650crossinterpdatafunc
1651_PyCrossInterpreterData_Lookup(PyObject *obj)
1652{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001653 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001654 PyObject *cls = PyObject_Type(obj);
1655 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001656 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1657 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001658 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001659 _register_builtins_for_crossinterpreter_data(xidregistry);
1660 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001661 }
1662 for(; cur != NULL; cur = cur->next) {
1663 if (cur->cls == (PyTypeObject *)cls) {
1664 getdata = cur->getdata;
1665 break;
1666 }
1667 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001668 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001669 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001670 return getdata;
1671}
1672
1673/* cross-interpreter data for builtin types */
1674
Eric Snow6d2cd902018-05-16 15:04:57 -04001675struct _shared_bytes_data {
1676 char *bytes;
1677 Py_ssize_t len;
1678};
1679
Eric Snow7f8bfc92018-01-29 18:23:44 -07001680static PyObject *
1681_new_bytes_object(_PyCrossInterpreterData *data)
1682{
Eric Snow6d2cd902018-05-16 15:04:57 -04001683 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1684 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001685}
1686
1687static int
1688_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1689{
Eric Snow6d2cd902018-05-16 15:04:57 -04001690 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1691 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1692 return -1;
1693 }
1694 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001695 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001696 data->obj = obj; // Will be "released" (decref'ed) when data released.
1697 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001698 data->free = PyMem_Free;
1699 return 0;
1700}
1701
1702struct _shared_str_data {
1703 int kind;
1704 const void *buffer;
1705 Py_ssize_t len;
1706};
1707
1708static PyObject *
1709_new_str_object(_PyCrossInterpreterData *data)
1710{
1711 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1712 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1713}
1714
1715static int
1716_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1717{
1718 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1719 shared->kind = PyUnicode_KIND(obj);
1720 shared->buffer = PyUnicode_DATA(obj);
1721 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1722 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001723 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001724 data->obj = obj; // Will be "released" (decref'ed) when data released.
1725 data->new_object = _new_str_object;
1726 data->free = PyMem_Free;
1727 return 0;
1728}
1729
1730static PyObject *
1731_new_long_object(_PyCrossInterpreterData *data)
1732{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001733 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001734}
1735
1736static int
1737_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1738{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001739 /* Note that this means the size of shareable ints is bounded by
1740 * sys.maxsize. Hence on 32-bit architectures that is half the
1741 * size of maximum shareable ints on 64-bit.
1742 */
1743 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001744 if (value == -1 && PyErr_Occurred()) {
1745 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1746 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1747 }
1748 return -1;
1749 }
1750 data->data = (void *)value;
1751 data->obj = NULL;
1752 data->new_object = _new_long_object;
1753 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001754 return 0;
1755}
1756
1757static PyObject *
1758_new_none_object(_PyCrossInterpreterData *data)
1759{
1760 // XXX Singleton refcounts are problematic across interpreters...
1761 Py_INCREF(Py_None);
1762 return Py_None;
1763}
1764
1765static int
1766_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1767{
1768 data->data = NULL;
1769 // data->obj remains NULL
1770 data->new_object = _new_none_object;
1771 data->free = NULL; // There is nothing to free.
1772 return 0;
1773}
1774
1775static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001776_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001777{
1778 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001779 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001780 Py_FatalError("could not register None for cross-interpreter sharing");
1781 }
1782
Eric Snow6d2cd902018-05-16 15:04:57 -04001783 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001784 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001785 Py_FatalError("could not register int for cross-interpreter sharing");
1786 }
1787
Eric Snow7f8bfc92018-01-29 18:23:44 -07001788 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001789 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001790 Py_FatalError("could not register bytes for cross-interpreter sharing");
1791 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001792
1793 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001794 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001795 Py_FatalError("could not register str for cross-interpreter sharing");
1796 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001797}
1798
1799
Victor Stinner0b72b232020-03-12 23:18:39 +01001800_PyFrameEvalFunction
1801_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1802{
1803 return interp->eval_frame;
1804}
1805
1806
1807void
1808_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1809 _PyFrameEvalFunction eval_frame)
1810{
1811 interp->eval_frame = eval_frame;
1812}
1813
Victor Stinnerda7933e2020-04-13 03:04:28 +02001814
1815const PyConfig*
1816_PyInterpreterState_GetConfig(PyInterpreterState *interp)
1817{
1818 return &interp->config;
1819}
1820
1821
1822PyStatus
1823_PyInterpreterState_SetConfig(PyInterpreterState *interp,
1824 const PyConfig *config)
1825{
1826 return _PyConfig_Copy(&interp->config, config);
1827}
1828
1829
1830const PyConfig*
1831_Py_GetConfig(void)
1832{
1833 assert(PyGILState_Check());
1834 PyThreadState *tstate = _PyThreadState_GET();
1835 return _PyInterpreterState_GetConfig(tstate->interp);
1836}
1837
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001838#ifdef __cplusplus
1839}
1840#endif