blob: 436f874842cc84f1c3da01348e4c3da671908cd7 [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;
Mark Shannon9e7b2072021-04-13 11:08:14 +0100627 tstate->root_cframe.use_tracing = 0;
628 tstate->cframe = &tstate->root_cframe;
Victor Stinner8bb32302019-04-24 16:47:40 +0200629 tstate->gilstate_counter = 0;
630 tstate->async_exc = NULL;
631 tstate->thread_id = PyThread_get_thread_ident();
632
633 tstate->dict = NULL;
634
635 tstate->curexc_type = NULL;
636 tstate->curexc_value = NULL;
637 tstate->curexc_traceback = NULL;
638
639 tstate->exc_state.exc_type = NULL;
640 tstate->exc_state.exc_value = NULL;
641 tstate->exc_state.exc_traceback = NULL;
642 tstate->exc_state.previous_item = NULL;
643 tstate->exc_info = &tstate->exc_state;
644
645 tstate->c_profilefunc = NULL;
646 tstate->c_tracefunc = NULL;
647 tstate->c_profileobj = NULL;
648 tstate->c_traceobj = NULL;
649
650 tstate->trash_delete_nesting = 0;
651 tstate->trash_delete_later = NULL;
652 tstate->on_delete = NULL;
653 tstate->on_delete_data = NULL;
654
655 tstate->coroutine_origin_tracking_depth = 0;
656
Victor Stinner8bb32302019-04-24 16:47:40 +0200657 tstate->async_gen_firstiter = NULL;
658 tstate->async_gen_finalizer = NULL;
659
660 tstate->context = NULL;
661 tstate->context_ver = 1;
662
Victor Stinner8bb32302019-04-24 16:47:40 +0200663 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100664 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200665 }
666
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200667 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100668 tstate->id = ++interp->tstate_next_unique_id;
Victor Stinner8bb32302019-04-24 16:47:40 +0200669 tstate->prev = NULL;
670 tstate->next = interp->tstate_head;
671 if (tstate->next)
672 tstate->next->prev = tstate;
673 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200674 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000677}
678
Victor Stinner45b9be52010-03-03 23:28:07 +0000679PyThreadState *
680PyThreadState_New(PyInterpreterState *interp)
681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000683}
684
685PyThreadState *
686_PyThreadState_Prealloc(PyInterpreterState *interp)
687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000689}
690
691void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100692_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000693{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100694 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000695}
696
Martin v. Löwis1a214512008-06-11 05:26:20 +0000697PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200698PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000699{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200700 Py_ssize_t index = module->m_base.m_index;
Victor Stinner81a7be32020-04-14 15:14:01 +0200701 PyInterpreterState *state = _PyInterpreterState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000703 if (module->m_slots) {
704 return NULL;
705 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (index == 0)
707 return NULL;
708 if (state->modules_by_index == NULL)
709 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200710 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 return NULL;
712 res = PyList_GET_ITEM(state->modules_by_index, index);
713 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000714}
715
716int
Victor Stinner82c83bd2019-11-22 18:52:27 +0100717_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000718{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300719 if (!def) {
Victor Stinner71a35222020-03-26 22:46:14 +0100720 assert(_PyErr_Occurred(tstate));
Berker Peksag4b7b5652016-08-22 18:05:56 +0300721 return -1;
722 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000723 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100724 _PyErr_SetString(tstate,
725 PyExc_SystemError,
726 "PyState_AddModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000727 return -1;
728 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100729
730 PyInterpreterState *interp = tstate->interp;
731 if (!interp->modules_by_index) {
732 interp->modules_by_index = PyList_New(0);
733 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100735 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100737
738 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
739 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100741 }
742 }
743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100745 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000747}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000748
Martin v. Löwis7800f752012-06-22 12:20:55 +0200749int
750PyState_AddModule(PyObject* module, struct PyModuleDef* def)
751{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200752 if (!def) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100753 Py_FatalError("module definition is NULL");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200754 return -1;
755 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100756
757 PyThreadState *tstate = _PyThreadState_GET();
758 PyInterpreterState *interp = tstate->interp;
759 Py_ssize_t index = def->m_base.m_index;
760 if (interp->modules_by_index &&
761 index < PyList_GET_SIZE(interp->modules_by_index) &&
762 module == PyList_GET_ITEM(interp->modules_by_index, index))
763 {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100764 _Py_FatalErrorFormat(__func__, "module %p already added", module);
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100765 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200766 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100767 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200768}
769
770int
771PyState_RemoveModule(struct PyModuleDef* def)
772{
Victor Stinner71a35222020-03-26 22:46:14 +0100773 PyThreadState *tstate = _PyThreadState_GET();
774 PyInterpreterState *interp = tstate->interp;
775
Nick Coghland5cacbb2015-05-23 22:24:10 +1000776 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100777 _PyErr_SetString(tstate,
778 PyExc_SystemError,
779 "PyState_RemoveModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000780 return -1;
781 }
Victor Stinner71a35222020-03-26 22:46:14 +0100782
783 Py_ssize_t index = def->m_base.m_index;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200784 if (index == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100785 Py_FatalError("invalid module index");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200786 }
Victor Stinner71a35222020-03-26 22:46:14 +0100787 if (interp->modules_by_index == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100788 Py_FatalError("Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200789 }
Victor Stinner71a35222020-03-26 22:46:14 +0100790 if (index > PyList_GET_SIZE(interp->modules_by_index)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100791 Py_FatalError("Module index out of bounds.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200792 }
Victor Stinner71a35222020-03-26 22:46:14 +0100793
Zackery Spytz2a893432018-12-05 00:14:00 -0700794 Py_INCREF(Py_None);
Victor Stinner71a35222020-03-26 22:46:14 +0100795 return PyList_SetItem(interp->modules_by_index, index, Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200796}
797
Victor Stinner048a3562020-11-05 00:45:56 +0100798// Used by finalize_modules()
Antoine Pitrou40322e62013-08-11 00:30:09 +0200799void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200800_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200801{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200802 if (!interp->modules_by_index) {
803 return;
804 }
805
806 Py_ssize_t i;
807 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
808 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
809 if (PyModule_Check(m)) {
810 /* cleanup the saved copy of module dicts */
811 PyModuleDef *md = PyModule_GetDef(m);
812 if (md) {
813 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200814 }
815 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200816 }
817
818 /* Setting modules_by_index to NULL could be dangerous, so we
819 clear the list instead. */
820 if (PyList_SetSlice(interp->modules_by_index,
821 0, PyList_GET_SIZE(interp->modules_by_index),
822 NULL)) {
823 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200824 }
825}
826
Guido van Rossuma027efa1997-05-05 20:56:21 +0000827void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000828PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000829{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200830 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200831
Victor Stinner5804f872020-03-24 16:32:26 +0100832 if (verbose && tstate->frame != NULL) {
833 /* bpo-20526: After the main thread calls
834 _PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
835 exit when trying to take the GIL. If a thread exit in the middle of
836 _PyEval_EvalFrameDefault(), tstate->frame is not reset to its
837 previous value. It is more likely with daemon threads, but it can
838 happen with regular threads if threading._shutdown() fails
839 (ex: interrupted by CTRL+C). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 fprintf(stderr,
841 "PyThreadState_Clear: warning: thread still has a frame\n");
Victor Stinner5804f872020-03-24 16:32:26 +0100842 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000843
Victor Stinner5804f872020-03-24 16:32:26 +0100844 /* Don't clear tstate->frame: it is a borrowed reference */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 Py_CLEAR(tstate->dict);
847 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 Py_CLEAR(tstate->curexc_type);
850 Py_CLEAR(tstate->curexc_value);
851 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000852
Mark Shannonae3087c2017-10-22 22:41:51 +0100853 Py_CLEAR(tstate->exc_state.exc_type);
854 Py_CLEAR(tstate->exc_state.exc_value);
855 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300856
Mark Shannonae3087c2017-10-22 22:41:51 +0100857 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200858 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100859 fprintf(stderr,
860 "PyThreadState_Clear: warning: thread still has a generator\n");
861 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 tstate->c_profilefunc = NULL;
864 tstate->c_tracefunc = NULL;
865 Py_CLEAR(tstate->c_profileobj);
866 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400867
Yury Selivanoveb636452016-09-08 22:01:51 -0700868 Py_CLEAR(tstate->async_gen_firstiter);
869 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500870
871 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100872
873 if (tstate->on_delete != NULL) {
874 tstate->on_delete(tstate->on_delete_data);
875 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000876}
877
878
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300879/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000880static void
Victor Stinner9da74302019-11-20 11:17:17 +0100881tstate_delete_common(PyThreadState *tstate,
882 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000883{
Victor Stinner3026cad2020-06-01 16:02:40 +0200884 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200885 PyInterpreterState *interp = tstate->interp;
886 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100887 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200888 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100889 _PyRuntimeState *runtime = interp->runtime;
890
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200891 HEAD_LOCK(runtime);
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100892 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200893 tstate->prev->next = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100894 }
895 else {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200896 interp->tstate_head = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100897 }
898 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200899 tstate->next->prev = tstate->prev;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100900 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200901 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100902
Victor Stinner9da74302019-11-20 11:17:17 +0100903 if (gilstate->autoInterpreterState &&
904 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
905 {
906 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
907 }
908}
909
910
911static void
912_PyThreadState_Delete(PyThreadState *tstate, int check_current)
913{
914 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
915 if (check_current) {
916 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100917 _Py_FatalErrorFormat(__func__, "tstate %p is still current", tstate);
Victor Stinner9da74302019-11-20 11:17:17 +0100918 }
919 }
920 tstate_delete_common(tstate, gilstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100921 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000922}
923
924
Victor Stinner01b1cc12019-11-20 02:27:56 +0100925void
926PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000927{
Victor Stinner9da74302019-11-20 11:17:17 +0100928 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200929}
930
931
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300932void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100933_PyThreadState_DeleteCurrent(PyThreadState *tstate)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200934{
Victor Stinner3026cad2020-06-01 16:02:40 +0200935 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100936 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner9da74302019-11-20 11:17:17 +0100937 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200938 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100939 _PyEval_ReleaseLock(tstate);
940 PyMem_RawFree(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000941}
Guido van Rossum29757862001-01-23 01:46:06 +0000942
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300943void
944PyThreadState_DeleteCurrent(void)
945{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100946 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
947 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
948 _PyThreadState_DeleteCurrent(tstate);
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300949}
950
Guido van Rossum29757862001-01-23 01:46:06 +0000951
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200952/*
953 * Delete all thread states except the one passed as argument.
954 * Note that, if there is a current thread state, it *must* be the one
955 * passed as argument. Also, this won't touch any other interpreters
956 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000957 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200958 */
959void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200960_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200961{
962 PyInterpreterState *interp = tstate->interp;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100963
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200964 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200965 /* Remove all thread states, except tstate, from the linked list of
966 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200967 without holding the lock. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100968 PyThreadState *list = interp->tstate_head;
969 if (list == tstate) {
970 list = tstate->next;
971 }
972 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200973 tstate->prev->next = tstate->next;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100974 }
975 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200976 tstate->next->prev = tstate->prev;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100977 }
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200978 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200979 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200980 HEAD_UNLOCK(runtime);
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100981
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200982 /* Clear and deallocate all stale thread states. Even if this
983 executes Python code, we should be safe since it executes
984 in the current thread, not one of the stale threads. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100985 PyThreadState *p, *next;
986 for (p = list; p; p = next) {
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200987 next = p->next;
988 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200989 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200990 }
991}
992
993
Victor Stinnere838a932020-05-05 19:56:48 +0200994#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
995PyThreadState*
996_PyThreadState_GetTSS(void) {
997 return PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
998}
999#endif
1000
1001
Guido van Rossuma027efa1997-05-05 20:56:21 +00001002PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001003_PyThreadState_UncheckedGet(void)
1004{
Victor Stinner50b48572018-11-01 01:51:40 +01001005 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001006}
1007
1008
1009PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001010PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +00001011{
Victor Stinner50b48572018-11-01 01:51:40 +01001012 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +02001013 _Py_EnsureTstateNotNULL(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +00001015}
1016
1017
Victor Stinner09532fe2019-05-10 23:39:09 +02001018PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001019_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +00001020{
Victor Stinnere838a932020-05-05 19:56:48 +02001021#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1022 PyThreadState *oldts = _PyThreadState_GetTSS();
1023#else
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001024 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Victor Stinnere838a932020-05-05 19:56:48 +02001025#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +00001026
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001027 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 /* It should not be possible for more than one thread state
1029 to be used for a thread. Check this the best we can in debug
1030 builds.
1031 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02001032#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 if (newts) {
1034 /* This can be called from PyEval_RestoreThread(). Similar
1035 to it, we need to ensure errno doesn't change.
1036 */
1037 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001038 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 if (check && check->interp == newts->interp && check != newts)
1040 Py_FatalError("Invalid thread state for this thread");
1041 errno = err;
1042 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001043#endif
Victor Stinnere838a932020-05-05 19:56:48 +02001044#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1045 PyThread_tss_set(&gilstate->autoTSSkey, newts);
1046#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +00001048}
Guido van Rossumede04391998-04-10 20:18:25 +00001049
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001050PyThreadState *
1051PyThreadState_Swap(PyThreadState *newts)
1052{
1053 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
1054}
1055
Guido van Rossumede04391998-04-10 20:18:25 +00001056/* An extension mechanism to store arbitrary additional per-thread state.
1057 PyThreadState_GetDict() returns a dictionary that can be used to hold such
1058 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001059 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
1060 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +00001061
1062PyObject *
Victor Stinner0e427c62020-03-25 21:22:55 +01001063_PyThreadState_GetDict(PyThreadState *tstate)
1064{
1065 assert(tstate != NULL);
1066 if (tstate->dict == NULL) {
1067 tstate->dict = PyDict_New();
1068 if (tstate->dict == NULL) {
1069 _PyErr_Clear(tstate);
1070 }
1071 }
1072 return tstate->dict;
1073}
1074
1075
1076PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001077PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +00001078{
Victor Stinner50b48572018-11-01 01:51:40 +01001079 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner0e427c62020-03-25 21:22:55 +01001080 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 }
Victor Stinner0e427c62020-03-25 21:22:55 +01001083 return _PyThreadState_GetDict(tstate);
Guido van Rossumede04391998-04-10 20:18:25 +00001084}
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001085
1086
Victor Stinner8fb02b62020-03-13 23:38:08 +01001087PyInterpreterState *
1088PyThreadState_GetInterpreter(PyThreadState *tstate)
1089{
1090 assert(tstate != NULL);
Victor Stinner8fb02b62020-03-13 23:38:08 +01001091 return tstate->interp;
1092}
1093
1094
Victor Stinner4386b902020-04-29 03:01:43 +02001095PyFrameObject*
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001096PyThreadState_GetFrame(PyThreadState *tstate)
1097{
1098 assert(tstate != NULL);
Victor Stinner4386b902020-04-29 03:01:43 +02001099 PyFrameObject *frame = tstate->frame;
1100 Py_XINCREF(frame);
1101 return frame;
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001102}
1103
1104
Victor Stinner5c3cda02020-03-25 21:23:53 +01001105uint64_t
1106PyThreadState_GetID(PyThreadState *tstate)
1107{
1108 assert(tstate != NULL);
1109 return tstate->id;
1110}
1111
1112
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001113/* Asynchronously raise an exception in a thread.
1114 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001115 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001116 to call this, or use ctypes. Must be called with the GIL held.
1117 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1118 match any known thread id). Can be called with exc=NULL to clear an
1119 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001120
1121int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001122PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1123{
Victor Stinner09532fe2019-05-10 23:39:09 +02001124 _PyRuntimeState *runtime = &_PyRuntime;
1125 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 /* Although the GIL is held, a few C API functions can be called
1128 * without the GIL held, and in particular some that create and
1129 * destroy thread and interpreter states. Those can mutate the
1130 * list of thread states we're traversing, so to prevent that we lock
1131 * head_mutex for the duration.
1132 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001133 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001134 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1135 if (tstate->thread_id != id) {
1136 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001138
1139 /* Tricky: we need to decref the current value
1140 * (if any) in tstate->async_exc, but that can in turn
1141 * allow arbitrary Python code to run, including
1142 * perhaps calls to this function. To prevent
1143 * deadlock, we need to release head_mutex before
1144 * the decref.
1145 */
1146 PyObject *old_exc = tstate->async_exc;
1147 Py_XINCREF(exc);
1148 tstate->async_exc = exc;
1149 HEAD_UNLOCK(runtime);
1150
1151 Py_XDECREF(old_exc);
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001152 _PyEval_SignalAsyncExc(tstate->interp);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001153 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001155 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001157}
1158
1159
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001160/* Routines for advanced debuggers, requested by David Beazley.
1161 Don't use unless you know what you are doing! */
1162
1163PyInterpreterState *
1164PyInterpreterState_Head(void)
1165{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001166 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001167}
1168
1169PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001170PyInterpreterState_Main(void)
1171{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001172 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001173}
1174
1175PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001176PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001178}
1179
1180PyThreadState *
1181PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001183}
1184
1185PyThreadState *
1186PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001188}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001189
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001190/* The implementation of sys._current_frames(). This is intended to be
1191 called with the GIL held, as it will be when called via
1192 sys._current_frames(). It's possible it would work fine even without
1193 the GIL held, but haven't thought enough about that.
1194*/
1195PyObject *
1196_PyThread_CurrentFrames(void)
1197{
Victor Stinner71a35222020-03-26 22:46:14 +01001198 PyThreadState *tstate = _PyThreadState_GET();
1199 if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001200 return NULL;
1201 }
1202
Victor Stinner71a35222020-03-26 22:46:14 +01001203 PyObject *result = PyDict_New();
1204 if (result == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 return NULL;
Victor Stinner71a35222020-03-26 22:46:14 +01001206 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 /* for i in all interpreters:
1209 * for t in all of i's thread states:
1210 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001211 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 * need to grab head_mutex for the duration.
1213 */
Victor Stinner71a35222020-03-26 22:46:14 +01001214 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001215 HEAD_LOCK(runtime);
Victor Stinner71a35222020-03-26 22:46:14 +01001216 PyInterpreterState *i;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001217 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 PyThreadState *t;
1219 for (t = i->tstate_head; t != NULL; t = t->next) {
Victor Stinner4386b902020-04-29 03:01:43 +02001220 PyFrameObject *frame = t->frame;
Victor Stinner71a35222020-03-26 22:46:14 +01001221 if (frame == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 continue;
Victor Stinner71a35222020-03-26 22:46:14 +01001223 }
1224 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1225 if (id == NULL) {
1226 goto fail;
1227 }
1228 int stat = PyDict_SetItem(result, id, (PyObject *)frame);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 Py_DECREF(id);
Victor Stinner71a35222020-03-26 22:46:14 +01001230 if (stat < 0) {
1231 goto fail;
1232 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 }
1234 }
Victor Stinner71a35222020-03-26 22:46:14 +01001235 goto done;
1236
1237fail:
1238 Py_CLEAR(result);
1239
1240done:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001241 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001243}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001244
Julien Danjou64366fa2020-11-02 15:16:25 +01001245PyObject *
1246_PyThread_CurrentExceptions(void)
1247{
1248 PyThreadState *tstate = _PyThreadState_GET();
1249
1250 _Py_EnsureTstateNotNULL(tstate);
1251
1252 if (_PySys_Audit(tstate, "sys._current_exceptions", NULL) < 0) {
1253 return NULL;
1254 }
1255
1256 PyObject *result = PyDict_New();
1257 if (result == NULL) {
1258 return NULL;
1259 }
1260
1261 /* for i in all interpreters:
1262 * for t in all of i's thread states:
1263 * if t's frame isn't NULL, map t's id to its frame
1264 * Because these lists can mutate even when the GIL is held, we
1265 * need to grab head_mutex for the duration.
1266 */
1267 _PyRuntimeState *runtime = tstate->interp->runtime;
1268 HEAD_LOCK(runtime);
1269 PyInterpreterState *i;
1270 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
1271 PyThreadState *t;
1272 for (t = i->tstate_head; t != NULL; t = t->next) {
1273 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(t);
1274 if (err_info == NULL) {
1275 continue;
1276 }
1277 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1278 if (id == NULL) {
1279 goto fail;
1280 }
1281 PyObject *exc_info = PyTuple_Pack(
1282 3,
1283 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
1284 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
1285 err_info->exc_traceback != NULL ? err_info->exc_traceback : Py_None);
1286 if (exc_info == NULL) {
1287 Py_DECREF(id);
1288 goto fail;
1289 }
1290 int stat = PyDict_SetItem(result, id, exc_info);
1291 Py_DECREF(id);
1292 Py_DECREF(exc_info);
1293 if (stat < 0) {
1294 goto fail;
1295 }
1296 }
1297 }
1298 goto done;
1299
1300fail:
1301 Py_CLEAR(result);
1302
1303done:
1304 HEAD_UNLOCK(runtime);
1305 return result;
1306}
1307
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001308/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001309
1310/* Keep this as a static, as it is not reliable! It can only
1311 ever be compared to the state for the *current* thread.
1312 * If not equal, then it doesn't matter that the actual
1313 value may change immediately after comparison, as it can't
1314 possibly change to the current thread's state.
1315 * If equal, then the current thread holds the lock, so the value can't
1316 change until we yield the lock.
1317*/
1318static int
1319PyThreadState_IsCurrent(PyThreadState *tstate)
1320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001322 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001323 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1324 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001325}
1326
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001327/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001328 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001329*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001330PyStatus
Victor Stinner87f649a2021-03-10 20:00:46 +01001331_PyGILState_Init(_PyRuntimeState *runtime)
1332{
1333 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1334 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
1335 return _PyStatus_NO_MEMORY();
1336 }
1337 // PyThreadState_New() calls _PyGILState_NoteThreadState() which does
1338 // nothing before autoInterpreterState is set.
1339 assert(gilstate->autoInterpreterState == NULL);
1340 return _PyStatus_OK();
1341}
1342
1343
1344PyStatus
1345_PyGILState_SetTstate(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001346{
Victor Stinner101bf692021-02-19 13:33:31 +01001347 if (!_Py_IsMainInterpreter(tstate->interp)) {
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001348 /* Currently, PyGILState is shared by all interpreters. The main
1349 * interpreter is responsible to initialize it. */
1350 return _PyStatus_OK();
1351 }
1352
Victor Stinner8bb32302019-04-24 16:47:40 +02001353 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001354 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001355 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001356
Victor Stinner01b1cc12019-11-20 02:27:56 +01001357 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001358
Victor Stinnerb45d2592019-06-20 00:05:23 +02001359 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001360 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1361 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001362
Victor Stinner8bb32302019-04-24 16:47:40 +02001363 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001364 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001365}
1366
Victor Stinner861d9ab2016-03-16 22:45:24 +01001367PyInterpreterState *
1368_PyGILState_GetInterpreterStateUnsafe(void)
1369{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001370 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001371}
1372
Tim Peters19717fa2004-10-09 17:38:29 +00001373void
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001374_PyGILState_Fini(PyInterpreterState *interp)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001375{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001376 struct _gilstate_runtime_state *gilstate = &interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001377 PyThread_tss_delete(&gilstate->autoTSSkey);
1378 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001379}
1380
Victor Stinner26881c82020-06-02 15:51:37 +02001381#ifdef HAVE_FORK
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001382/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001383 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001384 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001385 */
Victor Stinner26881c82020-06-02 15:51:37 +02001386PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001387_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001388{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001389 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001390 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001391
1392 PyThread_tss_delete(&gilstate->autoTSSkey);
1393 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner26881c82020-06-02 15:51:37 +02001394 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001395 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001396
Charles-François Natalia233df82011-11-22 19:49:51 +01001397 /* If the thread had an associated auto thread state, reassociate it with
1398 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001399 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001400 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001401 {
Victor Stinner26881c82020-06-02 15:51:37 +02001402 return _PyStatus_ERR("failed to set autoTSSkey");
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001403 }
Victor Stinner26881c82020-06-02 15:51:37 +02001404 return _PyStatus_OK();
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001405}
Victor Stinner26881c82020-06-02 15:51:37 +02001406#endif
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001407
Michael W. Hudson188d4362005-06-20 16:52:57 +00001408/* When a thread state is created for a thread by some mechanism other than
1409 PyGILState_Ensure, it's important that the GILState machinery knows about
1410 it so it doesn't try to create another thread state for the thread (this is
1411 a better fix for SF bug #1010677 than the first one attempted).
1412*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001413static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001414_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001415{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001416 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001417 threadstate created in Py_Initialize(). Don't do anything for now
1418 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001419 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001421 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001422
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001423 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 The only situation where you can legitimately have more than one
1426 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001427 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001428
Victor Stinner590cebe2013-12-13 11:08:56 +01001429 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1430 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001431
Victor Stinner590cebe2013-12-13 11:08:56 +01001432 The first thread state created for that given OS level thread will
1433 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001435 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1436 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001437 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001438 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001439 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 /* PyGILState_Release must not try to delete this thread state. */
1442 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001443}
1444
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001445/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001446static PyThreadState *
1447_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1448{
1449 if (gilstate->autoInterpreterState == NULL)
1450 return NULL;
1451 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1452}
1453
Tim Peters19717fa2004-10-09 17:38:29 +00001454PyThreadState *
1455PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001456{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001457 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001458}
1459
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001460int
1461PyGILState_Check(void)
1462{
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001463 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1464 if (!gilstate->check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001465 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001466 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001467
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001468 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1469 return 1;
1470 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001471
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001472 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1473 if (tstate == NULL) {
1474 return 0;
1475 }
1476
1477 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001478}
1479
Tim Peters19717fa2004-10-09 17:38:29 +00001480PyGILState_STATE
1481PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001482{
Victor Stinner175a7042020-03-10 00:37:48 +01001483 _PyRuntimeState *runtime = &_PyRuntime;
1484 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 /* Note that we do not auto-init Python here - apart from
1487 potential races with 2 threads auto-initializing, pep-311
1488 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001489 called Py_Initialize(). */
1490
1491 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1492 called by Py_Initialize() */
Victor Stinnere838a932020-05-05 19:56:48 +02001493#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinner175a7042020-03-10 00:37:48 +01001494 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinnere838a932020-05-05 19:56:48 +02001495#endif
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001496 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001497
Victor Stinner175a7042020-03-10 00:37:48 +01001498 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1499 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001501 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001502 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001503 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001505 }
1506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 /* This is our thread state! We'll need to delete it in the
1508 matching call to PyGILState_Release(). */
1509 tcur->gilstate_counter = 0;
1510 current = 0; /* new thread state is never current */
1511 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001512 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001514 }
1515
1516 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001518 }
1519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 /* Update our counter in the thread-state - no need for locks:
1521 - tcur will remain valid as we hold the GIL.
1522 - the counter is safe as we are the only thread "allowed"
1523 to modify this value
1524 */
1525 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001528}
1529
Tim Peters19717fa2004-10-09 17:38:29 +00001530void
1531PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001532{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001533 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001534 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1535 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001536 Py_FatalError("auto-releasing thread-state, "
1537 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001538 }
1539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 /* We must hold the GIL and have our thread state current */
1541 /* XXX - remove the check - the assert should be fine,
1542 but while this is very new (April 2003), the extra check
1543 by release-only users can't hurt.
1544 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001545 if (!PyThreadState_IsCurrent(tstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001546 _Py_FatalErrorFormat(__func__,
1547 "thread state %p must be current when releasing",
1548 tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001549 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001550 assert(PyThreadState_IsCurrent(tstate));
1551 --tstate->gilstate_counter;
1552 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 /* If we're going to destroy this thread-state, we must
1555 * clear it while the GIL is held, as destructors may run.
1556 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001557 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 /* can't have been locked when we created it */
1559 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001560 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 /* Delete the thread-state. Note this releases the GIL too!
1562 * It's vital that the GIL be held here, to avoid shutdown
1563 * races; see bugs 225673 and 1061968 (that nasty bug has a
1564 * habit of coming back).
1565 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001566 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1567 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 }
1569 /* Release the lock if necessary */
1570 else if (oldstate == PyGILState_UNLOCKED)
1571 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001572}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001573
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001574
Eric Snow7f8bfc92018-01-29 18:23:44 -07001575/**************************/
1576/* cross-interpreter data */
1577/**************************/
1578
1579/* cross-interpreter data */
1580
1581crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1582
1583/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1584 to keep the registry code separate. */
1585static crossinterpdatafunc
1586_lookup_getdata(PyObject *obj)
1587{
1588 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1589 if (getdata == NULL && PyErr_Occurred() == 0)
1590 PyErr_Format(PyExc_ValueError,
1591 "%S does not support cross-interpreter data", obj);
1592 return getdata;
1593}
1594
1595int
1596_PyObject_CheckCrossInterpreterData(PyObject *obj)
1597{
1598 crossinterpdatafunc getdata = _lookup_getdata(obj);
1599 if (getdata == NULL) {
1600 return -1;
1601 }
1602 return 0;
1603}
1604
1605static int
Victor Stinner71a35222020-03-26 22:46:14 +01001606_check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001607{
1608 // data->data can be anything, including NULL, so we don't check it.
1609
1610 // data->obj may be NULL, so we don't check it.
1611
1612 if (data->interp < 0) {
Victor Stinner71a35222020-03-26 22:46:14 +01001613 _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001614 return -1;
1615 }
1616
1617 if (data->new_object == NULL) {
Victor Stinner71a35222020-03-26 22:46:14 +01001618 _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001619 return -1;
1620 }
1621
1622 // data->free may be NULL, so we don't check it.
1623
1624 return 0;
1625}
1626
1627int
1628_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1629{
Victor Stinner71a35222020-03-26 22:46:14 +01001630 // PyThreadState_Get() aborts if tstate is NULL.
1631 PyThreadState *tstate = PyThreadState_Get();
1632 PyInterpreterState *interp = tstate->interp;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001633
1634 // Reset data before re-populating.
1635 *data = (_PyCrossInterpreterData){0};
1636 data->free = PyMem_RawFree; // Set a default that may be overridden.
1637
1638 // Call the "getdata" func for the object.
1639 Py_INCREF(obj);
1640 crossinterpdatafunc getdata = _lookup_getdata(obj);
1641 if (getdata == NULL) {
1642 Py_DECREF(obj);
1643 return -1;
1644 }
1645 int res = getdata(obj, data);
1646 Py_DECREF(obj);
1647 if (res != 0) {
1648 return -1;
1649 }
1650
1651 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001652 data->interp = interp->id;
Victor Stinner71a35222020-03-26 22:46:14 +01001653 if (_check_xidata(tstate, data) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001654 _PyCrossInterpreterData_Release(data);
1655 return -1;
1656 }
1657
1658 return 0;
1659}
1660
Victor Stinnere225beb2019-06-03 18:14:24 +02001661static void
Eric Snow63799132018-06-01 18:45:20 -06001662_release_xidata(void *arg)
1663{
1664 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1665 if (data->free != NULL) {
1666 data->free(data->data);
1667 }
1668 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001669}
1670
1671static void
1672_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1673 PyInterpreterState *interp,
1674 void (*func)(void *), void *arg)
1675{
1676 /* We would use Py_AddPendingCall() if it weren't specific to the
1677 * main interpreter (see bpo-33608). In the meantime we take a
1678 * naive approach.
1679 */
1680 PyThreadState *save_tstate = NULL;
1681 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1682 // XXX Using the "head" thread isn't strictly correct.
1683 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1684 // XXX Possible GILState issues?
1685 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1686 }
1687
1688 func(arg);
1689
1690 // Switch back.
1691 if (save_tstate != NULL) {
1692 _PyThreadState_Swap(gilstate, save_tstate);
1693 }
Eric Snow63799132018-06-01 18:45:20 -06001694}
1695
Eric Snow7f8bfc92018-01-29 18:23:44 -07001696void
1697_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1698{
1699 if (data->data == NULL && data->obj == NULL) {
1700 // Nothing to release!
1701 return;
1702 }
1703
Victor Stinnere225beb2019-06-03 18:14:24 +02001704 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001705 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1706 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001707 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001708 if (data->free != NULL) {
1709 // XXX Someone leaked some memory...
1710 }
1711 return;
1712 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001713
Eric Snow7f8bfc92018-01-29 18:23:44 -07001714 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001715 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1716 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001717}
1718
1719PyObject *
1720_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1721{
1722 return data->new_object(data);
1723}
1724
1725/* registry of {type -> crossinterpdatafunc} */
1726
1727/* For now we use a global registry of shareable classes. An
1728 alternative would be to add a tp_* slot for a class's
1729 crossinterpdatafunc. It would be simpler and more efficient. */
1730
1731static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001732_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1733 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001734{
1735 // Note that we effectively replace already registered classes
1736 // rather than failing.
1737 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1738 if (newhead == NULL)
1739 return -1;
1740 newhead->cls = cls;
1741 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001742 newhead->next = xidregistry->head;
1743 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001744 return 0;
1745}
1746
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001747static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001748
1749int
Eric Snowc11183c2019-03-15 16:35:46 -06001750_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001751 crossinterpdatafunc getdata)
1752{
1753 if (!PyType_Check(cls)) {
1754 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1755 return -1;
1756 }
1757 if (getdata == NULL) {
1758 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1759 return -1;
1760 }
1761
1762 // Make sure the class isn't ever deallocated.
1763 Py_INCREF((PyObject *)cls);
1764
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001765 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1766 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1767 if (xidregistry->head == NULL) {
1768 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001769 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001770 int res = _register_xidata(xidregistry, cls, getdata);
1771 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001772 return res;
1773}
1774
Eric Snow6d2cd902018-05-16 15:04:57 -04001775/* Cross-interpreter objects are looked up by exact match on the class.
1776 We can reassess this policy when we move from a global registry to a
1777 tp_* slot. */
1778
Eric Snow7f8bfc92018-01-29 18:23:44 -07001779crossinterpdatafunc
1780_PyCrossInterpreterData_Lookup(PyObject *obj)
1781{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001782 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001783 PyObject *cls = PyObject_Type(obj);
1784 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001785 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1786 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001787 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001788 _register_builtins_for_crossinterpreter_data(xidregistry);
1789 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001790 }
1791 for(; cur != NULL; cur = cur->next) {
1792 if (cur->cls == (PyTypeObject *)cls) {
1793 getdata = cur->getdata;
1794 break;
1795 }
1796 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001797 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001798 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001799 return getdata;
1800}
1801
1802/* cross-interpreter data for builtin types */
1803
Eric Snow6d2cd902018-05-16 15:04:57 -04001804struct _shared_bytes_data {
1805 char *bytes;
1806 Py_ssize_t len;
1807};
1808
Eric Snow7f8bfc92018-01-29 18:23:44 -07001809static PyObject *
1810_new_bytes_object(_PyCrossInterpreterData *data)
1811{
Eric Snow6d2cd902018-05-16 15:04:57 -04001812 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1813 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001814}
1815
1816static int
1817_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1818{
Eric Snow6d2cd902018-05-16 15:04:57 -04001819 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1820 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1821 return -1;
1822 }
1823 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001824 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001825 data->obj = obj; // Will be "released" (decref'ed) when data released.
1826 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001827 data->free = PyMem_Free;
1828 return 0;
1829}
1830
1831struct _shared_str_data {
1832 int kind;
1833 const void *buffer;
1834 Py_ssize_t len;
1835};
1836
1837static PyObject *
1838_new_str_object(_PyCrossInterpreterData *data)
1839{
1840 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1841 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1842}
1843
1844static int
1845_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1846{
1847 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1848 shared->kind = PyUnicode_KIND(obj);
1849 shared->buffer = PyUnicode_DATA(obj);
An Long29c11722020-06-13 20:26:01 +08001850 shared->len = PyUnicode_GET_LENGTH(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001851 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001852 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001853 data->obj = obj; // Will be "released" (decref'ed) when data released.
1854 data->new_object = _new_str_object;
1855 data->free = PyMem_Free;
1856 return 0;
1857}
1858
1859static PyObject *
1860_new_long_object(_PyCrossInterpreterData *data)
1861{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001862 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001863}
1864
1865static int
1866_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1867{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001868 /* Note that this means the size of shareable ints is bounded by
1869 * sys.maxsize. Hence on 32-bit architectures that is half the
1870 * size of maximum shareable ints on 64-bit.
1871 */
1872 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001873 if (value == -1 && PyErr_Occurred()) {
1874 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1875 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1876 }
1877 return -1;
1878 }
1879 data->data = (void *)value;
1880 data->obj = NULL;
1881 data->new_object = _new_long_object;
1882 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001883 return 0;
1884}
1885
1886static PyObject *
1887_new_none_object(_PyCrossInterpreterData *data)
1888{
1889 // XXX Singleton refcounts are problematic across interpreters...
1890 Py_INCREF(Py_None);
1891 return Py_None;
1892}
1893
1894static int
1895_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1896{
1897 data->data = NULL;
1898 // data->obj remains NULL
1899 data->new_object = _new_none_object;
1900 data->free = NULL; // There is nothing to free.
1901 return 0;
1902}
1903
1904static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001905_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001906{
1907 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001908 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001909 Py_FatalError("could not register None for cross-interpreter sharing");
1910 }
1911
Eric Snow6d2cd902018-05-16 15:04:57 -04001912 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001913 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001914 Py_FatalError("could not register int for cross-interpreter sharing");
1915 }
1916
Eric Snow7f8bfc92018-01-29 18:23:44 -07001917 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001918 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001919 Py_FatalError("could not register bytes for cross-interpreter sharing");
1920 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001921
1922 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001923 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001924 Py_FatalError("could not register str for cross-interpreter sharing");
1925 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001926}
1927
1928
Victor Stinner0b72b232020-03-12 23:18:39 +01001929_PyFrameEvalFunction
1930_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1931{
1932 return interp->eval_frame;
1933}
1934
1935
1936void
1937_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1938 _PyFrameEvalFunction eval_frame)
1939{
1940 interp->eval_frame = eval_frame;
1941}
1942
Victor Stinnerda7933e2020-04-13 03:04:28 +02001943
1944const PyConfig*
1945_PyInterpreterState_GetConfig(PyInterpreterState *interp)
1946{
1947 return &interp->config;
1948}
1949
1950
Victor Stinner048a3562020-11-05 00:45:56 +01001951int
1952_PyInterpreterState_GetConfigCopy(PyConfig *config)
Victor Stinnerda7933e2020-04-13 03:04:28 +02001953{
Victor Stinner048a3562020-11-05 00:45:56 +01001954 PyInterpreterState *interp = PyInterpreterState_Get();
1955
1956 PyStatus status = _PyConfig_Copy(config, &interp->config);
1957 if (PyStatus_Exception(status)) {
1958 _PyErr_SetFromPyStatus(status);
1959 return -1;
1960 }
1961 return 0;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001962}
1963
1964
1965const PyConfig*
1966_Py_GetConfig(void)
1967{
1968 assert(PyGILState_Check());
1969 PyThreadState *tstate = _PyThreadState_GET();
1970 return _PyInterpreterState_GetConfig(tstate->interp);
1971}
1972
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001973#ifdef __cplusplus
1974}
1975#endif