blob: 0539096bdc55d7f6276fe49c2bb935fa20adada7 [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 Stinner621cebe2018-11-12 16:53:38 +01009#include "pycore_pymem.h"
10#include "pycore_pystate.h"
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
Eric Snow8479a342019-03-08 23:44:33 -0700135/* This function is called from PyOS_AfterFork_Child to ensure that
136 * newly created child processes do not share locks with the parent.
137 */
138
139void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200140_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700141{
142 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200143 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700144
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200145 /* Force default allocator, since _PyRuntimeState_Fini() must
146 use the same allocator than this function. */
147 PyMemAllocatorEx old_alloc;
148 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
149
150 runtime->interpreters.mutex = PyThread_allocate_lock();
151 runtime->interpreters.main->id_mutex = PyThread_allocate_lock();
152 runtime->xidregistry.mutex = PyThread_allocate_lock();
153
154 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
155
156 if (runtime->interpreters.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700157 Py_FatalError("Can't initialize lock for runtime interpreters");
158 }
159
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200160 if (runtime->interpreters.main->id_mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700161 Py_FatalError("Can't initialize ID lock for main interpreter");
162 }
163
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200164 if (runtime->xidregistry.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700165 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
166 }
167}
168
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200169#define HEAD_LOCK(runtime) \
170 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
171#define HEAD_UNLOCK(runtime) \
172 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700173
Victor Stinner8bb32302019-04-24 16:47:40 +0200174/* Forward declaration */
175static void _PyGILState_NoteThreadState(
176 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000177
Victor Stinner331a6a52019-05-27 16:39:22 +0200178PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600179_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700180{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200181 struct pyinterpreters *interpreters = &runtime->interpreters;
182 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100183
184 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
185 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200186 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100187 /* Force default allocator, since _PyRuntimeState_Fini() must
188 use the same allocator than this function. */
189 PyMemAllocatorEx old_alloc;
190 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
191
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200192 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100193
194 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
195
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200196 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200197 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800198 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600199 }
Victor Stinner5d926472018-03-06 14:31:37 +0100200
Victor Stinner331a6a52019-05-27 16:39:22 +0200201 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700202}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000203
204PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000205PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000206{
Victor Stinner71a35222020-03-26 22:46:14 +0100207 PyThreadState *tstate = _PyThreadState_GET();
208 /* tstate is NULL when Py_InitializeFromConfig() calls
209 PyInterpreterState_New() to create the main interpreter. */
210 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_New", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700211 return NULL;
212 }
213
Andy Lester7668a8b2020-03-24 23:26:44 -0500214 PyInterpreterState *interp = PyMem_RawCalloc(1, sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100215 if (interp == NULL) {
216 return NULL;
217 }
218
Eric Snow4c6955e2018-02-16 18:53:40 -0700219 interp->id_refcount = -1;
Victor Stinner022be022019-05-22 23:58:50 +0200220
Victor Stinner71a35222020-03-26 22:46:14 +0100221 /* Don't get runtime from tstate since tstate can be NULL */
Victor Stinner01b1cc12019-11-20 02:27:56 +0100222 _PyRuntimeState *runtime = &_PyRuntime;
223 interp->runtime = runtime;
224
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200225 if (_PyEval_InitState(&interp->ceval) < 0) {
226 goto out_of_memory;
227 }
228
Victor Stinner72474072019-11-20 12:25:50 +0100229 _PyGC_InitState(&interp->gc);
Victor Stinner8462a492019-10-01 12:06:16 +0200230 PyConfig_InitPythonConfig(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200231
Victor Stinnerd4341102017-11-23 00:12:09 +0100232 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000233#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300234#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100235 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000236#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100237 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000238#endif
239#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000240
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200241 struct pyinterpreters *interpreters = &runtime->interpreters;
242
243 HEAD_LOCK(runtime);
244 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100245 /* overflow or Py_Initialize() not called! */
Victor Stinner71a35222020-03-26 22:46:14 +0100246 if (tstate != NULL) {
247 _PyErr_SetString(tstate, PyExc_RuntimeError,
248 "failed to get an interpreter ID");
249 }
Pablo Galindo95d630e2018-08-31 22:49:29 +0100250 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100251 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100252 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200253 else {
254 interp->id = interpreters->next_id;
255 interpreters->next_id += 1;
256 interp->next = interpreters->head;
257 if (interpreters->main == NULL) {
258 interpreters->main = interp;
259 }
260 interpreters->head = interp;
261 }
262 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000263
Pablo Galindo95d630e2018-08-31 22:49:29 +0100264 if (interp == NULL) {
265 return NULL;
266 }
267
Yury Selivanovf23746a2018-01-22 19:11:18 -0500268 interp->tstate_next_unique_id = 0;
269
Steve Dowerb82e17e2019-05-23 08:45:22 -0700270 interp->audit_hooks = NULL;
271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 return interp;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200273
274out_of_memory:
275 if (tstate != NULL) {
276 _PyErr_NoMemory(tstate);
277 }
278
279 PyMem_RawFree(interp);
280 return NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000281}
282
283
Victor Stinner01b1cc12019-11-20 02:27:56 +0100284void
285PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000286{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100287 _PyRuntimeState *runtime = interp->runtime;
288
Victor Stinner71a35222020-03-26 22:46:14 +0100289 /* Use the current Python thread state to call audit hooks,
290 not the current Python thread state of 'interp'. */
291 PyThreadState *tstate = _PyThreadState_GET();
292 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_Clear", NULL) < 0) {
293 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700294 }
295
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200296 HEAD_LOCK(runtime);
297 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200299 }
300 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700301
302 Py_CLEAR(interp->audit_hooks);
303
Victor Stinner331a6a52019-05-27 16:39:22 +0200304 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 Py_CLEAR(interp->codec_search_path);
306 Py_CLEAR(interp->codec_search_cache);
307 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700308 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 Py_CLEAR(interp->sysdict);
311 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200312 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400313 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300314 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600315 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200316#ifdef HAVE_FORK
317 Py_CLEAR(interp->before_forkers);
318 Py_CLEAR(interp->after_forkers_parent);
319 Py_CLEAR(interp->after_forkers_child);
320#endif
Victor Stinner7b3c2522020-03-07 00:24:23 +0100321 if (_PyRuntimeState_GetFinalizing(runtime) == NULL) {
Eric Snow86ea5812019-05-10 13:29:55 -0400322 _PyWarnings_Fini(interp);
323 }
Eric Snow5be45a62019-03-08 22:47:07 -0700324 // XXX Once we have one allocator per interpreter (i.e.
325 // per-interpreter GC) we must ensure that all of the interpreter's
326 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000327}
328
329
330static void
Victor Stinner9da74302019-11-20 11:17:17 +0100331zapthreads(PyInterpreterState *interp, int check_current)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000332{
Victor Stinner9da74302019-11-20 11:17:17 +0100333 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 /* No need to lock the mutex here because this should only happen
335 when the threads are all really dead (XXX famous last words). */
Victor Stinner9da74302019-11-20 11:17:17 +0100336 while ((tstate = interp->tstate_head) != NULL) {
337 _PyThreadState_Delete(tstate, check_current);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000339}
340
341
Victor Stinner01b1cc12019-11-20 02:27:56 +0100342void
343PyInterpreterState_Delete(PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200344{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100345 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200346 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner9da74302019-11-20 11:17:17 +0100347 zapthreads(interp, 0);
348
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200349 _PyEval_FiniState(&interp->ceval);
350
Victor Stinner9da74302019-11-20 11:17:17 +0100351 /* Delete current thread. After this, many C API calls become crashy. */
352 _PyThreadState_Swap(&runtime->gilstate, NULL);
353
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200354 HEAD_LOCK(runtime);
355 PyInterpreterState **p;
356 for (p = &interpreters->head; ; p = &(*p)->next) {
357 if (*p == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100358 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200359 }
360 if (*p == interp) {
361 break;
362 }
363 }
364 if (interp->tstate_head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100365 Py_FatalError("remaining threads");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200366 }
367 *p = interp->next;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200368
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200369 if (interpreters->main == interp) {
370 interpreters->main = NULL;
371 if (interpreters->head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100372 Py_FatalError("remaining subinterpreters");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200373 }
374 }
375 HEAD_UNLOCK(runtime);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200376
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200377 if (interp->id_mutex != NULL) {
378 PyThread_free_lock(interp->id_mutex);
379 }
380 PyMem_RawFree(interp);
381}
382
383
Eric Snow59032962018-09-14 14:17:20 -0700384/*
385 * Delete all interpreter states except the main interpreter. If there
386 * is a current interpreter state, it *must* be the main interpreter.
387 */
388void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200389_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700390{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200391 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200392 struct pyinterpreters *interpreters = &runtime->interpreters;
393
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200394 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200395 if (tstate != NULL && tstate->interp != interpreters->main) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100396 Py_FatalError("not main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700397 }
398
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200399 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200400 PyInterpreterState *interp = interpreters->head;
401 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100402 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200403 if (interp == interpreters->main) {
404 interpreters->main->next = NULL;
405 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100406 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700407 continue;
408 }
409
Victor Stinner01b1cc12019-11-20 02:27:56 +0100410 PyInterpreterState_Clear(interp); // XXX must activate?
Victor Stinner9da74302019-11-20 11:17:17 +0100411 zapthreads(interp, 1);
Eric Snow59032962018-09-14 14:17:20 -0700412 if (interp->id_mutex != NULL) {
413 PyThread_free_lock(interp->id_mutex);
414 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100415 PyInterpreterState *prev_interp = interp;
416 interp = interp->next;
417 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700418 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200419 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700420
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200421 if (interpreters->head == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100422 Py_FatalError("missing main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700423 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200424 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700425}
426
427
Victor Stinnercaba55b2018-08-03 15:33:52 +0200428PyInterpreterState *
Victor Stinnerbe793732020-03-13 18:15:33 +0100429PyInterpreterState_Get(void)
Victor Stinnercaba55b2018-08-03 15:33:52 +0200430{
Victor Stinner50b48572018-11-01 01:51:40 +0100431 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner23ef89d2020-03-18 02:26:04 +0100432 ensure_tstate_not_null(__func__, tstate);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200433 PyInterpreterState *interp = tstate->interp;
434 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100435 Py_FatalError("no current interpreter");
Victor Stinnercaba55b2018-08-03 15:33:52 +0200436 }
437 return interp;
438}
439
440
Eric Snowe3774162017-05-22 19:46:40 -0700441int64_t
442PyInterpreterState_GetID(PyInterpreterState *interp)
443{
444 if (interp == NULL) {
445 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
446 return -1;
447 }
448 return interp->id;
449}
450
451
Eric Snow5be45a62019-03-08 22:47:07 -0700452static PyInterpreterState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200453interp_look_up_id(_PyRuntimeState *runtime, PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700454{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200455 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100456 while (interp != NULL) {
457 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700458 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100459 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700460 }
461 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100462 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700463 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100464 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700465 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100466 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700467}
468
Eric Snow5be45a62019-03-08 22:47:07 -0700469PyInterpreterState *
470_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
471{
472 PyInterpreterState *interp = NULL;
473 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200474 _PyRuntimeState *runtime = &_PyRuntime;
475 HEAD_LOCK(runtime);
476 interp = interp_look_up_id(runtime, requested_id);
477 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700478 }
479 if (interp == NULL && !PyErr_Occurred()) {
480 PyErr_Format(PyExc_RuntimeError,
481 "unrecognized interpreter ID %lld", requested_id);
482 }
483 return interp;
484}
485
Eric Snow4c6955e2018-02-16 18:53:40 -0700486
487int
488_PyInterpreterState_IDInitref(PyInterpreterState *interp)
489{
490 if (interp->id_mutex != NULL) {
491 return 0;
492 }
493 interp->id_mutex = PyThread_allocate_lock();
494 if (interp->id_mutex == NULL) {
495 PyErr_SetString(PyExc_RuntimeError,
496 "failed to create init interpreter ID mutex");
497 return -1;
498 }
499 interp->id_refcount = 0;
500 return 0;
501}
502
503
504void
505_PyInterpreterState_IDIncref(PyInterpreterState *interp)
506{
507 if (interp->id_mutex == NULL) {
508 return;
509 }
510 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
511 interp->id_refcount += 1;
512 PyThread_release_lock(interp->id_mutex);
513}
514
515
516void
517_PyInterpreterState_IDDecref(PyInterpreterState *interp)
518{
519 if (interp->id_mutex == NULL) {
520 return;
521 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200522 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700523 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
524 assert(interp->id_refcount != 0);
525 interp->id_refcount -= 1;
526 int64_t refcount = interp->id_refcount;
527 PyThread_release_lock(interp->id_mutex);
528
Eric Snowc11183c2019-03-15 16:35:46 -0600529 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700530 // XXX Using the "head" thread isn't strictly correct.
531 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
532 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200533 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700534 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200535 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700536 }
537}
538
Eric Snowc11183c2019-03-15 16:35:46 -0600539int
540_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
541{
542 return interp->requires_idref;
543}
544
545void
546_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
547{
548 interp->requires_idref = required ? 1 : 0;
549}
550
Eric Snowc11183c2019-03-15 16:35:46 -0600551PyObject *
552_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
553{
554 if (interp->modules == NULL) {
555 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
556 return NULL;
557 }
558 return PyMapping_GetItemString(interp->modules, "__main__");
559}
560
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600561PyObject *
562PyInterpreterState_GetDict(PyInterpreterState *interp)
563{
564 if (interp->dict == NULL) {
565 interp->dict = PyDict_New();
566 if (interp->dict == NULL) {
567 PyErr_Clear();
568 }
569 }
570 /* Returning NULL means no per-interpreter dict is available. */
571 return interp->dict;
572}
573
Victor Stinner45b9be52010-03-03 23:28:07 +0000574static PyThreadState *
575new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000576{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100577 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200578 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200579 if (tstate == NULL) {
580 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000582
Victor Stinner8bb32302019-04-24 16:47:40 +0200583 tstate->interp = interp;
584
585 tstate->frame = NULL;
586 tstate->recursion_depth = 0;
587 tstate->overflowed = 0;
588 tstate->recursion_critical = 0;
589 tstate->stackcheck_counter = 0;
590 tstate->tracing = 0;
591 tstate->use_tracing = 0;
592 tstate->gilstate_counter = 0;
593 tstate->async_exc = NULL;
594 tstate->thread_id = PyThread_get_thread_ident();
595
596 tstate->dict = NULL;
597
598 tstate->curexc_type = NULL;
599 tstate->curexc_value = NULL;
600 tstate->curexc_traceback = NULL;
601
602 tstate->exc_state.exc_type = NULL;
603 tstate->exc_state.exc_value = NULL;
604 tstate->exc_state.exc_traceback = NULL;
605 tstate->exc_state.previous_item = NULL;
606 tstate->exc_info = &tstate->exc_state;
607
608 tstate->c_profilefunc = NULL;
609 tstate->c_tracefunc = NULL;
610 tstate->c_profileobj = NULL;
611 tstate->c_traceobj = NULL;
612
613 tstate->trash_delete_nesting = 0;
614 tstate->trash_delete_later = NULL;
615 tstate->on_delete = NULL;
616 tstate->on_delete_data = NULL;
617
618 tstate->coroutine_origin_tracking_depth = 0;
619
Victor Stinner8bb32302019-04-24 16:47:40 +0200620 tstate->async_gen_firstiter = NULL;
621 tstate->async_gen_finalizer = NULL;
622
623 tstate->context = NULL;
624 tstate->context_ver = 1;
625
Victor Stinner8bb32302019-04-24 16:47:40 +0200626 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100627 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200628 }
629
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200630 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100631 tstate->id = ++interp->tstate_next_unique_id;
Victor Stinner8bb32302019-04-24 16:47:40 +0200632 tstate->prev = NULL;
633 tstate->next = interp->tstate_head;
634 if (tstate->next)
635 tstate->next->prev = tstate;
636 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200637 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000640}
641
Victor Stinner45b9be52010-03-03 23:28:07 +0000642PyThreadState *
643PyThreadState_New(PyInterpreterState *interp)
644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000646}
647
648PyThreadState *
649_PyThreadState_Prealloc(PyInterpreterState *interp)
650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000652}
653
654void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100655_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000656{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100657 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000658}
659
Martin v. Löwis1a214512008-06-11 05:26:20 +0000660PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200661PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000662{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200663 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100664 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000666 if (module->m_slots) {
667 return NULL;
668 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if (index == 0)
670 return NULL;
671 if (state->modules_by_index == NULL)
672 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200673 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 return NULL;
675 res = PyList_GET_ITEM(state->modules_by_index, index);
676 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000677}
678
679int
Victor Stinner82c83bd2019-11-22 18:52:27 +0100680_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000681{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300682 if (!def) {
Victor Stinner71a35222020-03-26 22:46:14 +0100683 assert(_PyErr_Occurred(tstate));
Berker Peksag4b7b5652016-08-22 18:05:56 +0300684 return -1;
685 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000686 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100687 _PyErr_SetString(tstate,
688 PyExc_SystemError,
689 "PyState_AddModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000690 return -1;
691 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100692
693 PyInterpreterState *interp = tstate->interp;
694 if (!interp->modules_by_index) {
695 interp->modules_by_index = PyList_New(0);
696 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100698 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100700
701 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
702 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100704 }
705 }
706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100708 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000710}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000711
Martin v. Löwis7800f752012-06-22 12:20:55 +0200712int
713PyState_AddModule(PyObject* module, struct PyModuleDef* def)
714{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200715 if (!def) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100716 Py_FatalError("module definition is NULL");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200717 return -1;
718 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100719
720 PyThreadState *tstate = _PyThreadState_GET();
721 PyInterpreterState *interp = tstate->interp;
722 Py_ssize_t index = def->m_base.m_index;
723 if (interp->modules_by_index &&
724 index < PyList_GET_SIZE(interp->modules_by_index) &&
725 module == PyList_GET_ITEM(interp->modules_by_index, index))
726 {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100727 _Py_FatalErrorFormat(__func__, "module %p already added", module);
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100728 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200729 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100730 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200731}
732
733int
734PyState_RemoveModule(struct PyModuleDef* def)
735{
Victor Stinner71a35222020-03-26 22:46:14 +0100736 PyThreadState *tstate = _PyThreadState_GET();
737 PyInterpreterState *interp = tstate->interp;
738
Nick Coghland5cacbb2015-05-23 22:24:10 +1000739 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100740 _PyErr_SetString(tstate,
741 PyExc_SystemError,
742 "PyState_RemoveModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000743 return -1;
744 }
Victor Stinner71a35222020-03-26 22:46:14 +0100745
746 Py_ssize_t index = def->m_base.m_index;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200747 if (index == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100748 Py_FatalError("invalid module index");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200749 }
Victor Stinner71a35222020-03-26 22:46:14 +0100750 if (interp->modules_by_index == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100751 Py_FatalError("Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200752 }
Victor Stinner71a35222020-03-26 22:46:14 +0100753 if (index > PyList_GET_SIZE(interp->modules_by_index)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100754 Py_FatalError("Module index out of bounds.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200755 }
Victor Stinner71a35222020-03-26 22:46:14 +0100756
Zackery Spytz2a893432018-12-05 00:14:00 -0700757 Py_INCREF(Py_None);
Victor Stinner71a35222020-03-26 22:46:14 +0100758 return PyList_SetItem(interp->modules_by_index, index, Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200759}
760
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200761/* Used by PyImport_Cleanup() */
Antoine Pitrou40322e62013-08-11 00:30:09 +0200762void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200763_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200764{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200765 if (!interp->modules_by_index) {
766 return;
767 }
768
769 Py_ssize_t i;
770 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
771 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
772 if (PyModule_Check(m)) {
773 /* cleanup the saved copy of module dicts */
774 PyModuleDef *md = PyModule_GetDef(m);
775 if (md) {
776 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200777 }
778 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200779 }
780
781 /* Setting modules_by_index to NULL could be dangerous, so we
782 clear the list instead. */
783 if (PyList_SetSlice(interp->modules_by_index,
784 0, PyList_GET_SIZE(interp->modules_by_index),
785 NULL)) {
786 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200787 }
788}
789
Guido van Rossuma027efa1997-05-05 20:56:21 +0000790void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000791PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000792{
Victor Stinner331a6a52019-05-27 16:39:22 +0200793 int verbose = tstate->interp->config.verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200794
Victor Stinner5804f872020-03-24 16:32:26 +0100795 if (verbose && tstate->frame != NULL) {
796 /* bpo-20526: After the main thread calls
797 _PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
798 exit when trying to take the GIL. If a thread exit in the middle of
799 _PyEval_EvalFrameDefault(), tstate->frame is not reset to its
800 previous value. It is more likely with daemon threads, but it can
801 happen with regular threads if threading._shutdown() fails
802 (ex: interrupted by CTRL+C). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 fprintf(stderr,
804 "PyThreadState_Clear: warning: thread still has a frame\n");
Victor Stinner5804f872020-03-24 16:32:26 +0100805 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000806
Victor Stinner5804f872020-03-24 16:32:26 +0100807 /* Don't clear tstate->frame: it is a borrowed reference */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 Py_CLEAR(tstate->dict);
810 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 Py_CLEAR(tstate->curexc_type);
813 Py_CLEAR(tstate->curexc_value);
814 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000815
Mark Shannonae3087c2017-10-22 22:41:51 +0100816 Py_CLEAR(tstate->exc_state.exc_type);
817 Py_CLEAR(tstate->exc_state.exc_value);
818 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300819
Mark Shannonae3087c2017-10-22 22:41:51 +0100820 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200821 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100822 fprintf(stderr,
823 "PyThreadState_Clear: warning: thread still has a generator\n");
824 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 tstate->c_profilefunc = NULL;
827 tstate->c_tracefunc = NULL;
828 Py_CLEAR(tstate->c_profileobj);
829 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400830
Yury Selivanoveb636452016-09-08 22:01:51 -0700831 Py_CLEAR(tstate->async_gen_firstiter);
832 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500833
834 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100835
836 if (tstate->on_delete != NULL) {
837 tstate->on_delete(tstate->on_delete_data);
838 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000839}
840
841
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300842/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000843static void
Victor Stinner9da74302019-11-20 11:17:17 +0100844tstate_delete_common(PyThreadState *tstate,
845 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000846{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100847 ensure_tstate_not_null(__func__, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200848 PyInterpreterState *interp = tstate->interp;
849 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100850 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200851 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100852 _PyRuntimeState *runtime = interp->runtime;
853
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200854 HEAD_LOCK(runtime);
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100855 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200856 tstate->prev->next = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100857 }
858 else {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200859 interp->tstate_head = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100860 }
861 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200862 tstate->next->prev = tstate->prev;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100863 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200864 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100865
Victor Stinner9da74302019-11-20 11:17:17 +0100866 if (gilstate->autoInterpreterState &&
867 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
868 {
869 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
870 }
871}
872
873
874static void
875_PyThreadState_Delete(PyThreadState *tstate, int check_current)
876{
877 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
878 if (check_current) {
879 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100880 _Py_FatalErrorFormat(__func__, "tstate %p is still current", tstate);
Victor Stinner9da74302019-11-20 11:17:17 +0100881 }
882 }
883 tstate_delete_common(tstate, gilstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100884 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000885}
886
887
Victor Stinner01b1cc12019-11-20 02:27:56 +0100888void
889PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000890{
Victor Stinner9da74302019-11-20 11:17:17 +0100891 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200892}
893
894
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300895void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100896_PyThreadState_DeleteCurrent(PyThreadState *tstate)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200897{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100898 ensure_tstate_not_null(__func__, tstate);
899 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner9da74302019-11-20 11:17:17 +0100900 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200901 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100902 _PyEval_ReleaseLock(tstate);
903 PyMem_RawFree(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000904}
Guido van Rossum29757862001-01-23 01:46:06 +0000905
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300906void
907PyThreadState_DeleteCurrent(void)
908{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100909 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
910 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
911 _PyThreadState_DeleteCurrent(tstate);
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300912}
913
Guido van Rossum29757862001-01-23 01:46:06 +0000914
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200915/*
916 * Delete all thread states except the one passed as argument.
917 * Note that, if there is a current thread state, it *must* be the one
918 * passed as argument. Also, this won't touch any other interpreters
919 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000920 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200921 */
922void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200923_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200924{
925 PyInterpreterState *interp = tstate->interp;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100926
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200927 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200928 /* Remove all thread states, except tstate, from the linked list of
929 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200930 without holding the lock. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100931 PyThreadState *list = interp->tstate_head;
932 if (list == tstate) {
933 list = tstate->next;
934 }
935 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200936 tstate->prev->next = tstate->next;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100937 }
938 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200939 tstate->next->prev = tstate->prev;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100940 }
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200941 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200942 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200943 HEAD_UNLOCK(runtime);
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100944
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200945 /* Clear and deallocate all stale thread states. Even if this
946 executes Python code, we should be safe since it executes
947 in the current thread, not one of the stale threads. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100948 PyThreadState *p, *next;
949 for (p = list; p; p = next) {
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200950 next = p->next;
951 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200952 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200953 }
954}
955
956
Guido van Rossuma027efa1997-05-05 20:56:21 +0000957PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100958_PyThreadState_UncheckedGet(void)
959{
Victor Stinner50b48572018-11-01 01:51:40 +0100960 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100961}
962
963
964PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000965PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000966{
Victor Stinner50b48572018-11-01 01:51:40 +0100967 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner23ef89d2020-03-18 02:26:04 +0100968 ensure_tstate_not_null(__func__, tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000970}
971
972
Victor Stinner09532fe2019-05-10 23:39:09 +0200973PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200974_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000975{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200976 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000977
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200978 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 /* It should not be possible for more than one thread state
980 to be used for a thread. Check this the best we can in debug
981 builds.
982 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200983#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 if (newts) {
985 /* This can be called from PyEval_RestoreThread(). Similar
986 to it, we need to ensure errno doesn't change.
987 */
988 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200989 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 if (check && check->interp == newts->interp && check != newts)
991 Py_FatalError("Invalid thread state for this thread");
992 errno = err;
993 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000994#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000996}
Guido van Rossumede04391998-04-10 20:18:25 +0000997
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200998PyThreadState *
999PyThreadState_Swap(PyThreadState *newts)
1000{
1001 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
1002}
1003
Guido van Rossumede04391998-04-10 20:18:25 +00001004/* An extension mechanism to store arbitrary additional per-thread state.
1005 PyThreadState_GetDict() returns a dictionary that can be used to hold such
1006 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001007 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
1008 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +00001009
1010PyObject *
Victor Stinner0e427c62020-03-25 21:22:55 +01001011_PyThreadState_GetDict(PyThreadState *tstate)
1012{
1013 assert(tstate != NULL);
1014 if (tstate->dict == NULL) {
1015 tstate->dict = PyDict_New();
1016 if (tstate->dict == NULL) {
1017 _PyErr_Clear(tstate);
1018 }
1019 }
1020 return tstate->dict;
1021}
1022
1023
1024PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001025PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +00001026{
Victor Stinner50b48572018-11-01 01:51:40 +01001027 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner0e427c62020-03-25 21:22:55 +01001028 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 }
Victor Stinner0e427c62020-03-25 21:22:55 +01001031 return _PyThreadState_GetDict(tstate);
Guido van Rossumede04391998-04-10 20:18:25 +00001032}
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001033
1034
Victor Stinner8fb02b62020-03-13 23:38:08 +01001035PyInterpreterState *
1036PyThreadState_GetInterpreter(PyThreadState *tstate)
1037{
1038 assert(tstate != NULL);
Victor Stinner8fb02b62020-03-13 23:38:08 +01001039 return tstate->interp;
1040}
1041
1042
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001043struct _frame*
1044PyThreadState_GetFrame(PyThreadState *tstate)
1045{
1046 assert(tstate != NULL);
Victor Stinner6723e932020-03-20 17:46:56 +01001047 return tstate->frame;
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001048}
1049
1050
Victor Stinner5c3cda02020-03-25 21:23:53 +01001051uint64_t
1052PyThreadState_GetID(PyThreadState *tstate)
1053{
1054 assert(tstate != NULL);
1055 return tstate->id;
1056}
1057
1058
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001059/* Asynchronously raise an exception in a thread.
1060 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001061 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001062 to call this, or use ctypes. Must be called with the GIL held.
1063 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1064 match any known thread id). Can be called with exc=NULL to clear an
1065 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001066
1067int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001068PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1069{
Victor Stinner09532fe2019-05-10 23:39:09 +02001070 _PyRuntimeState *runtime = &_PyRuntime;
1071 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 /* Although the GIL is held, a few C API functions can be called
1074 * without the GIL held, and in particular some that create and
1075 * destroy thread and interpreter states. Those can mutate the
1076 * list of thread states we're traversing, so to prevent that we lock
1077 * head_mutex for the duration.
1078 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001079 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001080 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1081 if (tstate->thread_id != id) {
1082 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001084
1085 /* Tricky: we need to decref the current value
1086 * (if any) in tstate->async_exc, but that can in turn
1087 * allow arbitrary Python code to run, including
1088 * perhaps calls to this function. To prevent
1089 * deadlock, we need to release head_mutex before
1090 * the decref.
1091 */
1092 PyObject *old_exc = tstate->async_exc;
1093 Py_XINCREF(exc);
1094 tstate->async_exc = exc;
1095 HEAD_UNLOCK(runtime);
1096
1097 Py_XDECREF(old_exc);
1098 _PyEval_SignalAsyncExc(tstate);
1099 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001101 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001103}
1104
1105
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001106/* Routines for advanced debuggers, requested by David Beazley.
1107 Don't use unless you know what you are doing! */
1108
1109PyInterpreterState *
1110PyInterpreterState_Head(void)
1111{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001112 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001113}
1114
1115PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001116PyInterpreterState_Main(void)
1117{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001118 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001119}
1120
1121PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001122PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001124}
1125
1126PyThreadState *
1127PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001129}
1130
1131PyThreadState *
1132PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001134}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001135
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001136/* The implementation of sys._current_frames(). This is intended to be
1137 called with the GIL held, as it will be when called via
1138 sys._current_frames(). It's possible it would work fine even without
1139 the GIL held, but haven't thought enough about that.
1140*/
1141PyObject *
1142_PyThread_CurrentFrames(void)
1143{
Victor Stinner71a35222020-03-26 22:46:14 +01001144 PyThreadState *tstate = _PyThreadState_GET();
1145 if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001146 return NULL;
1147 }
1148
Victor Stinner71a35222020-03-26 22:46:14 +01001149 PyObject *result = PyDict_New();
1150 if (result == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 return NULL;
Victor Stinner71a35222020-03-26 22:46:14 +01001152 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 /* for i in all interpreters:
1155 * for t in all of i's thread states:
1156 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001157 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 * need to grab head_mutex for the duration.
1159 */
Victor Stinner71a35222020-03-26 22:46:14 +01001160 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001161 HEAD_LOCK(runtime);
Victor Stinner71a35222020-03-26 22:46:14 +01001162 PyInterpreterState *i;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001163 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 PyThreadState *t;
1165 for (t = i->tstate_head; t != NULL; t = t->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 struct _frame *frame = t->frame;
Victor Stinner71a35222020-03-26 22:46:14 +01001167 if (frame == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 continue;
Victor Stinner71a35222020-03-26 22:46:14 +01001169 }
1170 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1171 if (id == NULL) {
1172 goto fail;
1173 }
1174 int stat = PyDict_SetItem(result, id, (PyObject *)frame);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 Py_DECREF(id);
Victor Stinner71a35222020-03-26 22:46:14 +01001176 if (stat < 0) {
1177 goto fail;
1178 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 }
1180 }
Victor Stinner71a35222020-03-26 22:46:14 +01001181 goto done;
1182
1183fail:
1184 Py_CLEAR(result);
1185
1186done:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001187 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001189}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001190
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001191/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001192
1193/* Keep this as a static, as it is not reliable! It can only
1194 ever be compared to the state for the *current* thread.
1195 * If not equal, then it doesn't matter that the actual
1196 value may change immediately after comparison, as it can't
1197 possibly change to the current thread's state.
1198 * If equal, then the current thread holds the lock, so the value can't
1199 change until we yield the lock.
1200*/
1201static int
1202PyThreadState_IsCurrent(PyThreadState *tstate)
1203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001205 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001206 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1207 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001208}
1209
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001210/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001211 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001212*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001213PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001214_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001215{
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001216 if (!_Py_IsMainInterpreter(tstate)) {
1217 /* Currently, PyGILState is shared by all interpreters. The main
1218 * interpreter is responsible to initialize it. */
1219 return _PyStatus_OK();
1220 }
1221
Victor Stinner8bb32302019-04-24 16:47:40 +02001222 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001223 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001224 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001225
Victor Stinner01b1cc12019-11-20 02:27:56 +01001226 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001227
1228 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001229 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001230 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001231 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001232 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1233 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001234
Victor Stinner8bb32302019-04-24 16:47:40 +02001235 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001236 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001237}
1238
Victor Stinner861d9ab2016-03-16 22:45:24 +01001239PyInterpreterState *
1240_PyGILState_GetInterpreterStateUnsafe(void)
1241{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001242 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001243}
1244
Tim Peters19717fa2004-10-09 17:38:29 +00001245void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001246_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001247{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001248 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001249 PyThread_tss_delete(&gilstate->autoTSSkey);
1250 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001251}
1252
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001253/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001254 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001255 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001256 */
1257void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001258_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001259{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001260 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001261 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001262
1263 PyThread_tss_delete(&gilstate->autoTSSkey);
1264 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001265 Py_FatalError("Could not allocate TSS entry");
1266 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001267
Charles-François Natalia233df82011-11-22 19:49:51 +01001268 /* If the thread had an associated auto thread state, reassociate it with
1269 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001270 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001271 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001272 {
1273 Py_FatalError("Couldn't create autoTSSkey mapping");
1274 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001275}
1276
Michael W. Hudson188d4362005-06-20 16:52:57 +00001277/* When a thread state is created for a thread by some mechanism other than
1278 PyGILState_Ensure, it's important that the GILState machinery knows about
1279 it so it doesn't try to create another thread state for the thread (this is
1280 a better fix for SF bug #1010677 than the first one attempted).
1281*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001282static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001283_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001284{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001285 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001286 threadstate created in Py_Initialize(). Don't do anything for now
1287 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001288 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001290 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001291
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001292 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 The only situation where you can legitimately have more than one
1295 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001296 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001297
Victor Stinner590cebe2013-12-13 11:08:56 +01001298 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1299 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001300
Victor Stinner590cebe2013-12-13 11:08:56 +01001301 The first thread state created for that given OS level thread will
1302 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001304 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1305 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001306 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001307 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001308 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 /* PyGILState_Release must not try to delete this thread state. */
1311 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001312}
1313
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001314/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001315static PyThreadState *
1316_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1317{
1318 if (gilstate->autoInterpreterState == NULL)
1319 return NULL;
1320 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1321}
1322
Tim Peters19717fa2004-10-09 17:38:29 +00001323PyThreadState *
1324PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001325{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001326 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001327}
1328
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001329int
1330PyGILState_Check(void)
1331{
Victor Stinner8a1be612016-03-14 22:07:55 +01001332
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001333 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001334 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001335 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001336
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001337 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1338 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1339 return 1;
1340 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001341
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001342 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1343 if (tstate == NULL) {
1344 return 0;
1345 }
1346
1347 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001348}
1349
Tim Peters19717fa2004-10-09 17:38:29 +00001350PyGILState_STATE
1351PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001352{
Victor Stinner175a7042020-03-10 00:37:48 +01001353 _PyRuntimeState *runtime = &_PyRuntime;
1354 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 /* Note that we do not auto-init Python here - apart from
1357 potential races with 2 threads auto-initializing, pep-311
1358 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001359 called Py_Initialize(). */
1360
1361 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1362 called by Py_Initialize() */
1363 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001364 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001365
Victor Stinner175a7042020-03-10 00:37:48 +01001366 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1367 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001369 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001370 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001371 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001373 }
1374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 /* This is our thread state! We'll need to delete it in the
1376 matching call to PyGILState_Release(). */
1377 tcur->gilstate_counter = 0;
1378 current = 0; /* new thread state is never current */
1379 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001380 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001382 }
1383
1384 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001386 }
1387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 /* Update our counter in the thread-state - no need for locks:
1389 - tcur will remain valid as we hold the GIL.
1390 - the counter is safe as we are the only thread "allowed"
1391 to modify this value
1392 */
1393 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001396}
1397
Tim Peters19717fa2004-10-09 17:38:29 +00001398void
1399PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001400{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001401 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001402 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1403 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 Py_FatalError("auto-releasing thread-state, "
1405 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001406 }
1407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 /* We must hold the GIL and have our thread state current */
1409 /* XXX - remove the check - the assert should be fine,
1410 but while this is very new (April 2003), the extra check
1411 by release-only users can't hurt.
1412 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001413 if (!PyThreadState_IsCurrent(tstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001414 _Py_FatalErrorFormat(__func__,
1415 "thread state %p must be current when releasing",
1416 tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001417 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001418 assert(PyThreadState_IsCurrent(tstate));
1419 --tstate->gilstate_counter;
1420 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 /* If we're going to destroy this thread-state, we must
1423 * clear it while the GIL is held, as destructors may run.
1424 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001425 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 /* can't have been locked when we created it */
1427 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001428 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 /* Delete the thread-state. Note this releases the GIL too!
1430 * It's vital that the GIL be held here, to avoid shutdown
1431 * races; see bugs 225673 and 1061968 (that nasty bug has a
1432 * habit of coming back).
1433 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001434 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1435 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 }
1437 /* Release the lock if necessary */
1438 else if (oldstate == PyGILState_UNLOCKED)
1439 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001440}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001441
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001442
Eric Snow7f8bfc92018-01-29 18:23:44 -07001443/**************************/
1444/* cross-interpreter data */
1445/**************************/
1446
1447/* cross-interpreter data */
1448
1449crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1450
1451/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1452 to keep the registry code separate. */
1453static crossinterpdatafunc
1454_lookup_getdata(PyObject *obj)
1455{
1456 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1457 if (getdata == NULL && PyErr_Occurred() == 0)
1458 PyErr_Format(PyExc_ValueError,
1459 "%S does not support cross-interpreter data", obj);
1460 return getdata;
1461}
1462
1463int
1464_PyObject_CheckCrossInterpreterData(PyObject *obj)
1465{
1466 crossinterpdatafunc getdata = _lookup_getdata(obj);
1467 if (getdata == NULL) {
1468 return -1;
1469 }
1470 return 0;
1471}
1472
1473static int
Victor Stinner71a35222020-03-26 22:46:14 +01001474_check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001475{
1476 // data->data can be anything, including NULL, so we don't check it.
1477
1478 // data->obj may be NULL, so we don't check it.
1479
1480 if (data->interp < 0) {
Victor Stinner71a35222020-03-26 22:46:14 +01001481 _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001482 return -1;
1483 }
1484
1485 if (data->new_object == NULL) {
Victor Stinner71a35222020-03-26 22:46:14 +01001486 _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001487 return -1;
1488 }
1489
1490 // data->free may be NULL, so we don't check it.
1491
1492 return 0;
1493}
1494
1495int
1496_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1497{
Victor Stinner71a35222020-03-26 22:46:14 +01001498 // PyThreadState_Get() aborts if tstate is NULL.
1499 PyThreadState *tstate = PyThreadState_Get();
1500 PyInterpreterState *interp = tstate->interp;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001501
1502 // Reset data before re-populating.
1503 *data = (_PyCrossInterpreterData){0};
1504 data->free = PyMem_RawFree; // Set a default that may be overridden.
1505
1506 // Call the "getdata" func for the object.
1507 Py_INCREF(obj);
1508 crossinterpdatafunc getdata = _lookup_getdata(obj);
1509 if (getdata == NULL) {
1510 Py_DECREF(obj);
1511 return -1;
1512 }
1513 int res = getdata(obj, data);
1514 Py_DECREF(obj);
1515 if (res != 0) {
1516 return -1;
1517 }
1518
1519 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001520 data->interp = interp->id;
Victor Stinner71a35222020-03-26 22:46:14 +01001521 if (_check_xidata(tstate, data) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001522 _PyCrossInterpreterData_Release(data);
1523 return -1;
1524 }
1525
1526 return 0;
1527}
1528
Victor Stinnere225beb2019-06-03 18:14:24 +02001529static void
Eric Snow63799132018-06-01 18:45:20 -06001530_release_xidata(void *arg)
1531{
1532 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1533 if (data->free != NULL) {
1534 data->free(data->data);
1535 }
1536 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001537}
1538
1539static void
1540_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1541 PyInterpreterState *interp,
1542 void (*func)(void *), void *arg)
1543{
1544 /* We would use Py_AddPendingCall() if it weren't specific to the
1545 * main interpreter (see bpo-33608). In the meantime we take a
1546 * naive approach.
1547 */
1548 PyThreadState *save_tstate = NULL;
1549 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1550 // XXX Using the "head" thread isn't strictly correct.
1551 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1552 // XXX Possible GILState issues?
1553 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1554 }
1555
1556 func(arg);
1557
1558 // Switch back.
1559 if (save_tstate != NULL) {
1560 _PyThreadState_Swap(gilstate, save_tstate);
1561 }
Eric Snow63799132018-06-01 18:45:20 -06001562}
1563
Eric Snow7f8bfc92018-01-29 18:23:44 -07001564void
1565_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1566{
1567 if (data->data == NULL && data->obj == NULL) {
1568 // Nothing to release!
1569 return;
1570 }
1571
Victor Stinnere225beb2019-06-03 18:14:24 +02001572 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001573 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1574 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001575 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001576 if (data->free != NULL) {
1577 // XXX Someone leaked some memory...
1578 }
1579 return;
1580 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001581
Eric Snow7f8bfc92018-01-29 18:23:44 -07001582 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001583 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1584 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001585}
1586
1587PyObject *
1588_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1589{
1590 return data->new_object(data);
1591}
1592
1593/* registry of {type -> crossinterpdatafunc} */
1594
1595/* For now we use a global registry of shareable classes. An
1596 alternative would be to add a tp_* slot for a class's
1597 crossinterpdatafunc. It would be simpler and more efficient. */
1598
1599static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001600_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1601 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001602{
1603 // Note that we effectively replace already registered classes
1604 // rather than failing.
1605 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1606 if (newhead == NULL)
1607 return -1;
1608 newhead->cls = cls;
1609 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001610 newhead->next = xidregistry->head;
1611 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001612 return 0;
1613}
1614
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001615static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001616
1617int
Eric Snowc11183c2019-03-15 16:35:46 -06001618_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001619 crossinterpdatafunc getdata)
1620{
1621 if (!PyType_Check(cls)) {
1622 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1623 return -1;
1624 }
1625 if (getdata == NULL) {
1626 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1627 return -1;
1628 }
1629
1630 // Make sure the class isn't ever deallocated.
1631 Py_INCREF((PyObject *)cls);
1632
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001633 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1634 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1635 if (xidregistry->head == NULL) {
1636 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001637 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001638 int res = _register_xidata(xidregistry, cls, getdata);
1639 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001640 return res;
1641}
1642
Eric Snow6d2cd902018-05-16 15:04:57 -04001643/* Cross-interpreter objects are looked up by exact match on the class.
1644 We can reassess this policy when we move from a global registry to a
1645 tp_* slot. */
1646
Eric Snow7f8bfc92018-01-29 18:23:44 -07001647crossinterpdatafunc
1648_PyCrossInterpreterData_Lookup(PyObject *obj)
1649{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001650 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001651 PyObject *cls = PyObject_Type(obj);
1652 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001653 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1654 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001655 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001656 _register_builtins_for_crossinterpreter_data(xidregistry);
1657 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001658 }
1659 for(; cur != NULL; cur = cur->next) {
1660 if (cur->cls == (PyTypeObject *)cls) {
1661 getdata = cur->getdata;
1662 break;
1663 }
1664 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001665 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001666 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001667 return getdata;
1668}
1669
1670/* cross-interpreter data for builtin types */
1671
Eric Snow6d2cd902018-05-16 15:04:57 -04001672struct _shared_bytes_data {
1673 char *bytes;
1674 Py_ssize_t len;
1675};
1676
Eric Snow7f8bfc92018-01-29 18:23:44 -07001677static PyObject *
1678_new_bytes_object(_PyCrossInterpreterData *data)
1679{
Eric Snow6d2cd902018-05-16 15:04:57 -04001680 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1681 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001682}
1683
1684static int
1685_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1686{
Eric Snow6d2cd902018-05-16 15:04:57 -04001687 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1688 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1689 return -1;
1690 }
1691 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001692 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001693 data->obj = obj; // Will be "released" (decref'ed) when data released.
1694 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001695 data->free = PyMem_Free;
1696 return 0;
1697}
1698
1699struct _shared_str_data {
1700 int kind;
1701 const void *buffer;
1702 Py_ssize_t len;
1703};
1704
1705static PyObject *
1706_new_str_object(_PyCrossInterpreterData *data)
1707{
1708 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1709 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1710}
1711
1712static int
1713_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1714{
1715 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1716 shared->kind = PyUnicode_KIND(obj);
1717 shared->buffer = PyUnicode_DATA(obj);
1718 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1719 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001720 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001721 data->obj = obj; // Will be "released" (decref'ed) when data released.
1722 data->new_object = _new_str_object;
1723 data->free = PyMem_Free;
1724 return 0;
1725}
1726
1727static PyObject *
1728_new_long_object(_PyCrossInterpreterData *data)
1729{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001730 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001731}
1732
1733static int
1734_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1735{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001736 /* Note that this means the size of shareable ints is bounded by
1737 * sys.maxsize. Hence on 32-bit architectures that is half the
1738 * size of maximum shareable ints on 64-bit.
1739 */
1740 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001741 if (value == -1 && PyErr_Occurred()) {
1742 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1743 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1744 }
1745 return -1;
1746 }
1747 data->data = (void *)value;
1748 data->obj = NULL;
1749 data->new_object = _new_long_object;
1750 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001751 return 0;
1752}
1753
1754static PyObject *
1755_new_none_object(_PyCrossInterpreterData *data)
1756{
1757 // XXX Singleton refcounts are problematic across interpreters...
1758 Py_INCREF(Py_None);
1759 return Py_None;
1760}
1761
1762static int
1763_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1764{
1765 data->data = NULL;
1766 // data->obj remains NULL
1767 data->new_object = _new_none_object;
1768 data->free = NULL; // There is nothing to free.
1769 return 0;
1770}
1771
1772static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001773_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001774{
1775 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001776 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001777 Py_FatalError("could not register None for cross-interpreter sharing");
1778 }
1779
Eric Snow6d2cd902018-05-16 15:04:57 -04001780 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001781 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001782 Py_FatalError("could not register int for cross-interpreter sharing");
1783 }
1784
Eric Snow7f8bfc92018-01-29 18:23:44 -07001785 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001786 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001787 Py_FatalError("could not register bytes for cross-interpreter sharing");
1788 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001789
1790 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001791 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001792 Py_FatalError("could not register str for cross-interpreter sharing");
1793 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001794}
1795
1796
Victor Stinner0b72b232020-03-12 23:18:39 +01001797_PyFrameEvalFunction
1798_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1799{
1800 return interp->eval_frame;
1801}
1802
1803
1804void
1805_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1806 _PyFrameEvalFunction eval_frame)
1807{
1808 interp->eval_frame = eval_frame;
1809}
1810
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001811#ifdef __cplusplus
1812}
1813#endif