blob: e7c085d1f83a92eee5640ddc57fa8ff40c6b16b9 [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 Stinner01b1cc12019-11-20 02:27:56 +01001330_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001331{
Victor Stinner101bf692021-02-19 13:33:31 +01001332 if (!_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001333 /* Currently, PyGILState is shared by all interpreters. The main
1334 * interpreter is responsible to initialize it. */
1335 return _PyStatus_OK();
1336 }
1337
Victor Stinner8bb32302019-04-24 16:47:40 +02001338 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001339 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001340 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001341
Victor Stinner01b1cc12019-11-20 02:27:56 +01001342 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001343
1344 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001345 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001346 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001347 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001348 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1349 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001350
Victor Stinner8bb32302019-04-24 16:47:40 +02001351 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001352 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001353}
1354
Victor Stinner861d9ab2016-03-16 22:45:24 +01001355PyInterpreterState *
1356_PyGILState_GetInterpreterStateUnsafe(void)
1357{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001358 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001359}
1360
Tim Peters19717fa2004-10-09 17:38:29 +00001361void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001362_PyGILState_Fini(PyInterpreterState *interp)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001363{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001364 struct _gilstate_runtime_state *gilstate = &interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001365 PyThread_tss_delete(&gilstate->autoTSSkey);
1366 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001367}
1368
Victor Stinner26881c82020-06-02 15:51:37 +02001369#ifdef HAVE_FORK
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001370/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001371 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001372 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001373 */
Victor Stinner26881c82020-06-02 15:51:37 +02001374PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001375_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001376{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001377 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001378 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001379
1380 PyThread_tss_delete(&gilstate->autoTSSkey);
1381 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner26881c82020-06-02 15:51:37 +02001382 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001383 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001384
Charles-François Natalia233df82011-11-22 19:49:51 +01001385 /* If the thread had an associated auto thread state, reassociate it with
1386 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001387 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001388 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001389 {
Victor Stinner26881c82020-06-02 15:51:37 +02001390 return _PyStatus_ERR("failed to set autoTSSkey");
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001391 }
Victor Stinner26881c82020-06-02 15:51:37 +02001392 return _PyStatus_OK();
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001393}
Victor Stinner26881c82020-06-02 15:51:37 +02001394#endif
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001395
Michael W. Hudson188d4362005-06-20 16:52:57 +00001396/* When a thread state is created for a thread by some mechanism other than
1397 PyGILState_Ensure, it's important that the GILState machinery knows about
1398 it so it doesn't try to create another thread state for the thread (this is
1399 a better fix for SF bug #1010677 than the first one attempted).
1400*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001401static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001402_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001403{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001404 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001405 threadstate created in Py_Initialize(). Don't do anything for now
1406 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001407 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001409 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001410
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001411 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 The only situation where you can legitimately have more than one
1414 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001415 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001416
Victor Stinner590cebe2013-12-13 11:08:56 +01001417 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1418 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001419
Victor Stinner590cebe2013-12-13 11:08:56 +01001420 The first thread state created for that given OS level thread will
1421 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001423 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1424 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001425 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001426 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001427 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 /* PyGILState_Release must not try to delete this thread state. */
1430 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001431}
1432
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001433/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001434static PyThreadState *
1435_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1436{
1437 if (gilstate->autoInterpreterState == NULL)
1438 return NULL;
1439 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1440}
1441
Tim Peters19717fa2004-10-09 17:38:29 +00001442PyThreadState *
1443PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001444{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001445 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001446}
1447
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001448int
1449PyGILState_Check(void)
1450{
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001451 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1452 if (!gilstate->check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001453 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001454 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001455
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001456 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1457 return 1;
1458 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001459
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001460 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1461 if (tstate == NULL) {
1462 return 0;
1463 }
1464
1465 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001466}
1467
Tim Peters19717fa2004-10-09 17:38:29 +00001468PyGILState_STATE
1469PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001470{
Victor Stinner175a7042020-03-10 00:37:48 +01001471 _PyRuntimeState *runtime = &_PyRuntime;
1472 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 /* Note that we do not auto-init Python here - apart from
1475 potential races with 2 threads auto-initializing, pep-311
1476 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001477 called Py_Initialize(). */
1478
1479 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1480 called by Py_Initialize() */
Victor Stinnere838a932020-05-05 19:56:48 +02001481#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinner175a7042020-03-10 00:37:48 +01001482 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinnere838a932020-05-05 19:56:48 +02001483#endif
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001484 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001485
Victor Stinner175a7042020-03-10 00:37:48 +01001486 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1487 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001488 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001489 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001490 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001491 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001493 }
1494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 /* This is our thread state! We'll need to delete it in the
1496 matching call to PyGILState_Release(). */
1497 tcur->gilstate_counter = 0;
1498 current = 0; /* new thread state is never current */
1499 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001500 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001502 }
1503
1504 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001506 }
1507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 /* Update our counter in the thread-state - no need for locks:
1509 - tcur will remain valid as we hold the GIL.
1510 - the counter is safe as we are the only thread "allowed"
1511 to modify this value
1512 */
1513 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001516}
1517
Tim Peters19717fa2004-10-09 17:38:29 +00001518void
1519PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001520{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001521 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001522 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1523 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 Py_FatalError("auto-releasing thread-state, "
1525 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001526 }
1527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 /* We must hold the GIL and have our thread state current */
1529 /* XXX - remove the check - the assert should be fine,
1530 but while this is very new (April 2003), the extra check
1531 by release-only users can't hurt.
1532 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001533 if (!PyThreadState_IsCurrent(tstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001534 _Py_FatalErrorFormat(__func__,
1535 "thread state %p must be current when releasing",
1536 tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001537 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001538 assert(PyThreadState_IsCurrent(tstate));
1539 --tstate->gilstate_counter;
1540 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 /* If we're going to destroy this thread-state, we must
1543 * clear it while the GIL is held, as destructors may run.
1544 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001545 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 /* can't have been locked when we created it */
1547 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001548 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 /* Delete the thread-state. Note this releases the GIL too!
1550 * It's vital that the GIL be held here, to avoid shutdown
1551 * races; see bugs 225673 and 1061968 (that nasty bug has a
1552 * habit of coming back).
1553 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001554 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1555 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 }
1557 /* Release the lock if necessary */
1558 else if (oldstate == PyGILState_UNLOCKED)
1559 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001560}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001561
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001562
Eric Snow7f8bfc92018-01-29 18:23:44 -07001563/**************************/
1564/* cross-interpreter data */
1565/**************************/
1566
1567/* cross-interpreter data */
1568
1569crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1570
1571/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1572 to keep the registry code separate. */
1573static crossinterpdatafunc
1574_lookup_getdata(PyObject *obj)
1575{
1576 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1577 if (getdata == NULL && PyErr_Occurred() == 0)
1578 PyErr_Format(PyExc_ValueError,
1579 "%S does not support cross-interpreter data", obj);
1580 return getdata;
1581}
1582
1583int
1584_PyObject_CheckCrossInterpreterData(PyObject *obj)
1585{
1586 crossinterpdatafunc getdata = _lookup_getdata(obj);
1587 if (getdata == NULL) {
1588 return -1;
1589 }
1590 return 0;
1591}
1592
1593static int
Victor Stinner71a35222020-03-26 22:46:14 +01001594_check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001595{
1596 // data->data can be anything, including NULL, so we don't check it.
1597
1598 // data->obj may be NULL, so we don't check it.
1599
1600 if (data->interp < 0) {
Victor Stinner71a35222020-03-26 22:46:14 +01001601 _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001602 return -1;
1603 }
1604
1605 if (data->new_object == NULL) {
Victor Stinner71a35222020-03-26 22:46:14 +01001606 _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001607 return -1;
1608 }
1609
1610 // data->free may be NULL, so we don't check it.
1611
1612 return 0;
1613}
1614
1615int
1616_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1617{
Victor Stinner71a35222020-03-26 22:46:14 +01001618 // PyThreadState_Get() aborts if tstate is NULL.
1619 PyThreadState *tstate = PyThreadState_Get();
1620 PyInterpreterState *interp = tstate->interp;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001621
1622 // Reset data before re-populating.
1623 *data = (_PyCrossInterpreterData){0};
1624 data->free = PyMem_RawFree; // Set a default that may be overridden.
1625
1626 // Call the "getdata" func for the object.
1627 Py_INCREF(obj);
1628 crossinterpdatafunc getdata = _lookup_getdata(obj);
1629 if (getdata == NULL) {
1630 Py_DECREF(obj);
1631 return -1;
1632 }
1633 int res = getdata(obj, data);
1634 Py_DECREF(obj);
1635 if (res != 0) {
1636 return -1;
1637 }
1638
1639 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001640 data->interp = interp->id;
Victor Stinner71a35222020-03-26 22:46:14 +01001641 if (_check_xidata(tstate, data) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001642 _PyCrossInterpreterData_Release(data);
1643 return -1;
1644 }
1645
1646 return 0;
1647}
1648
Victor Stinnere225beb2019-06-03 18:14:24 +02001649static void
Eric Snow63799132018-06-01 18:45:20 -06001650_release_xidata(void *arg)
1651{
1652 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1653 if (data->free != NULL) {
1654 data->free(data->data);
1655 }
1656 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001657}
1658
1659static void
1660_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1661 PyInterpreterState *interp,
1662 void (*func)(void *), void *arg)
1663{
1664 /* We would use Py_AddPendingCall() if it weren't specific to the
1665 * main interpreter (see bpo-33608). In the meantime we take a
1666 * naive approach.
1667 */
1668 PyThreadState *save_tstate = NULL;
1669 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1670 // XXX Using the "head" thread isn't strictly correct.
1671 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1672 // XXX Possible GILState issues?
1673 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1674 }
1675
1676 func(arg);
1677
1678 // Switch back.
1679 if (save_tstate != NULL) {
1680 _PyThreadState_Swap(gilstate, save_tstate);
1681 }
Eric Snow63799132018-06-01 18:45:20 -06001682}
1683
Eric Snow7f8bfc92018-01-29 18:23:44 -07001684void
1685_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1686{
1687 if (data->data == NULL && data->obj == NULL) {
1688 // Nothing to release!
1689 return;
1690 }
1691
Victor Stinnere225beb2019-06-03 18:14:24 +02001692 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001693 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1694 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001695 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001696 if (data->free != NULL) {
1697 // XXX Someone leaked some memory...
1698 }
1699 return;
1700 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001701
Eric Snow7f8bfc92018-01-29 18:23:44 -07001702 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001703 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1704 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001705}
1706
1707PyObject *
1708_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1709{
1710 return data->new_object(data);
1711}
1712
1713/* registry of {type -> crossinterpdatafunc} */
1714
1715/* For now we use a global registry of shareable classes. An
1716 alternative would be to add a tp_* slot for a class's
1717 crossinterpdatafunc. It would be simpler and more efficient. */
1718
1719static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001720_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1721 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001722{
1723 // Note that we effectively replace already registered classes
1724 // rather than failing.
1725 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1726 if (newhead == NULL)
1727 return -1;
1728 newhead->cls = cls;
1729 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001730 newhead->next = xidregistry->head;
1731 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001732 return 0;
1733}
1734
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001735static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001736
1737int
Eric Snowc11183c2019-03-15 16:35:46 -06001738_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001739 crossinterpdatafunc getdata)
1740{
1741 if (!PyType_Check(cls)) {
1742 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1743 return -1;
1744 }
1745 if (getdata == NULL) {
1746 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1747 return -1;
1748 }
1749
1750 // Make sure the class isn't ever deallocated.
1751 Py_INCREF((PyObject *)cls);
1752
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001753 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1754 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1755 if (xidregistry->head == NULL) {
1756 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001757 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001758 int res = _register_xidata(xidregistry, cls, getdata);
1759 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001760 return res;
1761}
1762
Eric Snow6d2cd902018-05-16 15:04:57 -04001763/* Cross-interpreter objects are looked up by exact match on the class.
1764 We can reassess this policy when we move from a global registry to a
1765 tp_* slot. */
1766
Eric Snow7f8bfc92018-01-29 18:23:44 -07001767crossinterpdatafunc
1768_PyCrossInterpreterData_Lookup(PyObject *obj)
1769{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001770 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001771 PyObject *cls = PyObject_Type(obj);
1772 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001773 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1774 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001775 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001776 _register_builtins_for_crossinterpreter_data(xidregistry);
1777 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001778 }
1779 for(; cur != NULL; cur = cur->next) {
1780 if (cur->cls == (PyTypeObject *)cls) {
1781 getdata = cur->getdata;
1782 break;
1783 }
1784 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001785 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001786 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001787 return getdata;
1788}
1789
1790/* cross-interpreter data for builtin types */
1791
Eric Snow6d2cd902018-05-16 15:04:57 -04001792struct _shared_bytes_data {
1793 char *bytes;
1794 Py_ssize_t len;
1795};
1796
Eric Snow7f8bfc92018-01-29 18:23:44 -07001797static PyObject *
1798_new_bytes_object(_PyCrossInterpreterData *data)
1799{
Eric Snow6d2cd902018-05-16 15:04:57 -04001800 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1801 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001802}
1803
1804static int
1805_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1806{
Eric Snow6d2cd902018-05-16 15:04:57 -04001807 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1808 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1809 return -1;
1810 }
1811 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001812 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001813 data->obj = obj; // Will be "released" (decref'ed) when data released.
1814 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001815 data->free = PyMem_Free;
1816 return 0;
1817}
1818
1819struct _shared_str_data {
1820 int kind;
1821 const void *buffer;
1822 Py_ssize_t len;
1823};
1824
1825static PyObject *
1826_new_str_object(_PyCrossInterpreterData *data)
1827{
1828 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1829 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1830}
1831
1832static int
1833_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1834{
1835 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1836 shared->kind = PyUnicode_KIND(obj);
1837 shared->buffer = PyUnicode_DATA(obj);
An Long29c11722020-06-13 20:26:01 +08001838 shared->len = PyUnicode_GET_LENGTH(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001839 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001840 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001841 data->obj = obj; // Will be "released" (decref'ed) when data released.
1842 data->new_object = _new_str_object;
1843 data->free = PyMem_Free;
1844 return 0;
1845}
1846
1847static PyObject *
1848_new_long_object(_PyCrossInterpreterData *data)
1849{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001850 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001851}
1852
1853static int
1854_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1855{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001856 /* Note that this means the size of shareable ints is bounded by
1857 * sys.maxsize. Hence on 32-bit architectures that is half the
1858 * size of maximum shareable ints on 64-bit.
1859 */
1860 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001861 if (value == -1 && PyErr_Occurred()) {
1862 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1863 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1864 }
1865 return -1;
1866 }
1867 data->data = (void *)value;
1868 data->obj = NULL;
1869 data->new_object = _new_long_object;
1870 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001871 return 0;
1872}
1873
1874static PyObject *
1875_new_none_object(_PyCrossInterpreterData *data)
1876{
1877 // XXX Singleton refcounts are problematic across interpreters...
1878 Py_INCREF(Py_None);
1879 return Py_None;
1880}
1881
1882static int
1883_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1884{
1885 data->data = NULL;
1886 // data->obj remains NULL
1887 data->new_object = _new_none_object;
1888 data->free = NULL; // There is nothing to free.
1889 return 0;
1890}
1891
1892static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001893_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001894{
1895 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001896 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001897 Py_FatalError("could not register None for cross-interpreter sharing");
1898 }
1899
Eric Snow6d2cd902018-05-16 15:04:57 -04001900 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001901 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001902 Py_FatalError("could not register int for cross-interpreter sharing");
1903 }
1904
Eric Snow7f8bfc92018-01-29 18:23:44 -07001905 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001906 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001907 Py_FatalError("could not register bytes for cross-interpreter sharing");
1908 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001909
1910 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001911 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001912 Py_FatalError("could not register str for cross-interpreter sharing");
1913 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001914}
1915
1916
Victor Stinner0b72b232020-03-12 23:18:39 +01001917_PyFrameEvalFunction
1918_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1919{
1920 return interp->eval_frame;
1921}
1922
1923
1924void
1925_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1926 _PyFrameEvalFunction eval_frame)
1927{
1928 interp->eval_frame = eval_frame;
1929}
1930
Victor Stinnerda7933e2020-04-13 03:04:28 +02001931
1932const PyConfig*
1933_PyInterpreterState_GetConfig(PyInterpreterState *interp)
1934{
1935 return &interp->config;
1936}
1937
1938
Victor Stinner048a3562020-11-05 00:45:56 +01001939int
1940_PyInterpreterState_GetConfigCopy(PyConfig *config)
Victor Stinnerda7933e2020-04-13 03:04:28 +02001941{
Victor Stinner048a3562020-11-05 00:45:56 +01001942 PyInterpreterState *interp = PyInterpreterState_Get();
1943
1944 PyStatus status = _PyConfig_Copy(config, &interp->config);
1945 if (PyStatus_Exception(status)) {
1946 _PyErr_SetFromPyStatus(status);
1947 return -1;
1948 }
1949 return 0;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001950}
1951
1952
1953const PyConfig*
1954_Py_GetConfig(void)
1955{
1956 assert(PyGILState_Check());
1957 PyThreadState *tstate = _PyThreadState_GET();
1958 return _PyInterpreterState_GetConfig(tstate->interp);
1959}
1960
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001961#ifdef __cplusplus
1962}
1963#endif