blob: c8b2530f68dfe011bf34e99a7b4ebc18c4e9383d [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 Stinner41010182020-12-26 01:45:43 +01007#include "pycore_object.h" // _PyType_InitCache()
Victor Stinner0e427c62020-03-25 21:22:55 +01008#include "pycore_pyerrors.h"
9#include "pycore_pylifecycle.h"
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +020010#include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
Victor Stinnere5014be2020-04-14 17:52:15 +020011#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner71a35222020-03-26 22:46:14 +010012#include "pycore_sysmodule.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +000013
Tim Peters84705582004-10-10 02:47:33 +000014/* --------------------------------------------------------------------------
15CAUTION
16
Victor Stinner1a7425f2013-07-07 16:25:15 +020017Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
18number of these functions are advertised as safe to call when the GIL isn't
19held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
20debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
21to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000022-------------------------------------------------------------------------- */
23
Martin v. Löwisf0473d52001-07-18 16:17:16 +000024#ifdef HAVE_DLOPEN
25#ifdef HAVE_DLFCN_H
26#include <dlfcn.h>
27#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030028#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000029#define RTLD_LAZY 1
30#endif
31#endif
32
Benjamin Peterson43162b82012-04-13 11:58:27 -040033#ifdef __cplusplus
34extern "C" {
35#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000036
Victor Stinner10c8e6a2019-04-26 01:53:18 +020037#define _PyRuntimeGILState_GetThreadState(gilstate) \
38 ((PyThreadState*)_Py_atomic_load_relaxed(&(gilstate)->tstate_current))
39#define _PyRuntimeGILState_SetThreadState(gilstate, value) \
40 _Py_atomic_store_relaxed(&(gilstate)->tstate_current, \
41 (uintptr_t)(value))
42
43/* Forward declarations */
44static PyThreadState *_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate);
Victor Stinner9da74302019-11-20 11:17:17 +010045static void _PyThreadState_Delete(PyThreadState *tstate, int check_current);
Victor Stinner10c8e6a2019-04-26 01:53:18 +020046
47
Victor Stinner331a6a52019-05-27 16:39:22 +020048static PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010049_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060050{
Steve Dowerb82e17e2019-05-23 08:45:22 -070051 /* We preserve the hook across init, because there is
52 currently no public API to set it between runtime
53 initialization and interpreter initialization. */
54 void *open_code_hook = runtime->open_code_hook;
55 void *open_code_userdata = runtime->open_code_userdata;
56 _Py_AuditHookEntry *audit_hook_head = runtime->audit_hook_head;
Victor Stinner44bf57a2021-01-12 10:29:45 +010057 // bpo-42882: Preserve next_index value if Py_Initialize()/Py_Finalize()
58 // is called multiple times.
Ken Jin196d4de2021-02-05 06:08:03 +080059 Py_ssize_t unicode_next_index = runtime->unicode_ids.next_index;
Steve Dowerb82e17e2019-05-23 08:45:22 -070060
Eric Snow2ebc5ce2017-09-07 23:51:28 -060061 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010062
Steve Dowerb82e17e2019-05-23 08:45:22 -070063 runtime->open_code_hook = open_code_hook;
64 runtime->open_code_userdata = open_code_userdata;
65 runtime->audit_hook_head = audit_hook_head;
66
Victor Stinnerdab84232020-03-17 18:56:44 +010067 _PyEval_InitRuntimeState(&runtime->ceval);
Victor Stinner441b10c2019-09-28 04:28:35 +020068
Victor Stinner3c30a762019-10-01 10:56:37 +020069 PyPreConfig_InitPythonConfig(&runtime->preconfig);
Michael W. Hudson188d4362005-06-20 16:52:57 +000070
Eric Snow2ebc5ce2017-09-07 23:51:28 -060071 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080072
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090073 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
74 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080075 Py_tss_t initial = Py_tss_NEEDS_INIT;
76 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000077
Eric Snow2ebc5ce2017-09-07 23:51:28 -060078 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079 if (runtime->interpreters.mutex == NULL) {
Victor Stinnerba3d67c2020-12-26 00:41:46 +010080 return _PyStatus_NO_MEMORY();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060082 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070083
84 runtime->xidregistry.mutex = PyThread_allocate_lock();
85 if (runtime->xidregistry.mutex == NULL) {
Victor Stinnerba3d67c2020-12-26 00:41:46 +010086 return _PyStatus_NO_MEMORY();
Eric Snow7f8bfc92018-01-29 18:23:44 -070087 }
88
Eric Snow8479a342019-03-08 23:44:33 -070089 // Set it to the ID of the main thread of the main interpreter.
90 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070091
Victor Stinnerba3d67c2020-12-26 00:41:46 +010092 runtime->unicode_ids.lock = PyThread_allocate_lock();
93 if (runtime->unicode_ids.lock == NULL) {
94 return _PyStatus_NO_MEMORY();
95 }
Victor Stinner44bf57a2021-01-12 10:29:45 +010096 runtime->unicode_ids.next_index = unicode_next_index;
Victor Stinnerba3d67c2020-12-26 00:41:46 +010097
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 Stinnerba3d67c2020-12-26 00:41:46 +0100121#define FREE_LOCK(LOCK) \
122 if (LOCK != NULL) { \
123 PyThread_free_lock(LOCK); \
124 LOCK = NULL; \
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600125 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800126
Victor Stinnerba3d67c2020-12-26 00:41:46 +0100127 FREE_LOCK(runtime->interpreters.mutex);
128 FREE_LOCK(runtime->xidregistry.mutex);
129 FREE_LOCK(runtime->unicode_ids.lock);
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100130
Victor Stinnerba3d67c2020-12-26 00:41:46 +0100131#undef FREE_LOCK
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
Victor Stinner26881c82020-06-02 15:51:37 +0200137 newly created child processes do not share locks with the parent. */
138PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200139_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700140{
141 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200142 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700143
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200144 /* Force default allocator, since _PyRuntimeState_Fini() must
145 use the same allocator than this function. */
146 PyMemAllocatorEx old_alloc;
147 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
148
Victor Stinner26881c82020-06-02 15:51:37 +0200149 int reinit_interp = _PyThread_at_fork_reinit(&runtime->interpreters.mutex);
150 int reinit_main_id = _PyThread_at_fork_reinit(&runtime->interpreters.main->id_mutex);
151 int reinit_xidregistry = _PyThread_at_fork_reinit(&runtime->xidregistry.mutex);
Victor Stinnerba3d67c2020-12-26 00:41:46 +0100152 int reinit_unicode_ids = _PyThread_at_fork_reinit(&runtime->unicode_ids.lock);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200153
154 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
155
Victor Stinner26881c82020-06-02 15:51:37 +0200156 if (reinit_interp < 0
157 || reinit_main_id < 0
Victor Stinnerba3d67c2020-12-26 00:41:46 +0100158 || reinit_xidregistry < 0
159 || reinit_unicode_ids < 0)
Victor Stinner26881c82020-06-02 15:51:37 +0200160 {
161 return _PyStatus_ERR("Failed to reinitialize runtime locks");
Eric Snow8479a342019-03-08 23:44:33 -0700162
Eric Snow8479a342019-03-08 23:44:33 -0700163 }
Victor Stinner26881c82020-06-02 15:51:37 +0200164 return _PyStatus_OK();
Eric Snow8479a342019-03-08 23:44:33 -0700165}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900166#endif
Eric Snow8479a342019-03-08 23:44:33 -0700167
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200168#define HEAD_LOCK(runtime) \
169 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
170#define HEAD_UNLOCK(runtime) \
171 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700172
Victor Stinner8bb32302019-04-24 16:47:40 +0200173/* Forward declaration */
174static void _PyGILState_NoteThreadState(
175 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000176
Victor Stinner331a6a52019-05-27 16:39:22 +0200177PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600178_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700179{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200180 struct pyinterpreters *interpreters = &runtime->interpreters;
181 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100182
183 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
184 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200185 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100186 /* Force default allocator, since _PyRuntimeState_Fini() must
187 use the same allocator than this function. */
188 PyMemAllocatorEx old_alloc;
189 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
190
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200191 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100192
193 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
194
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200195 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200196 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800197 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600198 }
Victor Stinner5d926472018-03-06 14:31:37 +0100199
Victor Stinner331a6a52019-05-27 16:39:22 +0200200 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700201}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000202
203PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000204PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000205{
Victor Stinner71a35222020-03-26 22:46:14 +0100206 PyThreadState *tstate = _PyThreadState_GET();
207 /* tstate is NULL when Py_InitializeFromConfig() calls
208 PyInterpreterState_New() to create the main interpreter. */
209 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_New", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700210 return NULL;
211 }
212
Andy Lester7668a8b2020-03-24 23:26:44 -0500213 PyInterpreterState *interp = PyMem_RawCalloc(1, sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100214 if (interp == NULL) {
215 return NULL;
216 }
217
Eric Snow4c6955e2018-02-16 18:53:40 -0700218 interp->id_refcount = -1;
Victor Stinner022be022019-05-22 23:58:50 +0200219
Victor Stinner71a35222020-03-26 22:46:14 +0100220 /* Don't get runtime from tstate since tstate can be NULL */
Victor Stinner01b1cc12019-11-20 02:27:56 +0100221 _PyRuntimeState *runtime = &_PyRuntime;
222 interp->runtime = runtime;
223
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200224 if (_PyEval_InitState(&interp->ceval) < 0) {
225 goto out_of_memory;
226 }
227
Victor Stinner72474072019-11-20 12:25:50 +0100228 _PyGC_InitState(&interp->gc);
Victor Stinner8462a492019-10-01 12:06:16 +0200229 PyConfig_InitPythonConfig(&interp->config);
Victor Stinner41010182020-12-26 01:45:43 +0100230 _PyType_InitCache(interp);
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 Stinnereba5bf22020-10-30 22:51:02 +0100284static void
285interpreter_clear(PyInterpreterState *interp, PyThreadState *tstate)
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 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_Clear", NULL) < 0) {
290 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700291 }
292
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200293 HEAD_LOCK(runtime);
294 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200296 }
297 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700298
299 Py_CLEAR(interp->audit_hooks);
300
Victor Stinner331a6a52019-05-27 16:39:22 +0200301 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 Py_CLEAR(interp->codec_search_path);
303 Py_CLEAR(interp->codec_search_cache);
304 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700305 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 Py_CLEAR(interp->modules_by_index);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200307 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400308 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300309 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600310 Py_CLEAR(interp->dict);
Brandt Bucher145bf262021-02-26 14:51:55 -0800311 Py_CLEAR(interp->map_abc);
312 Py_CLEAR(interp->seq_abc);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200313#ifdef HAVE_FORK
314 Py_CLEAR(interp->before_forkers);
315 Py_CLEAR(interp->after_forkers_parent);
316 Py_CLEAR(interp->after_forkers_child);
317#endif
Victor Stinnerfd957c12020-11-03 18:07:15 +0100318
319 _PyAST_Fini(interp);
320 _PyWarnings_Fini(interp);
Victor Stinnerb8fa1352020-12-15 14:34:19 +0100321 _PyAtExit_Fini(interp);
Victor Stinnerfd957c12020-11-03 18:07:15 +0100322
323 // All Python types must be destroyed before the last GC collection. Python
324 // types create a reference cycle to themselves in their in their
325 // PyTypeObject.tp_mro member (the tuple contains the type).
Victor Stinnereba5bf22020-10-30 22:51:02 +0100326
327 /* Last garbage collection on this interpreter */
328 _PyGC_CollectNoFail(tstate);
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100329 _PyGC_Fini(interp);
Victor Stinnereba5bf22020-10-30 22:51:02 +0100330
Hai Shi8ecc0c42020-08-13 05:23:30 +0800331 /* We don't clear sysdict and builtins until the end of this function.
332 Because clearing other attributes can execute arbitrary Python code
333 which requires sysdict and builtins. */
334 PyDict_Clear(interp->sysdict);
335 PyDict_Clear(interp->builtins);
336 Py_CLEAR(interp->sysdict);
337 Py_CLEAR(interp->builtins);
338
Eric Snow5be45a62019-03-08 22:47:07 -0700339 // XXX Once we have one allocator per interpreter (i.e.
340 // per-interpreter GC) we must ensure that all of the interpreter's
341 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000342}
343
344
Victor Stinnereba5bf22020-10-30 22:51:02 +0100345void
346PyInterpreterState_Clear(PyInterpreterState *interp)
347{
348 // Use the current Python thread state to call audit hooks and to collect
349 // garbage. It can be different than the current Python thread state
350 // of 'interp'.
351 PyThreadState *current_tstate = _PyThreadState_GET();
352
353 interpreter_clear(interp, current_tstate);
354}
355
356
357void
358_PyInterpreterState_Clear(PyThreadState *tstate)
359{
360 interpreter_clear(tstate->interp, tstate);
361}
362
363
Guido van Rossum25ce5661997-08-02 03:10:38 +0000364static void
Victor Stinner9da74302019-11-20 11:17:17 +0100365zapthreads(PyInterpreterState *interp, int check_current)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000366{
Victor Stinner9da74302019-11-20 11:17:17 +0100367 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 /* No need to lock the mutex here because this should only happen
369 when the threads are all really dead (XXX famous last words). */
Victor Stinner9da74302019-11-20 11:17:17 +0100370 while ((tstate = interp->tstate_head) != NULL) {
371 _PyThreadState_Delete(tstate, check_current);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000373}
374
375
Victor Stinner01b1cc12019-11-20 02:27:56 +0100376void
377PyInterpreterState_Delete(PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200378{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100379 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200380 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner9da74302019-11-20 11:17:17 +0100381 zapthreads(interp, 0);
382
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200383 _PyEval_FiniState(&interp->ceval);
384
Victor Stinner9da74302019-11-20 11:17:17 +0100385 /* Delete current thread. After this, many C API calls become crashy. */
386 _PyThreadState_Swap(&runtime->gilstate, NULL);
387
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200388 HEAD_LOCK(runtime);
389 PyInterpreterState **p;
390 for (p = &interpreters->head; ; p = &(*p)->next) {
391 if (*p == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100392 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200393 }
394 if (*p == interp) {
395 break;
396 }
397 }
398 if (interp->tstate_head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100399 Py_FatalError("remaining threads");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200400 }
401 *p = interp->next;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200402
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200403 if (interpreters->main == interp) {
404 interpreters->main = NULL;
405 if (interpreters->head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100406 Py_FatalError("remaining subinterpreters");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200407 }
408 }
409 HEAD_UNLOCK(runtime);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200410
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200411 if (interp->id_mutex != NULL) {
412 PyThread_free_lock(interp->id_mutex);
413 }
414 PyMem_RawFree(interp);
415}
416
417
Victor Stinner26881c82020-06-02 15:51:37 +0200418#ifdef HAVE_FORK
Eric Snow59032962018-09-14 14:17:20 -0700419/*
420 * Delete all interpreter states except the main interpreter. If there
421 * is a current interpreter state, it *must* be the main interpreter.
422 */
Victor Stinner26881c82020-06-02 15:51:37 +0200423PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200424_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700425{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200426 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200427 struct pyinterpreters *interpreters = &runtime->interpreters;
428
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200429 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200430 if (tstate != NULL && tstate->interp != interpreters->main) {
Victor Stinner26881c82020-06-02 15:51:37 +0200431 return _PyStatus_ERR("not main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700432 }
433
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200434 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200435 PyInterpreterState *interp = interpreters->head;
436 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100437 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200438 if (interp == interpreters->main) {
439 interpreters->main->next = NULL;
440 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100441 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700442 continue;
443 }
444
Victor Stinner01b1cc12019-11-20 02:27:56 +0100445 PyInterpreterState_Clear(interp); // XXX must activate?
Victor Stinner9da74302019-11-20 11:17:17 +0100446 zapthreads(interp, 1);
Eric Snow59032962018-09-14 14:17:20 -0700447 if (interp->id_mutex != NULL) {
448 PyThread_free_lock(interp->id_mutex);
449 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100450 PyInterpreterState *prev_interp = interp;
451 interp = interp->next;
452 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700453 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200454 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700455
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200456 if (interpreters->head == NULL) {
Victor Stinner26881c82020-06-02 15:51:37 +0200457 return _PyStatus_ERR("missing main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700458 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200459 _PyThreadState_Swap(gilstate, tstate);
Victor Stinner26881c82020-06-02 15:51:37 +0200460 return _PyStatus_OK();
Eric Snow59032962018-09-14 14:17:20 -0700461}
Victor Stinner26881c82020-06-02 15:51:37 +0200462#endif
Eric Snow59032962018-09-14 14:17:20 -0700463
464
Victor Stinnercaba55b2018-08-03 15:33:52 +0200465PyInterpreterState *
Victor Stinnerbe793732020-03-13 18:15:33 +0100466PyInterpreterState_Get(void)
Victor Stinnercaba55b2018-08-03 15:33:52 +0200467{
Victor Stinner50b48572018-11-01 01:51:40 +0100468 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200469 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200470 PyInterpreterState *interp = tstate->interp;
471 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100472 Py_FatalError("no current interpreter");
Victor Stinnercaba55b2018-08-03 15:33:52 +0200473 }
474 return interp;
475}
476
477
Eric Snowe3774162017-05-22 19:46:40 -0700478int64_t
479PyInterpreterState_GetID(PyInterpreterState *interp)
480{
481 if (interp == NULL) {
482 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
483 return -1;
484 }
485 return interp->id;
486}
487
488
Eric Snow5be45a62019-03-08 22:47:07 -0700489static PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200490interp_look_up_id(_PyRuntimeState *runtime, int64_t requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700491{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200492 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100493 while (interp != NULL) {
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200494 int64_t id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700495 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100496 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700497 }
498 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100499 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700500 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100501 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700502 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100503 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700504}
505
Eric Snow5be45a62019-03-08 22:47:07 -0700506PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200507_PyInterpreterState_LookUpID(int64_t requested_id)
Eric Snow5be45a62019-03-08 22:47:07 -0700508{
509 PyInterpreterState *interp = NULL;
510 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200511 _PyRuntimeState *runtime = &_PyRuntime;
512 HEAD_LOCK(runtime);
513 interp = interp_look_up_id(runtime, requested_id);
514 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700515 }
516 if (interp == NULL && !PyErr_Occurred()) {
517 PyErr_Format(PyExc_RuntimeError,
518 "unrecognized interpreter ID %lld", requested_id);
519 }
520 return interp;
521}
522
Eric Snow4c6955e2018-02-16 18:53:40 -0700523
524int
525_PyInterpreterState_IDInitref(PyInterpreterState *interp)
526{
527 if (interp->id_mutex != NULL) {
528 return 0;
529 }
530 interp->id_mutex = PyThread_allocate_lock();
531 if (interp->id_mutex == NULL) {
532 PyErr_SetString(PyExc_RuntimeError,
533 "failed to create init interpreter ID mutex");
534 return -1;
535 }
536 interp->id_refcount = 0;
537 return 0;
538}
539
540
541void
542_PyInterpreterState_IDIncref(PyInterpreterState *interp)
543{
544 if (interp->id_mutex == NULL) {
545 return;
546 }
547 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
548 interp->id_refcount += 1;
549 PyThread_release_lock(interp->id_mutex);
550}
551
552
553void
554_PyInterpreterState_IDDecref(PyInterpreterState *interp)
555{
556 if (interp->id_mutex == NULL) {
557 return;
558 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200559 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700560 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
561 assert(interp->id_refcount != 0);
562 interp->id_refcount -= 1;
563 int64_t refcount = interp->id_refcount;
564 PyThread_release_lock(interp->id_mutex);
565
Eric Snowc11183c2019-03-15 16:35:46 -0600566 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700567 // XXX Using the "head" thread isn't strictly correct.
568 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
569 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200570 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700571 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200572 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700573 }
574}
575
Eric Snowc11183c2019-03-15 16:35:46 -0600576int
577_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
578{
579 return interp->requires_idref;
580}
581
582void
583_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
584{
585 interp->requires_idref = required ? 1 : 0;
586}
587
Eric Snowc11183c2019-03-15 16:35:46 -0600588PyObject *
589_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
590{
591 if (interp->modules == NULL) {
592 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
593 return NULL;
594 }
595 return PyMapping_GetItemString(interp->modules, "__main__");
596}
597
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600598PyObject *
599PyInterpreterState_GetDict(PyInterpreterState *interp)
600{
601 if (interp->dict == NULL) {
602 interp->dict = PyDict_New();
603 if (interp->dict == NULL) {
604 PyErr_Clear();
605 }
606 }
607 /* Returning NULL means no per-interpreter dict is available. */
608 return interp->dict;
609}
610
Victor Stinner45b9be52010-03-03 23:28:07 +0000611static PyThreadState *
612new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000613{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100614 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200615 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200616 if (tstate == NULL) {
617 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000619
Victor Stinner8bb32302019-04-24 16:47:40 +0200620 tstate->interp = interp;
621
622 tstate->frame = NULL;
623 tstate->recursion_depth = 0;
Mark Shannon4e7a69b2020-12-02 13:30:55 +0000624 tstate->recursion_headroom = 0;
Victor Stinner8bb32302019-04-24 16:47:40 +0200625 tstate->stackcheck_counter = 0;
626 tstate->tracing = 0;
627 tstate->use_tracing = 0;
628 tstate->gilstate_counter = 0;
629 tstate->async_exc = NULL;
630 tstate->thread_id = PyThread_get_thread_ident();
631
632 tstate->dict = NULL;
633
634 tstate->curexc_type = NULL;
635 tstate->curexc_value = NULL;
636 tstate->curexc_traceback = NULL;
637
638 tstate->exc_state.exc_type = NULL;
639 tstate->exc_state.exc_value = NULL;
640 tstate->exc_state.exc_traceback = NULL;
641 tstate->exc_state.previous_item = NULL;
642 tstate->exc_info = &tstate->exc_state;
643
644 tstate->c_profilefunc = NULL;
645 tstate->c_tracefunc = NULL;
646 tstate->c_profileobj = NULL;
647 tstate->c_traceobj = NULL;
648
649 tstate->trash_delete_nesting = 0;
650 tstate->trash_delete_later = NULL;
651 tstate->on_delete = NULL;
652 tstate->on_delete_data = NULL;
653
654 tstate->coroutine_origin_tracking_depth = 0;
655
Victor Stinner8bb32302019-04-24 16:47:40 +0200656 tstate->async_gen_firstiter = NULL;
657 tstate->async_gen_finalizer = NULL;
658
659 tstate->context = NULL;
660 tstate->context_ver = 1;
661
Victor Stinner8bb32302019-04-24 16:47:40 +0200662 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100663 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200664 }
665
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200666 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100667 tstate->id = ++interp->tstate_next_unique_id;
Victor Stinner8bb32302019-04-24 16:47:40 +0200668 tstate->prev = NULL;
669 tstate->next = interp->tstate_head;
670 if (tstate->next)
671 tstate->next->prev = tstate;
672 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200673 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000676}
677
Victor Stinner45b9be52010-03-03 23:28:07 +0000678PyThreadState *
679PyThreadState_New(PyInterpreterState *interp)
680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000682}
683
684PyThreadState *
685_PyThreadState_Prealloc(PyInterpreterState *interp)
686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000688}
689
690void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100691_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000692{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100693 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000694}
695
Martin v. Löwis1a214512008-06-11 05:26:20 +0000696PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200697PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000698{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200699 Py_ssize_t index = module->m_base.m_index;
Victor Stinner81a7be32020-04-14 15:14:01 +0200700 PyInterpreterState *state = _PyInterpreterState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000702 if (module->m_slots) {
703 return NULL;
704 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 if (index == 0)
706 return NULL;
707 if (state->modules_by_index == NULL)
708 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200709 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 return NULL;
711 res = PyList_GET_ITEM(state->modules_by_index, index);
712 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000713}
714
715int
Victor Stinner82c83bd2019-11-22 18:52:27 +0100716_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000717{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300718 if (!def) {
Victor Stinner71a35222020-03-26 22:46:14 +0100719 assert(_PyErr_Occurred(tstate));
Berker Peksag4b7b5652016-08-22 18:05:56 +0300720 return -1;
721 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000722 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100723 _PyErr_SetString(tstate,
724 PyExc_SystemError,
725 "PyState_AddModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000726 return -1;
727 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100728
729 PyInterpreterState *interp = tstate->interp;
730 if (!interp->modules_by_index) {
731 interp->modules_by_index = PyList_New(0);
732 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100734 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100736
737 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
738 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100740 }
741 }
742
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100744 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000746}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000747
Martin v. Löwis7800f752012-06-22 12:20:55 +0200748int
749PyState_AddModule(PyObject* module, struct PyModuleDef* def)
750{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200751 if (!def) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100752 Py_FatalError("module definition is NULL");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200753 return -1;
754 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100755
756 PyThreadState *tstate = _PyThreadState_GET();
757 PyInterpreterState *interp = tstate->interp;
758 Py_ssize_t index = def->m_base.m_index;
759 if (interp->modules_by_index &&
760 index < PyList_GET_SIZE(interp->modules_by_index) &&
761 module == PyList_GET_ITEM(interp->modules_by_index, index))
762 {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100763 _Py_FatalErrorFormat(__func__, "module %p already added", module);
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100764 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200765 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100766 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200767}
768
769int
770PyState_RemoveModule(struct PyModuleDef* def)
771{
Victor Stinner71a35222020-03-26 22:46:14 +0100772 PyThreadState *tstate = _PyThreadState_GET();
773 PyInterpreterState *interp = tstate->interp;
774
Nick Coghland5cacbb2015-05-23 22:24:10 +1000775 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100776 _PyErr_SetString(tstate,
777 PyExc_SystemError,
778 "PyState_RemoveModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000779 return -1;
780 }
Victor Stinner71a35222020-03-26 22:46:14 +0100781
782 Py_ssize_t index = def->m_base.m_index;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200783 if (index == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100784 Py_FatalError("invalid module index");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200785 }
Victor Stinner71a35222020-03-26 22:46:14 +0100786 if (interp->modules_by_index == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100787 Py_FatalError("Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200788 }
Victor Stinner71a35222020-03-26 22:46:14 +0100789 if (index > PyList_GET_SIZE(interp->modules_by_index)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100790 Py_FatalError("Module index out of bounds.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200791 }
Victor Stinner71a35222020-03-26 22:46:14 +0100792
Zackery Spytz2a893432018-12-05 00:14:00 -0700793 Py_INCREF(Py_None);
Victor Stinner71a35222020-03-26 22:46:14 +0100794 return PyList_SetItem(interp->modules_by_index, index, Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200795}
796
Victor Stinner048a3562020-11-05 00:45:56 +0100797// Used by finalize_modules()
Antoine Pitrou40322e62013-08-11 00:30:09 +0200798void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200799_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200800{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200801 if (!interp->modules_by_index) {
802 return;
803 }
804
805 Py_ssize_t i;
806 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
807 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
808 if (PyModule_Check(m)) {
809 /* cleanup the saved copy of module dicts */
810 PyModuleDef *md = PyModule_GetDef(m);
811 if (md) {
812 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200813 }
814 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200815 }
816
817 /* Setting modules_by_index to NULL could be dangerous, so we
818 clear the list instead. */
819 if (PyList_SetSlice(interp->modules_by_index,
820 0, PyList_GET_SIZE(interp->modules_by_index),
821 NULL)) {
822 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200823 }
824}
825
Guido van Rossuma027efa1997-05-05 20:56:21 +0000826void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000827PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000828{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200829 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200830
Victor Stinner5804f872020-03-24 16:32:26 +0100831 if (verbose && tstate->frame != NULL) {
832 /* bpo-20526: After the main thread calls
833 _PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
834 exit when trying to take the GIL. If a thread exit in the middle of
835 _PyEval_EvalFrameDefault(), tstate->frame is not reset to its
836 previous value. It is more likely with daemon threads, but it can
837 happen with regular threads if threading._shutdown() fails
838 (ex: interrupted by CTRL+C). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 fprintf(stderr,
840 "PyThreadState_Clear: warning: thread still has a frame\n");
Victor Stinner5804f872020-03-24 16:32:26 +0100841 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000842
Victor Stinner5804f872020-03-24 16:32:26 +0100843 /* Don't clear tstate->frame: it is a borrowed reference */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 Py_CLEAR(tstate->dict);
846 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 Py_CLEAR(tstate->curexc_type);
849 Py_CLEAR(tstate->curexc_value);
850 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000851
Mark Shannonae3087c2017-10-22 22:41:51 +0100852 Py_CLEAR(tstate->exc_state.exc_type);
853 Py_CLEAR(tstate->exc_state.exc_value);
854 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300855
Mark Shannonae3087c2017-10-22 22:41:51 +0100856 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200857 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100858 fprintf(stderr,
859 "PyThreadState_Clear: warning: thread still has a generator\n");
860 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000861
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 tstate->c_profilefunc = NULL;
863 tstate->c_tracefunc = NULL;
864 Py_CLEAR(tstate->c_profileobj);
865 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400866
Yury Selivanoveb636452016-09-08 22:01:51 -0700867 Py_CLEAR(tstate->async_gen_firstiter);
868 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500869
870 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100871
872 if (tstate->on_delete != NULL) {
873 tstate->on_delete(tstate->on_delete_data);
874 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000875}
876
877
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300878/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000879static void
Victor Stinner9da74302019-11-20 11:17:17 +0100880tstate_delete_common(PyThreadState *tstate,
881 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000882{
Victor Stinner3026cad2020-06-01 16:02:40 +0200883 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200884 PyInterpreterState *interp = tstate->interp;
885 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100886 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200887 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100888 _PyRuntimeState *runtime = interp->runtime;
889
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200890 HEAD_LOCK(runtime);
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100891 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200892 tstate->prev->next = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100893 }
894 else {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200895 interp->tstate_head = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100896 }
897 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200898 tstate->next->prev = tstate->prev;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100899 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200900 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100901
Victor Stinner9da74302019-11-20 11:17:17 +0100902 if (gilstate->autoInterpreterState &&
903 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
904 {
905 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
906 }
907}
908
909
910static void
911_PyThreadState_Delete(PyThreadState *tstate, int check_current)
912{
913 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
914 if (check_current) {
915 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100916 _Py_FatalErrorFormat(__func__, "tstate %p is still current", tstate);
Victor Stinner9da74302019-11-20 11:17:17 +0100917 }
918 }
919 tstate_delete_common(tstate, gilstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100920 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000921}
922
923
Victor Stinner01b1cc12019-11-20 02:27:56 +0100924void
925PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000926{
Victor Stinner9da74302019-11-20 11:17:17 +0100927 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200928}
929
930
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300931void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100932_PyThreadState_DeleteCurrent(PyThreadState *tstate)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200933{
Victor Stinner3026cad2020-06-01 16:02:40 +0200934 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100935 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner9da74302019-11-20 11:17:17 +0100936 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200937 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100938 _PyEval_ReleaseLock(tstate);
939 PyMem_RawFree(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000940}
Guido van Rossum29757862001-01-23 01:46:06 +0000941
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300942void
943PyThreadState_DeleteCurrent(void)
944{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100945 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
946 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
947 _PyThreadState_DeleteCurrent(tstate);
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300948}
949
Guido van Rossum29757862001-01-23 01:46:06 +0000950
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200951/*
952 * Delete all thread states except the one passed as argument.
953 * Note that, if there is a current thread state, it *must* be the one
954 * passed as argument. Also, this won't touch any other interpreters
955 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000956 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200957 */
958void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200959_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200960{
961 PyInterpreterState *interp = tstate->interp;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100962
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200963 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200964 /* Remove all thread states, except tstate, from the linked list of
965 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200966 without holding the lock. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100967 PyThreadState *list = interp->tstate_head;
968 if (list == tstate) {
969 list = tstate->next;
970 }
971 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200972 tstate->prev->next = tstate->next;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100973 }
974 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200975 tstate->next->prev = tstate->prev;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100976 }
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200977 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200978 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200979 HEAD_UNLOCK(runtime);
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100980
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200981 /* Clear and deallocate all stale thread states. Even if this
982 executes Python code, we should be safe since it executes
983 in the current thread, not one of the stale threads. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100984 PyThreadState *p, *next;
985 for (p = list; p; p = next) {
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200986 next = p->next;
987 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200988 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200989 }
990}
991
992
Victor Stinnere838a932020-05-05 19:56:48 +0200993#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
994PyThreadState*
995_PyThreadState_GetTSS(void) {
996 return PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
997}
998#endif
999
1000
Guido van Rossuma027efa1997-05-05 20:56:21 +00001001PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001002_PyThreadState_UncheckedGet(void)
1003{
Victor Stinner50b48572018-11-01 01:51:40 +01001004 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001005}
1006
1007
1008PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001009PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +00001010{
Victor Stinner50b48572018-11-01 01:51:40 +01001011 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +02001012 _Py_EnsureTstateNotNULL(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +00001014}
1015
1016
Victor Stinner09532fe2019-05-10 23:39:09 +02001017PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001018_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +00001019{
Victor Stinnere838a932020-05-05 19:56:48 +02001020#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1021 PyThreadState *oldts = _PyThreadState_GetTSS();
1022#else
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001023 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Victor Stinnere838a932020-05-05 19:56:48 +02001024#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +00001025
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001026 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 /* It should not be possible for more than one thread state
1028 to be used for a thread. Check this the best we can in debug
1029 builds.
1030 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02001031#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 if (newts) {
1033 /* This can be called from PyEval_RestoreThread(). Similar
1034 to it, we need to ensure errno doesn't change.
1035 */
1036 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001037 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 if (check && check->interp == newts->interp && check != newts)
1039 Py_FatalError("Invalid thread state for this thread");
1040 errno = err;
1041 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001042#endif
Victor Stinnere838a932020-05-05 19:56:48 +02001043#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1044 PyThread_tss_set(&gilstate->autoTSSkey, newts);
1045#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +00001047}
Guido van Rossumede04391998-04-10 20:18:25 +00001048
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001049PyThreadState *
1050PyThreadState_Swap(PyThreadState *newts)
1051{
1052 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
1053}
1054
Guido van Rossumede04391998-04-10 20:18:25 +00001055/* An extension mechanism to store arbitrary additional per-thread state.
1056 PyThreadState_GetDict() returns a dictionary that can be used to hold such
1057 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001058 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
1059 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +00001060
1061PyObject *
Victor Stinner0e427c62020-03-25 21:22:55 +01001062_PyThreadState_GetDict(PyThreadState *tstate)
1063{
1064 assert(tstate != NULL);
1065 if (tstate->dict == NULL) {
1066 tstate->dict = PyDict_New();
1067 if (tstate->dict == NULL) {
1068 _PyErr_Clear(tstate);
1069 }
1070 }
1071 return tstate->dict;
1072}
1073
1074
1075PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001076PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +00001077{
Victor Stinner50b48572018-11-01 01:51:40 +01001078 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner0e427c62020-03-25 21:22:55 +01001079 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 }
Victor Stinner0e427c62020-03-25 21:22:55 +01001082 return _PyThreadState_GetDict(tstate);
Guido van Rossumede04391998-04-10 20:18:25 +00001083}
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001084
1085
Victor Stinner8fb02b62020-03-13 23:38:08 +01001086PyInterpreterState *
1087PyThreadState_GetInterpreter(PyThreadState *tstate)
1088{
1089 assert(tstate != NULL);
Victor Stinner8fb02b62020-03-13 23:38:08 +01001090 return tstate->interp;
1091}
1092
1093
Victor Stinner4386b902020-04-29 03:01:43 +02001094PyFrameObject*
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001095PyThreadState_GetFrame(PyThreadState *tstate)
1096{
1097 assert(tstate != NULL);
Victor Stinner4386b902020-04-29 03:01:43 +02001098 PyFrameObject *frame = tstate->frame;
1099 Py_XINCREF(frame);
1100 return frame;
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001101}
1102
1103
Victor Stinner5c3cda02020-03-25 21:23:53 +01001104uint64_t
1105PyThreadState_GetID(PyThreadState *tstate)
1106{
1107 assert(tstate != NULL);
1108 return tstate->id;
1109}
1110
1111
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001112/* Asynchronously raise an exception in a thread.
1113 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001114 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001115 to call this, or use ctypes. Must be called with the GIL held.
1116 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1117 match any known thread id). Can be called with exc=NULL to clear an
1118 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001119
1120int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001121PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1122{
Victor Stinner09532fe2019-05-10 23:39:09 +02001123 _PyRuntimeState *runtime = &_PyRuntime;
1124 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 /* Although the GIL is held, a few C API functions can be called
1127 * without the GIL held, and in particular some that create and
1128 * destroy thread and interpreter states. Those can mutate the
1129 * list of thread states we're traversing, so to prevent that we lock
1130 * head_mutex for the duration.
1131 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001132 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001133 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1134 if (tstate->thread_id != id) {
1135 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001137
1138 /* Tricky: we need to decref the current value
1139 * (if any) in tstate->async_exc, but that can in turn
1140 * allow arbitrary Python code to run, including
1141 * perhaps calls to this function. To prevent
1142 * deadlock, we need to release head_mutex before
1143 * the decref.
1144 */
1145 PyObject *old_exc = tstate->async_exc;
1146 Py_XINCREF(exc);
1147 tstate->async_exc = exc;
1148 HEAD_UNLOCK(runtime);
1149
1150 Py_XDECREF(old_exc);
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001151 _PyEval_SignalAsyncExc(tstate->interp);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001152 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001154 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001156}
1157
1158
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001159/* Routines for advanced debuggers, requested by David Beazley.
1160 Don't use unless you know what you are doing! */
1161
1162PyInterpreterState *
1163PyInterpreterState_Head(void)
1164{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001165 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001166}
1167
1168PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001169PyInterpreterState_Main(void)
1170{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001171 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001172}
1173
1174PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001175PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001177}
1178
1179PyThreadState *
1180PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001182}
1183
1184PyThreadState *
1185PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001187}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001188
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001189/* The implementation of sys._current_frames(). This is intended to be
1190 called with the GIL held, as it will be when called via
1191 sys._current_frames(). It's possible it would work fine even without
1192 the GIL held, but haven't thought enough about that.
1193*/
1194PyObject *
1195_PyThread_CurrentFrames(void)
1196{
Victor Stinner71a35222020-03-26 22:46:14 +01001197 PyThreadState *tstate = _PyThreadState_GET();
1198 if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001199 return NULL;
1200 }
1201
Victor Stinner71a35222020-03-26 22:46:14 +01001202 PyObject *result = PyDict_New();
1203 if (result == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 return NULL;
Victor Stinner71a35222020-03-26 22:46:14 +01001205 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 /* for i in all interpreters:
1208 * for t in all of i's thread states:
1209 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001210 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 * need to grab head_mutex for the duration.
1212 */
Victor Stinner71a35222020-03-26 22:46:14 +01001213 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001214 HEAD_LOCK(runtime);
Victor Stinner71a35222020-03-26 22:46:14 +01001215 PyInterpreterState *i;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001216 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 PyThreadState *t;
1218 for (t = i->tstate_head; t != NULL; t = t->next) {
Victor Stinner4386b902020-04-29 03:01:43 +02001219 PyFrameObject *frame = t->frame;
Victor Stinner71a35222020-03-26 22:46:14 +01001220 if (frame == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 continue;
Victor Stinner71a35222020-03-26 22:46:14 +01001222 }
1223 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1224 if (id == NULL) {
1225 goto fail;
1226 }
1227 int stat = PyDict_SetItem(result, id, (PyObject *)frame);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 Py_DECREF(id);
Victor Stinner71a35222020-03-26 22:46:14 +01001229 if (stat < 0) {
1230 goto fail;
1231 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 }
1233 }
Victor Stinner71a35222020-03-26 22:46:14 +01001234 goto done;
1235
1236fail:
1237 Py_CLEAR(result);
1238
1239done:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001240 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001242}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001243
Julien Danjou64366fa2020-11-02 15:16:25 +01001244PyObject *
1245_PyThread_CurrentExceptions(void)
1246{
1247 PyThreadState *tstate = _PyThreadState_GET();
1248
1249 _Py_EnsureTstateNotNULL(tstate);
1250
1251 if (_PySys_Audit(tstate, "sys._current_exceptions", NULL) < 0) {
1252 return NULL;
1253 }
1254
1255 PyObject *result = PyDict_New();
1256 if (result == NULL) {
1257 return NULL;
1258 }
1259
1260 /* for i in all interpreters:
1261 * for t in all of i's thread states:
1262 * if t's frame isn't NULL, map t's id to its frame
1263 * Because these lists can mutate even when the GIL is held, we
1264 * need to grab head_mutex for the duration.
1265 */
1266 _PyRuntimeState *runtime = tstate->interp->runtime;
1267 HEAD_LOCK(runtime);
1268 PyInterpreterState *i;
1269 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
1270 PyThreadState *t;
1271 for (t = i->tstate_head; t != NULL; t = t->next) {
1272 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(t);
1273 if (err_info == NULL) {
1274 continue;
1275 }
1276 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1277 if (id == NULL) {
1278 goto fail;
1279 }
1280 PyObject *exc_info = PyTuple_Pack(
1281 3,
1282 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
1283 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
1284 err_info->exc_traceback != NULL ? err_info->exc_traceback : Py_None);
1285 if (exc_info == NULL) {
1286 Py_DECREF(id);
1287 goto fail;
1288 }
1289 int stat = PyDict_SetItem(result, id, exc_info);
1290 Py_DECREF(id);
1291 Py_DECREF(exc_info);
1292 if (stat < 0) {
1293 goto fail;
1294 }
1295 }
1296 }
1297 goto done;
1298
1299fail:
1300 Py_CLEAR(result);
1301
1302done:
1303 HEAD_UNLOCK(runtime);
1304 return result;
1305}
1306
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001307/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001308
1309/* Keep this as a static, as it is not reliable! It can only
1310 ever be compared to the state for the *current* thread.
1311 * If not equal, then it doesn't matter that the actual
1312 value may change immediately after comparison, as it can't
1313 possibly change to the current thread's state.
1314 * If equal, then the current thread holds the lock, so the value can't
1315 change until we yield the lock.
1316*/
1317static int
1318PyThreadState_IsCurrent(PyThreadState *tstate)
1319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001321 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001322 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1323 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001324}
1325
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001326/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001327 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001328*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001329PyStatus
Victor Stinner87f649a2021-03-10 20:00:46 +01001330_PyGILState_Init(_PyRuntimeState *runtime)
1331{
1332 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1333 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
1334 return _PyStatus_NO_MEMORY();
1335 }
1336 // PyThreadState_New() calls _PyGILState_NoteThreadState() which does
1337 // nothing before autoInterpreterState is set.
1338 assert(gilstate->autoInterpreterState == NULL);
1339 return _PyStatus_OK();
1340}
1341
1342
1343PyStatus
1344_PyGILState_SetTstate(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001345{
Victor Stinner101bf692021-02-19 13:33:31 +01001346 if (!_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001347 /* Currently, PyGILState is shared by all interpreters. The main
1348 * interpreter is responsible to initialize it. */
1349 return _PyStatus_OK();
1350 }
1351
Victor Stinner8bb32302019-04-24 16:47:40 +02001352 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001353 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001354 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001355
Victor Stinner01b1cc12019-11-20 02:27:56 +01001356 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001357
Victor Stinnerb45d2592019-06-20 00:05:23 +02001358 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001359 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1360 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001361
Victor Stinner8bb32302019-04-24 16:47:40 +02001362 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001363 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001364}
1365
Victor Stinner861d9ab2016-03-16 22:45:24 +01001366PyInterpreterState *
1367_PyGILState_GetInterpreterStateUnsafe(void)
1368{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001369 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001370}
1371
Tim Peters19717fa2004-10-09 17:38:29 +00001372void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001373_PyGILState_Fini(PyInterpreterState *interp)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001374{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001375 struct _gilstate_runtime_state *gilstate = &interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001376 PyThread_tss_delete(&gilstate->autoTSSkey);
1377 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001378}
1379
Victor Stinner26881c82020-06-02 15:51:37 +02001380#ifdef HAVE_FORK
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001381/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001382 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001383 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001384 */
Victor Stinner26881c82020-06-02 15:51:37 +02001385PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001386_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001387{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001388 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001389 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001390
1391 PyThread_tss_delete(&gilstate->autoTSSkey);
1392 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner26881c82020-06-02 15:51:37 +02001393 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001394 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001395
Charles-François Natalia233df82011-11-22 19:49:51 +01001396 /* If the thread had an associated auto thread state, reassociate it with
1397 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001398 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001399 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001400 {
Victor Stinner26881c82020-06-02 15:51:37 +02001401 return _PyStatus_ERR("failed to set autoTSSkey");
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001402 }
Victor Stinner26881c82020-06-02 15:51:37 +02001403 return _PyStatus_OK();
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001404}
Victor Stinner26881c82020-06-02 15:51:37 +02001405#endif
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001406
Michael W. Hudson188d4362005-06-20 16:52:57 +00001407/* When a thread state is created for a thread by some mechanism other than
1408 PyGILState_Ensure, it's important that the GILState machinery knows about
1409 it so it doesn't try to create another thread state for the thread (this is
1410 a better fix for SF bug #1010677 than the first one attempted).
1411*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001412static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001413_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001414{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001415 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001416 threadstate created in Py_Initialize(). Don't do anything for now
1417 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001418 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001420 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001421
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001422 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 The only situation where you can legitimately have more than one
1425 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001426 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001427
Victor Stinner590cebe2013-12-13 11:08:56 +01001428 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1429 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001430
Victor Stinner590cebe2013-12-13 11:08:56 +01001431 The first thread state created for that given OS level thread will
1432 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001434 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1435 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001436 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001437 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001438 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 /* PyGILState_Release must not try to delete this thread state. */
1441 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001442}
1443
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001444/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001445static PyThreadState *
1446_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1447{
1448 if (gilstate->autoInterpreterState == NULL)
1449 return NULL;
1450 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1451}
1452
Tim Peters19717fa2004-10-09 17:38:29 +00001453PyThreadState *
1454PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001455{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001456 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001457}
1458
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001459int
1460PyGILState_Check(void)
1461{
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001462 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1463 if (!gilstate->check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001464 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001465 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001466
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001467 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1468 return 1;
1469 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001470
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001471 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1472 if (tstate == NULL) {
1473 return 0;
1474 }
1475
1476 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001477}
1478
Tim Peters19717fa2004-10-09 17:38:29 +00001479PyGILState_STATE
1480PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001481{
Victor Stinner175a7042020-03-10 00:37:48 +01001482 _PyRuntimeState *runtime = &_PyRuntime;
1483 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 /* Note that we do not auto-init Python here - apart from
1486 potential races with 2 threads auto-initializing, pep-311
1487 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001488 called Py_Initialize(). */
1489
1490 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1491 called by Py_Initialize() */
Victor Stinnere838a932020-05-05 19:56:48 +02001492#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinner175a7042020-03-10 00:37:48 +01001493 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinnere838a932020-05-05 19:56:48 +02001494#endif
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001495 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001496
Victor Stinner175a7042020-03-10 00:37:48 +01001497 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1498 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001500 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001501 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001502 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001504 }
1505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 /* This is our thread state! We'll need to delete it in the
1507 matching call to PyGILState_Release(). */
1508 tcur->gilstate_counter = 0;
1509 current = 0; /* new thread state is never current */
1510 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001511 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001513 }
1514
1515 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001517 }
1518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 /* Update our counter in the thread-state - no need for locks:
1520 - tcur will remain valid as we hold the GIL.
1521 - the counter is safe as we are the only thread "allowed"
1522 to modify this value
1523 */
1524 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001527}
1528
Tim Peters19717fa2004-10-09 17:38:29 +00001529void
1530PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001531{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001532 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001533 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1534 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 Py_FatalError("auto-releasing thread-state, "
1536 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001537 }
1538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 /* We must hold the GIL and have our thread state current */
1540 /* XXX - remove the check - the assert should be fine,
1541 but while this is very new (April 2003), the extra check
1542 by release-only users can't hurt.
1543 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001544 if (!PyThreadState_IsCurrent(tstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001545 _Py_FatalErrorFormat(__func__,
1546 "thread state %p must be current when releasing",
1547 tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001548 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001549 assert(PyThreadState_IsCurrent(tstate));
1550 --tstate->gilstate_counter;
1551 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 /* If we're going to destroy this thread-state, we must
1554 * clear it while the GIL is held, as destructors may run.
1555 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001556 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 /* can't have been locked when we created it */
1558 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001559 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 /* Delete the thread-state. Note this releases the GIL too!
1561 * It's vital that the GIL be held here, to avoid shutdown
1562 * races; see bugs 225673 and 1061968 (that nasty bug has a
1563 * habit of coming back).
1564 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001565 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1566 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 }
1568 /* Release the lock if necessary */
1569 else if (oldstate == PyGILState_UNLOCKED)
1570 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001571}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001572
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001573
Eric Snow7f8bfc92018-01-29 18:23:44 -07001574/**************************/
1575/* cross-interpreter data */
1576/**************************/
1577
1578/* cross-interpreter data */
1579
1580crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1581
1582/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1583 to keep the registry code separate. */
1584static crossinterpdatafunc
1585_lookup_getdata(PyObject *obj)
1586{
1587 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1588 if (getdata == NULL && PyErr_Occurred() == 0)
1589 PyErr_Format(PyExc_ValueError,
1590 "%S does not support cross-interpreter data", obj);
1591 return getdata;
1592}
1593
1594int
1595_PyObject_CheckCrossInterpreterData(PyObject *obj)
1596{
1597 crossinterpdatafunc getdata = _lookup_getdata(obj);
1598 if (getdata == NULL) {
1599 return -1;
1600 }
1601 return 0;
1602}
1603
1604static int
Victor Stinner71a35222020-03-26 22:46:14 +01001605_check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001606{
1607 // data->data can be anything, including NULL, so we don't check it.
1608
1609 // data->obj may be NULL, so we don't check it.
1610
1611 if (data->interp < 0) {
Victor Stinner71a35222020-03-26 22:46:14 +01001612 _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001613 return -1;
1614 }
1615
1616 if (data->new_object == NULL) {
Victor Stinner71a35222020-03-26 22:46:14 +01001617 _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001618 return -1;
1619 }
1620
1621 // data->free may be NULL, so we don't check it.
1622
1623 return 0;
1624}
1625
1626int
1627_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1628{
Victor Stinner71a35222020-03-26 22:46:14 +01001629 // PyThreadState_Get() aborts if tstate is NULL.
1630 PyThreadState *tstate = PyThreadState_Get();
1631 PyInterpreterState *interp = tstate->interp;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001632
1633 // Reset data before re-populating.
1634 *data = (_PyCrossInterpreterData){0};
1635 data->free = PyMem_RawFree; // Set a default that may be overridden.
1636
1637 // Call the "getdata" func for the object.
1638 Py_INCREF(obj);
1639 crossinterpdatafunc getdata = _lookup_getdata(obj);
1640 if (getdata == NULL) {
1641 Py_DECREF(obj);
1642 return -1;
1643 }
1644 int res = getdata(obj, data);
1645 Py_DECREF(obj);
1646 if (res != 0) {
1647 return -1;
1648 }
1649
1650 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001651 data->interp = interp->id;
Victor Stinner71a35222020-03-26 22:46:14 +01001652 if (_check_xidata(tstate, data) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001653 _PyCrossInterpreterData_Release(data);
1654 return -1;
1655 }
1656
1657 return 0;
1658}
1659
Victor Stinnere225beb2019-06-03 18:14:24 +02001660static void
Eric Snow63799132018-06-01 18:45:20 -06001661_release_xidata(void *arg)
1662{
1663 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1664 if (data->free != NULL) {
1665 data->free(data->data);
1666 }
1667 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001668}
1669
1670static void
1671_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1672 PyInterpreterState *interp,
1673 void (*func)(void *), void *arg)
1674{
1675 /* We would use Py_AddPendingCall() if it weren't specific to the
1676 * main interpreter (see bpo-33608). In the meantime we take a
1677 * naive approach.
1678 */
1679 PyThreadState *save_tstate = NULL;
1680 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1681 // XXX Using the "head" thread isn't strictly correct.
1682 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1683 // XXX Possible GILState issues?
1684 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1685 }
1686
1687 func(arg);
1688
1689 // Switch back.
1690 if (save_tstate != NULL) {
1691 _PyThreadState_Swap(gilstate, save_tstate);
1692 }
Eric Snow63799132018-06-01 18:45:20 -06001693}
1694
Eric Snow7f8bfc92018-01-29 18:23:44 -07001695void
1696_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1697{
1698 if (data->data == NULL && data->obj == NULL) {
1699 // Nothing to release!
1700 return;
1701 }
1702
Victor Stinnere225beb2019-06-03 18:14:24 +02001703 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001704 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1705 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001706 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001707 if (data->free != NULL) {
1708 // XXX Someone leaked some memory...
1709 }
1710 return;
1711 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001712
Eric Snow7f8bfc92018-01-29 18:23:44 -07001713 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001714 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1715 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001716}
1717
1718PyObject *
1719_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1720{
1721 return data->new_object(data);
1722}
1723
1724/* registry of {type -> crossinterpdatafunc} */
1725
1726/* For now we use a global registry of shareable classes. An
1727 alternative would be to add a tp_* slot for a class's
1728 crossinterpdatafunc. It would be simpler and more efficient. */
1729
1730static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001731_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1732 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001733{
1734 // Note that we effectively replace already registered classes
1735 // rather than failing.
1736 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1737 if (newhead == NULL)
1738 return -1;
1739 newhead->cls = cls;
1740 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001741 newhead->next = xidregistry->head;
1742 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001743 return 0;
1744}
1745
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001746static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001747
1748int
Eric Snowc11183c2019-03-15 16:35:46 -06001749_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001750 crossinterpdatafunc getdata)
1751{
1752 if (!PyType_Check(cls)) {
1753 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1754 return -1;
1755 }
1756 if (getdata == NULL) {
1757 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1758 return -1;
1759 }
1760
1761 // Make sure the class isn't ever deallocated.
1762 Py_INCREF((PyObject *)cls);
1763
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001764 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1765 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1766 if (xidregistry->head == NULL) {
1767 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001768 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001769 int res = _register_xidata(xidregistry, cls, getdata);
1770 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001771 return res;
1772}
1773
Eric Snow6d2cd902018-05-16 15:04:57 -04001774/* Cross-interpreter objects are looked up by exact match on the class.
1775 We can reassess this policy when we move from a global registry to a
1776 tp_* slot. */
1777
Eric Snow7f8bfc92018-01-29 18:23:44 -07001778crossinterpdatafunc
1779_PyCrossInterpreterData_Lookup(PyObject *obj)
1780{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001781 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001782 PyObject *cls = PyObject_Type(obj);
1783 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001784 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1785 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001786 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001787 _register_builtins_for_crossinterpreter_data(xidregistry);
1788 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001789 }
1790 for(; cur != NULL; cur = cur->next) {
1791 if (cur->cls == (PyTypeObject *)cls) {
1792 getdata = cur->getdata;
1793 break;
1794 }
1795 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001796 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001797 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001798 return getdata;
1799}
1800
1801/* cross-interpreter data for builtin types */
1802
Eric Snow6d2cd902018-05-16 15:04:57 -04001803struct _shared_bytes_data {
1804 char *bytes;
1805 Py_ssize_t len;
1806};
1807
Eric Snow7f8bfc92018-01-29 18:23:44 -07001808static PyObject *
1809_new_bytes_object(_PyCrossInterpreterData *data)
1810{
Eric Snow6d2cd902018-05-16 15:04:57 -04001811 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1812 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001813}
1814
1815static int
1816_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1817{
Eric Snow6d2cd902018-05-16 15:04:57 -04001818 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1819 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1820 return -1;
1821 }
1822 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001823 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001824 data->obj = obj; // Will be "released" (decref'ed) when data released.
1825 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001826 data->free = PyMem_Free;
1827 return 0;
1828}
1829
1830struct _shared_str_data {
1831 int kind;
1832 const void *buffer;
1833 Py_ssize_t len;
1834};
1835
1836static PyObject *
1837_new_str_object(_PyCrossInterpreterData *data)
1838{
1839 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1840 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1841}
1842
1843static int
1844_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1845{
1846 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1847 shared->kind = PyUnicode_KIND(obj);
1848 shared->buffer = PyUnicode_DATA(obj);
An Long29c11722020-06-13 20:26:01 +08001849 shared->len = PyUnicode_GET_LENGTH(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001850 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001851 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001852 data->obj = obj; // Will be "released" (decref'ed) when data released.
1853 data->new_object = _new_str_object;
1854 data->free = PyMem_Free;
1855 return 0;
1856}
1857
1858static PyObject *
1859_new_long_object(_PyCrossInterpreterData *data)
1860{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001861 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001862}
1863
1864static int
1865_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1866{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001867 /* Note that this means the size of shareable ints is bounded by
1868 * sys.maxsize. Hence on 32-bit architectures that is half the
1869 * size of maximum shareable ints on 64-bit.
1870 */
1871 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001872 if (value == -1 && PyErr_Occurred()) {
1873 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1874 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1875 }
1876 return -1;
1877 }
1878 data->data = (void *)value;
1879 data->obj = NULL;
1880 data->new_object = _new_long_object;
1881 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001882 return 0;
1883}
1884
1885static PyObject *
1886_new_none_object(_PyCrossInterpreterData *data)
1887{
1888 // XXX Singleton refcounts are problematic across interpreters...
1889 Py_INCREF(Py_None);
1890 return Py_None;
1891}
1892
1893static int
1894_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1895{
1896 data->data = NULL;
1897 // data->obj remains NULL
1898 data->new_object = _new_none_object;
1899 data->free = NULL; // There is nothing to free.
1900 return 0;
1901}
1902
1903static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001904_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001905{
1906 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001907 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001908 Py_FatalError("could not register None for cross-interpreter sharing");
1909 }
1910
Eric Snow6d2cd902018-05-16 15:04:57 -04001911 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001912 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001913 Py_FatalError("could not register int for cross-interpreter sharing");
1914 }
1915
Eric Snow7f8bfc92018-01-29 18:23:44 -07001916 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001917 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001918 Py_FatalError("could not register bytes for cross-interpreter sharing");
1919 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001920
1921 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001922 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001923 Py_FatalError("could not register str for cross-interpreter sharing");
1924 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001925}
1926
1927
Victor Stinner0b72b232020-03-12 23:18:39 +01001928_PyFrameEvalFunction
1929_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1930{
1931 return interp->eval_frame;
1932}
1933
1934
1935void
1936_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1937 _PyFrameEvalFunction eval_frame)
1938{
1939 interp->eval_frame = eval_frame;
1940}
1941
Victor Stinnerda7933e2020-04-13 03:04:28 +02001942
1943const PyConfig*
1944_PyInterpreterState_GetConfig(PyInterpreterState *interp)
1945{
1946 return &interp->config;
1947}
1948
1949
Victor Stinner048a3562020-11-05 00:45:56 +01001950int
1951_PyInterpreterState_GetConfigCopy(PyConfig *config)
Victor Stinnerda7933e2020-04-13 03:04:28 +02001952{
Victor Stinner048a3562020-11-05 00:45:56 +01001953 PyInterpreterState *interp = PyInterpreterState_Get();
1954
1955 PyStatus status = _PyConfig_Copy(config, &interp->config);
1956 if (PyStatus_Exception(status)) {
1957 _PyErr_SetFromPyStatus(status);
1958 return -1;
1959 }
1960 return 0;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001961}
1962
1963
1964const PyConfig*
1965_Py_GetConfig(void)
1966{
1967 assert(PyGILState_Check());
1968 PyThreadState *tstate = _PyThreadState_GET();
1969 return _PyInterpreterState_GetConfig(tstate->interp);
1970}
1971
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001972#ifdef __cplusplus
1973}
1974#endif