blob: ebf76a058b640220d8b36634e2c4e375a0633447 [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.
59 int64_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);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200311#ifdef HAVE_FORK
312 Py_CLEAR(interp->before_forkers);
313 Py_CLEAR(interp->after_forkers_parent);
314 Py_CLEAR(interp->after_forkers_child);
315#endif
Victor Stinnerfd957c12020-11-03 18:07:15 +0100316
317 _PyAST_Fini(interp);
318 _PyWarnings_Fini(interp);
Victor Stinnerb8fa1352020-12-15 14:34:19 +0100319 _PyAtExit_Fini(interp);
Victor Stinnerfd957c12020-11-03 18:07:15 +0100320
321 // All Python types must be destroyed before the last GC collection. Python
322 // types create a reference cycle to themselves in their in their
323 // PyTypeObject.tp_mro member (the tuple contains the type).
Victor Stinnereba5bf22020-10-30 22:51:02 +0100324
325 /* Last garbage collection on this interpreter */
326 _PyGC_CollectNoFail(tstate);
Victor Stinnereba5bf22020-10-30 22:51:02 +0100327 _PyGC_Fini(tstate);
328
Hai Shi8ecc0c42020-08-13 05:23:30 +0800329 /* We don't clear sysdict and builtins until the end of this function.
330 Because clearing other attributes can execute arbitrary Python code
331 which requires sysdict and builtins. */
332 PyDict_Clear(interp->sysdict);
333 PyDict_Clear(interp->builtins);
334 Py_CLEAR(interp->sysdict);
335 Py_CLEAR(interp->builtins);
336
Eric Snow5be45a62019-03-08 22:47:07 -0700337 // XXX Once we have one allocator per interpreter (i.e.
338 // per-interpreter GC) we must ensure that all of the interpreter's
339 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000340}
341
342
Victor Stinnereba5bf22020-10-30 22:51:02 +0100343void
344PyInterpreterState_Clear(PyInterpreterState *interp)
345{
346 // Use the current Python thread state to call audit hooks and to collect
347 // garbage. It can be different than the current Python thread state
348 // of 'interp'.
349 PyThreadState *current_tstate = _PyThreadState_GET();
350
351 interpreter_clear(interp, current_tstate);
352}
353
354
355void
356_PyInterpreterState_Clear(PyThreadState *tstate)
357{
358 interpreter_clear(tstate->interp, tstate);
359}
360
361
Guido van Rossum25ce5661997-08-02 03:10:38 +0000362static void
Victor Stinner9da74302019-11-20 11:17:17 +0100363zapthreads(PyInterpreterState *interp, int check_current)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000364{
Victor Stinner9da74302019-11-20 11:17:17 +0100365 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 /* No need to lock the mutex here because this should only happen
367 when the threads are all really dead (XXX famous last words). */
Victor Stinner9da74302019-11-20 11:17:17 +0100368 while ((tstate = interp->tstate_head) != NULL) {
369 _PyThreadState_Delete(tstate, check_current);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000371}
372
373
Victor Stinner01b1cc12019-11-20 02:27:56 +0100374void
375PyInterpreterState_Delete(PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200376{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100377 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200378 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner9da74302019-11-20 11:17:17 +0100379 zapthreads(interp, 0);
380
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200381 _PyEval_FiniState(&interp->ceval);
382
Victor Stinner9da74302019-11-20 11:17:17 +0100383 /* Delete current thread. After this, many C API calls become crashy. */
384 _PyThreadState_Swap(&runtime->gilstate, NULL);
385
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200386 HEAD_LOCK(runtime);
387 PyInterpreterState **p;
388 for (p = &interpreters->head; ; p = &(*p)->next) {
389 if (*p == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100390 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200391 }
392 if (*p == interp) {
393 break;
394 }
395 }
396 if (interp->tstate_head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100397 Py_FatalError("remaining threads");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200398 }
399 *p = interp->next;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200400
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200401 if (interpreters->main == interp) {
402 interpreters->main = NULL;
403 if (interpreters->head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100404 Py_FatalError("remaining subinterpreters");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200405 }
406 }
407 HEAD_UNLOCK(runtime);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200408
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200409 if (interp->id_mutex != NULL) {
410 PyThread_free_lock(interp->id_mutex);
411 }
412 PyMem_RawFree(interp);
413}
414
415
Victor Stinner26881c82020-06-02 15:51:37 +0200416#ifdef HAVE_FORK
Eric Snow59032962018-09-14 14:17:20 -0700417/*
418 * Delete all interpreter states except the main interpreter. If there
419 * is a current interpreter state, it *must* be the main interpreter.
420 */
Victor Stinner26881c82020-06-02 15:51:37 +0200421PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200422_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700423{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200424 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200425 struct pyinterpreters *interpreters = &runtime->interpreters;
426
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200427 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200428 if (tstate != NULL && tstate->interp != interpreters->main) {
Victor Stinner26881c82020-06-02 15:51:37 +0200429 return _PyStatus_ERR("not main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700430 }
431
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200432 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200433 PyInterpreterState *interp = interpreters->head;
434 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100435 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200436 if (interp == interpreters->main) {
437 interpreters->main->next = NULL;
438 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100439 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700440 continue;
441 }
442
Victor Stinner01b1cc12019-11-20 02:27:56 +0100443 PyInterpreterState_Clear(interp); // XXX must activate?
Victor Stinner9da74302019-11-20 11:17:17 +0100444 zapthreads(interp, 1);
Eric Snow59032962018-09-14 14:17:20 -0700445 if (interp->id_mutex != NULL) {
446 PyThread_free_lock(interp->id_mutex);
447 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100448 PyInterpreterState *prev_interp = interp;
449 interp = interp->next;
450 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700451 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200452 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700453
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200454 if (interpreters->head == NULL) {
Victor Stinner26881c82020-06-02 15:51:37 +0200455 return _PyStatus_ERR("missing main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700456 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200457 _PyThreadState_Swap(gilstate, tstate);
Victor Stinner26881c82020-06-02 15:51:37 +0200458 return _PyStatus_OK();
Eric Snow59032962018-09-14 14:17:20 -0700459}
Victor Stinner26881c82020-06-02 15:51:37 +0200460#endif
Eric Snow59032962018-09-14 14:17:20 -0700461
462
Victor Stinnercaba55b2018-08-03 15:33:52 +0200463PyInterpreterState *
Victor Stinnerbe793732020-03-13 18:15:33 +0100464PyInterpreterState_Get(void)
Victor Stinnercaba55b2018-08-03 15:33:52 +0200465{
Victor Stinner50b48572018-11-01 01:51:40 +0100466 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200467 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200468 PyInterpreterState *interp = tstate->interp;
469 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100470 Py_FatalError("no current interpreter");
Victor Stinnercaba55b2018-08-03 15:33:52 +0200471 }
472 return interp;
473}
474
475
Eric Snowe3774162017-05-22 19:46:40 -0700476int64_t
477PyInterpreterState_GetID(PyInterpreterState *interp)
478{
479 if (interp == NULL) {
480 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
481 return -1;
482 }
483 return interp->id;
484}
485
486
Eric Snow5be45a62019-03-08 22:47:07 -0700487static PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200488interp_look_up_id(_PyRuntimeState *runtime, int64_t requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700489{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200490 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100491 while (interp != NULL) {
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200492 int64_t id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700493 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100494 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700495 }
496 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100497 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700498 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100499 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700500 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100501 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700502}
503
Eric Snow5be45a62019-03-08 22:47:07 -0700504PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200505_PyInterpreterState_LookUpID(int64_t requested_id)
Eric Snow5be45a62019-03-08 22:47:07 -0700506{
507 PyInterpreterState *interp = NULL;
508 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200509 _PyRuntimeState *runtime = &_PyRuntime;
510 HEAD_LOCK(runtime);
511 interp = interp_look_up_id(runtime, requested_id);
512 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700513 }
514 if (interp == NULL && !PyErr_Occurred()) {
515 PyErr_Format(PyExc_RuntimeError,
516 "unrecognized interpreter ID %lld", requested_id);
517 }
518 return interp;
519}
520
Eric Snow4c6955e2018-02-16 18:53:40 -0700521
522int
523_PyInterpreterState_IDInitref(PyInterpreterState *interp)
524{
525 if (interp->id_mutex != NULL) {
526 return 0;
527 }
528 interp->id_mutex = PyThread_allocate_lock();
529 if (interp->id_mutex == NULL) {
530 PyErr_SetString(PyExc_RuntimeError,
531 "failed to create init interpreter ID mutex");
532 return -1;
533 }
534 interp->id_refcount = 0;
535 return 0;
536}
537
538
539void
540_PyInterpreterState_IDIncref(PyInterpreterState *interp)
541{
542 if (interp->id_mutex == NULL) {
543 return;
544 }
545 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
546 interp->id_refcount += 1;
547 PyThread_release_lock(interp->id_mutex);
548}
549
550
551void
552_PyInterpreterState_IDDecref(PyInterpreterState *interp)
553{
554 if (interp->id_mutex == NULL) {
555 return;
556 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200557 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700558 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
559 assert(interp->id_refcount != 0);
560 interp->id_refcount -= 1;
561 int64_t refcount = interp->id_refcount;
562 PyThread_release_lock(interp->id_mutex);
563
Eric Snowc11183c2019-03-15 16:35:46 -0600564 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700565 // XXX Using the "head" thread isn't strictly correct.
566 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
567 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200568 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700569 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200570 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700571 }
572}
573
Eric Snowc11183c2019-03-15 16:35:46 -0600574int
575_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
576{
577 return interp->requires_idref;
578}
579
580void
581_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
582{
583 interp->requires_idref = required ? 1 : 0;
584}
585
Eric Snowc11183c2019-03-15 16:35:46 -0600586PyObject *
587_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
588{
589 if (interp->modules == NULL) {
590 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
591 return NULL;
592 }
593 return PyMapping_GetItemString(interp->modules, "__main__");
594}
595
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600596PyObject *
597PyInterpreterState_GetDict(PyInterpreterState *interp)
598{
599 if (interp->dict == NULL) {
600 interp->dict = PyDict_New();
601 if (interp->dict == NULL) {
602 PyErr_Clear();
603 }
604 }
605 /* Returning NULL means no per-interpreter dict is available. */
606 return interp->dict;
607}
608
Victor Stinner45b9be52010-03-03 23:28:07 +0000609static PyThreadState *
610new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000611{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100612 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200613 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200614 if (tstate == NULL) {
615 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000617
Victor Stinner8bb32302019-04-24 16:47:40 +0200618 tstate->interp = interp;
619
620 tstate->frame = NULL;
621 tstate->recursion_depth = 0;
Mark Shannon4e7a69b2020-12-02 13:30:55 +0000622 tstate->recursion_headroom = 0;
Victor Stinner8bb32302019-04-24 16:47:40 +0200623 tstate->stackcheck_counter = 0;
624 tstate->tracing = 0;
625 tstate->use_tracing = 0;
626 tstate->gilstate_counter = 0;
627 tstate->async_exc = NULL;
628 tstate->thread_id = PyThread_get_thread_ident();
629
630 tstate->dict = NULL;
631
632 tstate->curexc_type = NULL;
633 tstate->curexc_value = NULL;
634 tstate->curexc_traceback = NULL;
635
636 tstate->exc_state.exc_type = NULL;
637 tstate->exc_state.exc_value = NULL;
638 tstate->exc_state.exc_traceback = NULL;
639 tstate->exc_state.previous_item = NULL;
640 tstate->exc_info = &tstate->exc_state;
641
642 tstate->c_profilefunc = NULL;
643 tstate->c_tracefunc = NULL;
644 tstate->c_profileobj = NULL;
645 tstate->c_traceobj = NULL;
646
647 tstate->trash_delete_nesting = 0;
648 tstate->trash_delete_later = NULL;
649 tstate->on_delete = NULL;
650 tstate->on_delete_data = NULL;
651
652 tstate->coroutine_origin_tracking_depth = 0;
653
Victor Stinner8bb32302019-04-24 16:47:40 +0200654 tstate->async_gen_firstiter = NULL;
655 tstate->async_gen_finalizer = NULL;
656
657 tstate->context = NULL;
658 tstate->context_ver = 1;
659
Victor Stinner8bb32302019-04-24 16:47:40 +0200660 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100661 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200662 }
663
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200664 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100665 tstate->id = ++interp->tstate_next_unique_id;
Victor Stinner8bb32302019-04-24 16:47:40 +0200666 tstate->prev = NULL;
667 tstate->next = interp->tstate_head;
668 if (tstate->next)
669 tstate->next->prev = tstate;
670 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200671 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000674}
675
Victor Stinner45b9be52010-03-03 23:28:07 +0000676PyThreadState *
677PyThreadState_New(PyInterpreterState *interp)
678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000680}
681
682PyThreadState *
683_PyThreadState_Prealloc(PyInterpreterState *interp)
684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000686}
687
688void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100689_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000690{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100691 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000692}
693
Martin v. Löwis1a214512008-06-11 05:26:20 +0000694PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200695PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000696{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200697 Py_ssize_t index = module->m_base.m_index;
Victor Stinner81a7be32020-04-14 15:14:01 +0200698 PyInterpreterState *state = _PyInterpreterState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000700 if (module->m_slots) {
701 return NULL;
702 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 if (index == 0)
704 return NULL;
705 if (state->modules_by_index == NULL)
706 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200707 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 return NULL;
709 res = PyList_GET_ITEM(state->modules_by_index, index);
710 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000711}
712
713int
Victor Stinner82c83bd2019-11-22 18:52:27 +0100714_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000715{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300716 if (!def) {
Victor Stinner71a35222020-03-26 22:46:14 +0100717 assert(_PyErr_Occurred(tstate));
Berker Peksag4b7b5652016-08-22 18:05:56 +0300718 return -1;
719 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000720 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100721 _PyErr_SetString(tstate,
722 PyExc_SystemError,
723 "PyState_AddModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000724 return -1;
725 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100726
727 PyInterpreterState *interp = tstate->interp;
728 if (!interp->modules_by_index) {
729 interp->modules_by_index = PyList_New(0);
730 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100732 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100734
735 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
736 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100738 }
739 }
740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100742 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000744}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000745
Martin v. Löwis7800f752012-06-22 12:20:55 +0200746int
747PyState_AddModule(PyObject* module, struct PyModuleDef* def)
748{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200749 if (!def) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100750 Py_FatalError("module definition is NULL");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200751 return -1;
752 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100753
754 PyThreadState *tstate = _PyThreadState_GET();
755 PyInterpreterState *interp = tstate->interp;
756 Py_ssize_t index = def->m_base.m_index;
757 if (interp->modules_by_index &&
758 index < PyList_GET_SIZE(interp->modules_by_index) &&
759 module == PyList_GET_ITEM(interp->modules_by_index, index))
760 {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100761 _Py_FatalErrorFormat(__func__, "module %p already added", module);
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100762 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200763 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100764 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200765}
766
767int
768PyState_RemoveModule(struct PyModuleDef* def)
769{
Victor Stinner71a35222020-03-26 22:46:14 +0100770 PyThreadState *tstate = _PyThreadState_GET();
771 PyInterpreterState *interp = tstate->interp;
772
Nick Coghland5cacbb2015-05-23 22:24:10 +1000773 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100774 _PyErr_SetString(tstate,
775 PyExc_SystemError,
776 "PyState_RemoveModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000777 return -1;
778 }
Victor Stinner71a35222020-03-26 22:46:14 +0100779
780 Py_ssize_t index = def->m_base.m_index;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200781 if (index == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100782 Py_FatalError("invalid module index");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200783 }
Victor Stinner71a35222020-03-26 22:46:14 +0100784 if (interp->modules_by_index == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100785 Py_FatalError("Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200786 }
Victor Stinner71a35222020-03-26 22:46:14 +0100787 if (index > PyList_GET_SIZE(interp->modules_by_index)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100788 Py_FatalError("Module index out of bounds.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200789 }
Victor Stinner71a35222020-03-26 22:46:14 +0100790
Zackery Spytz2a893432018-12-05 00:14:00 -0700791 Py_INCREF(Py_None);
Victor Stinner71a35222020-03-26 22:46:14 +0100792 return PyList_SetItem(interp->modules_by_index, index, Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200793}
794
Victor Stinner048a3562020-11-05 00:45:56 +0100795// Used by finalize_modules()
Antoine Pitrou40322e62013-08-11 00:30:09 +0200796void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200797_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200798{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200799 if (!interp->modules_by_index) {
800 return;
801 }
802
803 Py_ssize_t i;
804 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
805 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
806 if (PyModule_Check(m)) {
807 /* cleanup the saved copy of module dicts */
808 PyModuleDef *md = PyModule_GetDef(m);
809 if (md) {
810 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200811 }
812 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200813 }
814
815 /* Setting modules_by_index to NULL could be dangerous, so we
816 clear the list instead. */
817 if (PyList_SetSlice(interp->modules_by_index,
818 0, PyList_GET_SIZE(interp->modules_by_index),
819 NULL)) {
820 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200821 }
822}
823
Guido van Rossuma027efa1997-05-05 20:56:21 +0000824void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000825PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000826{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200827 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200828
Victor Stinner5804f872020-03-24 16:32:26 +0100829 if (verbose && tstate->frame != NULL) {
830 /* bpo-20526: After the main thread calls
831 _PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
832 exit when trying to take the GIL. If a thread exit in the middle of
833 _PyEval_EvalFrameDefault(), tstate->frame is not reset to its
834 previous value. It is more likely with daemon threads, but it can
835 happen with regular threads if threading._shutdown() fails
836 (ex: interrupted by CTRL+C). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 fprintf(stderr,
838 "PyThreadState_Clear: warning: thread still has a frame\n");
Victor Stinner5804f872020-03-24 16:32:26 +0100839 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000840
Victor Stinner5804f872020-03-24 16:32:26 +0100841 /* Don't clear tstate->frame: it is a borrowed reference */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 Py_CLEAR(tstate->dict);
844 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 Py_CLEAR(tstate->curexc_type);
847 Py_CLEAR(tstate->curexc_value);
848 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000849
Mark Shannonae3087c2017-10-22 22:41:51 +0100850 Py_CLEAR(tstate->exc_state.exc_type);
851 Py_CLEAR(tstate->exc_state.exc_value);
852 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300853
Mark Shannonae3087c2017-10-22 22:41:51 +0100854 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200855 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100856 fprintf(stderr,
857 "PyThreadState_Clear: warning: thread still has a generator\n");
858 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 tstate->c_profilefunc = NULL;
861 tstate->c_tracefunc = NULL;
862 Py_CLEAR(tstate->c_profileobj);
863 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400864
Yury Selivanoveb636452016-09-08 22:01:51 -0700865 Py_CLEAR(tstate->async_gen_firstiter);
866 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500867
868 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100869
870 if (tstate->on_delete != NULL) {
871 tstate->on_delete(tstate->on_delete_data);
872 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000873}
874
875
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300876/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000877static void
Victor Stinner9da74302019-11-20 11:17:17 +0100878tstate_delete_common(PyThreadState *tstate,
879 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000880{
Victor Stinner3026cad2020-06-01 16:02:40 +0200881 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200882 PyInterpreterState *interp = tstate->interp;
883 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100884 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200885 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100886 _PyRuntimeState *runtime = interp->runtime;
887
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200888 HEAD_LOCK(runtime);
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100889 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200890 tstate->prev->next = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100891 }
892 else {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200893 interp->tstate_head = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100894 }
895 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200896 tstate->next->prev = tstate->prev;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100897 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200898 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100899
Victor Stinner9da74302019-11-20 11:17:17 +0100900 if (gilstate->autoInterpreterState &&
901 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
902 {
903 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
904 }
905}
906
907
908static void
909_PyThreadState_Delete(PyThreadState *tstate, int check_current)
910{
911 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
912 if (check_current) {
913 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100914 _Py_FatalErrorFormat(__func__, "tstate %p is still current", tstate);
Victor Stinner9da74302019-11-20 11:17:17 +0100915 }
916 }
917 tstate_delete_common(tstate, gilstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100918 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000919}
920
921
Victor Stinner01b1cc12019-11-20 02:27:56 +0100922void
923PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000924{
Victor Stinner9da74302019-11-20 11:17:17 +0100925 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200926}
927
928
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300929void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100930_PyThreadState_DeleteCurrent(PyThreadState *tstate)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200931{
Victor Stinner3026cad2020-06-01 16:02:40 +0200932 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100933 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner9da74302019-11-20 11:17:17 +0100934 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200935 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100936 _PyEval_ReleaseLock(tstate);
937 PyMem_RawFree(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000938}
Guido van Rossum29757862001-01-23 01:46:06 +0000939
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300940void
941PyThreadState_DeleteCurrent(void)
942{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100943 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
944 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
945 _PyThreadState_DeleteCurrent(tstate);
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300946}
947
Guido van Rossum29757862001-01-23 01:46:06 +0000948
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200949/*
950 * Delete all thread states except the one passed as argument.
951 * Note that, if there is a current thread state, it *must* be the one
952 * passed as argument. Also, this won't touch any other interpreters
953 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000954 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200955 */
956void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200957_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200958{
959 PyInterpreterState *interp = tstate->interp;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100960
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200961 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200962 /* Remove all thread states, except tstate, from the linked list of
963 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200964 without holding the lock. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100965 PyThreadState *list = interp->tstate_head;
966 if (list == tstate) {
967 list = tstate->next;
968 }
969 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200970 tstate->prev->next = tstate->next;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100971 }
972 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200973 tstate->next->prev = tstate->prev;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100974 }
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200975 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200976 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200977 HEAD_UNLOCK(runtime);
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100978
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200979 /* Clear and deallocate all stale thread states. Even if this
980 executes Python code, we should be safe since it executes
981 in the current thread, not one of the stale threads. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100982 PyThreadState *p, *next;
983 for (p = list; p; p = next) {
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200984 next = p->next;
985 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200986 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200987 }
988}
989
990
Victor Stinnere838a932020-05-05 19:56:48 +0200991#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
992PyThreadState*
993_PyThreadState_GetTSS(void) {
994 return PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
995}
996#endif
997
998
Guido van Rossuma027efa1997-05-05 20:56:21 +0000999PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001000_PyThreadState_UncheckedGet(void)
1001{
Victor Stinner50b48572018-11-01 01:51:40 +01001002 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001003}
1004
1005
1006PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001007PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +00001008{
Victor Stinner50b48572018-11-01 01:51:40 +01001009 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +02001010 _Py_EnsureTstateNotNULL(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +00001012}
1013
1014
Victor Stinner09532fe2019-05-10 23:39:09 +02001015PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001016_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +00001017{
Victor Stinnere838a932020-05-05 19:56:48 +02001018#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1019 PyThreadState *oldts = _PyThreadState_GetTSS();
1020#else
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001021 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Victor Stinnere838a932020-05-05 19:56:48 +02001022#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +00001023
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001024 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 /* It should not be possible for more than one thread state
1026 to be used for a thread. Check this the best we can in debug
1027 builds.
1028 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02001029#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 if (newts) {
1031 /* This can be called from PyEval_RestoreThread(). Similar
1032 to it, we need to ensure errno doesn't change.
1033 */
1034 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001035 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 if (check && check->interp == newts->interp && check != newts)
1037 Py_FatalError("Invalid thread state for this thread");
1038 errno = err;
1039 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001040#endif
Victor Stinnere838a932020-05-05 19:56:48 +02001041#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1042 PyThread_tss_set(&gilstate->autoTSSkey, newts);
1043#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +00001045}
Guido van Rossumede04391998-04-10 20:18:25 +00001046
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001047PyThreadState *
1048PyThreadState_Swap(PyThreadState *newts)
1049{
1050 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
1051}
1052
Guido van Rossumede04391998-04-10 20:18:25 +00001053/* An extension mechanism to store arbitrary additional per-thread state.
1054 PyThreadState_GetDict() returns a dictionary that can be used to hold such
1055 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001056 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
1057 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +00001058
1059PyObject *
Victor Stinner0e427c62020-03-25 21:22:55 +01001060_PyThreadState_GetDict(PyThreadState *tstate)
1061{
1062 assert(tstate != NULL);
1063 if (tstate->dict == NULL) {
1064 tstate->dict = PyDict_New();
1065 if (tstate->dict == NULL) {
1066 _PyErr_Clear(tstate);
1067 }
1068 }
1069 return tstate->dict;
1070}
1071
1072
1073PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001074PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +00001075{
Victor Stinner50b48572018-11-01 01:51:40 +01001076 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner0e427c62020-03-25 21:22:55 +01001077 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 }
Victor Stinner0e427c62020-03-25 21:22:55 +01001080 return _PyThreadState_GetDict(tstate);
Guido van Rossumede04391998-04-10 20:18:25 +00001081}
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001082
1083
Victor Stinner8fb02b62020-03-13 23:38:08 +01001084PyInterpreterState *
1085PyThreadState_GetInterpreter(PyThreadState *tstate)
1086{
1087 assert(tstate != NULL);
Victor Stinner8fb02b62020-03-13 23:38:08 +01001088 return tstate->interp;
1089}
1090
1091
Victor Stinner4386b902020-04-29 03:01:43 +02001092PyFrameObject*
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001093PyThreadState_GetFrame(PyThreadState *tstate)
1094{
1095 assert(tstate != NULL);
Victor Stinner4386b902020-04-29 03:01:43 +02001096 PyFrameObject *frame = tstate->frame;
1097 Py_XINCREF(frame);
1098 return frame;
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001099}
1100
1101
Victor Stinner5c3cda02020-03-25 21:23:53 +01001102uint64_t
1103PyThreadState_GetID(PyThreadState *tstate)
1104{
1105 assert(tstate != NULL);
1106 return tstate->id;
1107}
1108
1109
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001110/* Asynchronously raise an exception in a thread.
1111 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001112 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001113 to call this, or use ctypes. Must be called with the GIL held.
1114 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1115 match any known thread id). Can be called with exc=NULL to clear an
1116 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001117
1118int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001119PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1120{
Victor Stinner09532fe2019-05-10 23:39:09 +02001121 _PyRuntimeState *runtime = &_PyRuntime;
1122 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 /* Although the GIL is held, a few C API functions can be called
1125 * without the GIL held, and in particular some that create and
1126 * destroy thread and interpreter states. Those can mutate the
1127 * list of thread states we're traversing, so to prevent that we lock
1128 * head_mutex for the duration.
1129 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001130 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001131 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1132 if (tstate->thread_id != id) {
1133 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001135
1136 /* Tricky: we need to decref the current value
1137 * (if any) in tstate->async_exc, but that can in turn
1138 * allow arbitrary Python code to run, including
1139 * perhaps calls to this function. To prevent
1140 * deadlock, we need to release head_mutex before
1141 * the decref.
1142 */
1143 PyObject *old_exc = tstate->async_exc;
1144 Py_XINCREF(exc);
1145 tstate->async_exc = exc;
1146 HEAD_UNLOCK(runtime);
1147
1148 Py_XDECREF(old_exc);
1149 _PyEval_SignalAsyncExc(tstate);
1150 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001152 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001154}
1155
1156
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001157/* Routines for advanced debuggers, requested by David Beazley.
1158 Don't use unless you know what you are doing! */
1159
1160PyInterpreterState *
1161PyInterpreterState_Head(void)
1162{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001163 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001164}
1165
1166PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001167PyInterpreterState_Main(void)
1168{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001169 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001170}
1171
1172PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001173PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001175}
1176
1177PyThreadState *
1178PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001180}
1181
1182PyThreadState *
1183PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001185}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001186
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001187/* The implementation of sys._current_frames(). This is intended to be
1188 called with the GIL held, as it will be when called via
1189 sys._current_frames(). It's possible it would work fine even without
1190 the GIL held, but haven't thought enough about that.
1191*/
1192PyObject *
1193_PyThread_CurrentFrames(void)
1194{
Victor Stinner71a35222020-03-26 22:46:14 +01001195 PyThreadState *tstate = _PyThreadState_GET();
1196 if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001197 return NULL;
1198 }
1199
Victor Stinner71a35222020-03-26 22:46:14 +01001200 PyObject *result = PyDict_New();
1201 if (result == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 return NULL;
Victor Stinner71a35222020-03-26 22:46:14 +01001203 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 /* for i in all interpreters:
1206 * for t in all of i's thread states:
1207 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001208 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 * need to grab head_mutex for the duration.
1210 */
Victor Stinner71a35222020-03-26 22:46:14 +01001211 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001212 HEAD_LOCK(runtime);
Victor Stinner71a35222020-03-26 22:46:14 +01001213 PyInterpreterState *i;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001214 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 PyThreadState *t;
1216 for (t = i->tstate_head; t != NULL; t = t->next) {
Victor Stinner4386b902020-04-29 03:01:43 +02001217 PyFrameObject *frame = t->frame;
Victor Stinner71a35222020-03-26 22:46:14 +01001218 if (frame == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 continue;
Victor Stinner71a35222020-03-26 22:46:14 +01001220 }
1221 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1222 if (id == NULL) {
1223 goto fail;
1224 }
1225 int stat = PyDict_SetItem(result, id, (PyObject *)frame);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 Py_DECREF(id);
Victor Stinner71a35222020-03-26 22:46:14 +01001227 if (stat < 0) {
1228 goto fail;
1229 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 }
1231 }
Victor Stinner71a35222020-03-26 22:46:14 +01001232 goto done;
1233
1234fail:
1235 Py_CLEAR(result);
1236
1237done:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001238 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001240}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001241
Julien Danjou64366fa2020-11-02 15:16:25 +01001242PyObject *
1243_PyThread_CurrentExceptions(void)
1244{
1245 PyThreadState *tstate = _PyThreadState_GET();
1246
1247 _Py_EnsureTstateNotNULL(tstate);
1248
1249 if (_PySys_Audit(tstate, "sys._current_exceptions", NULL) < 0) {
1250 return NULL;
1251 }
1252
1253 PyObject *result = PyDict_New();
1254 if (result == NULL) {
1255 return NULL;
1256 }
1257
1258 /* for i in all interpreters:
1259 * for t in all of i's thread states:
1260 * if t's frame isn't NULL, map t's id to its frame
1261 * Because these lists can mutate even when the GIL is held, we
1262 * need to grab head_mutex for the duration.
1263 */
1264 _PyRuntimeState *runtime = tstate->interp->runtime;
1265 HEAD_LOCK(runtime);
1266 PyInterpreterState *i;
1267 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
1268 PyThreadState *t;
1269 for (t = i->tstate_head; t != NULL; t = t->next) {
1270 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(t);
1271 if (err_info == NULL) {
1272 continue;
1273 }
1274 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1275 if (id == NULL) {
1276 goto fail;
1277 }
1278 PyObject *exc_info = PyTuple_Pack(
1279 3,
1280 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
1281 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
1282 err_info->exc_traceback != NULL ? err_info->exc_traceback : Py_None);
1283 if (exc_info == NULL) {
1284 Py_DECREF(id);
1285 goto fail;
1286 }
1287 int stat = PyDict_SetItem(result, id, exc_info);
1288 Py_DECREF(id);
1289 Py_DECREF(exc_info);
1290 if (stat < 0) {
1291 goto fail;
1292 }
1293 }
1294 }
1295 goto done;
1296
1297fail:
1298 Py_CLEAR(result);
1299
1300done:
1301 HEAD_UNLOCK(runtime);
1302 return result;
1303}
1304
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001305/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001306
1307/* Keep this as a static, as it is not reliable! It can only
1308 ever be compared to the state for the *current* thread.
1309 * If not equal, then it doesn't matter that the actual
1310 value may change immediately after comparison, as it can't
1311 possibly change to the current thread's state.
1312 * If equal, then the current thread holds the lock, so the value can't
1313 change until we yield the lock.
1314*/
1315static int
1316PyThreadState_IsCurrent(PyThreadState *tstate)
1317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001319 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001320 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1321 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001322}
1323
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001324/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001325 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001326*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001327PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001328_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001329{
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001330 if (!_Py_IsMainInterpreter(tstate)) {
1331 /* Currently, PyGILState is shared by all interpreters. The main
1332 * interpreter is responsible to initialize it. */
1333 return _PyStatus_OK();
1334 }
1335
Victor Stinner8bb32302019-04-24 16:47:40 +02001336 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001337 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001338 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001339
Victor Stinner01b1cc12019-11-20 02:27:56 +01001340 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001341
1342 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001343 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001344 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001345 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001346 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1347 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001348
Victor Stinner8bb32302019-04-24 16:47:40 +02001349 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001350 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001351}
1352
Victor Stinner861d9ab2016-03-16 22:45:24 +01001353PyInterpreterState *
1354_PyGILState_GetInterpreterStateUnsafe(void)
1355{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001356 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001357}
1358
Tim Peters19717fa2004-10-09 17:38:29 +00001359void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001360_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001361{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001362 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001363 PyThread_tss_delete(&gilstate->autoTSSkey);
1364 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001365}
1366
Victor Stinner26881c82020-06-02 15:51:37 +02001367#ifdef HAVE_FORK
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001368/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001369 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001370 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001371 */
Victor Stinner26881c82020-06-02 15:51:37 +02001372PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001373_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001374{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001375 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001376 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001377
1378 PyThread_tss_delete(&gilstate->autoTSSkey);
1379 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner26881c82020-06-02 15:51:37 +02001380 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001381 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001382
Charles-François Natalia233df82011-11-22 19:49:51 +01001383 /* If the thread had an associated auto thread state, reassociate it with
1384 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001385 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001386 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001387 {
Victor Stinner26881c82020-06-02 15:51:37 +02001388 return _PyStatus_ERR("failed to set autoTSSkey");
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001389 }
Victor Stinner26881c82020-06-02 15:51:37 +02001390 return _PyStatus_OK();
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001391}
Victor Stinner26881c82020-06-02 15:51:37 +02001392#endif
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001393
Michael W. Hudson188d4362005-06-20 16:52:57 +00001394/* When a thread state is created for a thread by some mechanism other than
1395 PyGILState_Ensure, it's important that the GILState machinery knows about
1396 it so it doesn't try to create another thread state for the thread (this is
1397 a better fix for SF bug #1010677 than the first one attempted).
1398*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001399static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001400_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001401{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001402 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001403 threadstate created in Py_Initialize(). Don't do anything for now
1404 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001405 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001407 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001408
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001409 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 The only situation where you can legitimately have more than one
1412 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001413 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001414
Victor Stinner590cebe2013-12-13 11:08:56 +01001415 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1416 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001417
Victor Stinner590cebe2013-12-13 11:08:56 +01001418 The first thread state created for that given OS level thread will
1419 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001421 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1422 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001423 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001424 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001425 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 /* PyGILState_Release must not try to delete this thread state. */
1428 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001429}
1430
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001431/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001432static PyThreadState *
1433_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1434{
1435 if (gilstate->autoInterpreterState == NULL)
1436 return NULL;
1437 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1438}
1439
Tim Peters19717fa2004-10-09 17:38:29 +00001440PyThreadState *
1441PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001442{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001443 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001444}
1445
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001446int
1447PyGILState_Check(void)
1448{
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001449 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1450 if (!gilstate->check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001451 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001452 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001453
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001454 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1455 return 1;
1456 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001457
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001458 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1459 if (tstate == NULL) {
1460 return 0;
1461 }
1462
1463 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001464}
1465
Tim Peters19717fa2004-10-09 17:38:29 +00001466PyGILState_STATE
1467PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001468{
Victor Stinner175a7042020-03-10 00:37:48 +01001469 _PyRuntimeState *runtime = &_PyRuntime;
1470 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 /* Note that we do not auto-init Python here - apart from
1473 potential races with 2 threads auto-initializing, pep-311
1474 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001475 called Py_Initialize(). */
1476
1477 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1478 called by Py_Initialize() */
Victor Stinnere838a932020-05-05 19:56:48 +02001479#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinner175a7042020-03-10 00:37:48 +01001480 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinnere838a932020-05-05 19:56:48 +02001481#endif
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001482 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001483
Victor Stinner175a7042020-03-10 00:37:48 +01001484 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1485 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001487 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001488 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001489 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001491 }
1492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 /* This is our thread state! We'll need to delete it in the
1494 matching call to PyGILState_Release(). */
1495 tcur->gilstate_counter = 0;
1496 current = 0; /* new thread state is never current */
1497 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001498 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001500 }
1501
1502 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001504 }
1505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 /* Update our counter in the thread-state - no need for locks:
1507 - tcur will remain valid as we hold the GIL.
1508 - the counter is safe as we are the only thread "allowed"
1509 to modify this value
1510 */
1511 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001514}
1515
Tim Peters19717fa2004-10-09 17:38:29 +00001516void
1517PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001518{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001519 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001520 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1521 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 Py_FatalError("auto-releasing thread-state, "
1523 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001524 }
1525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 /* We must hold the GIL and have our thread state current */
1527 /* XXX - remove the check - the assert should be fine,
1528 but while this is very new (April 2003), the extra check
1529 by release-only users can't hurt.
1530 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001531 if (!PyThreadState_IsCurrent(tstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001532 _Py_FatalErrorFormat(__func__,
1533 "thread state %p must be current when releasing",
1534 tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001535 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001536 assert(PyThreadState_IsCurrent(tstate));
1537 --tstate->gilstate_counter;
1538 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 /* If we're going to destroy this thread-state, we must
1541 * clear it while the GIL is held, as destructors may run.
1542 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001543 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 /* can't have been locked when we created it */
1545 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001546 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 /* Delete the thread-state. Note this releases the GIL too!
1548 * It's vital that the GIL be held here, to avoid shutdown
1549 * races; see bugs 225673 and 1061968 (that nasty bug has a
1550 * habit of coming back).
1551 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001552 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1553 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 }
1555 /* Release the lock if necessary */
1556 else if (oldstate == PyGILState_UNLOCKED)
1557 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001558}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001559
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001560
Eric Snow7f8bfc92018-01-29 18:23:44 -07001561/**************************/
1562/* cross-interpreter data */
1563/**************************/
1564
1565/* cross-interpreter data */
1566
1567crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1568
1569/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1570 to keep the registry code separate. */
1571static crossinterpdatafunc
1572_lookup_getdata(PyObject *obj)
1573{
1574 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1575 if (getdata == NULL && PyErr_Occurred() == 0)
1576 PyErr_Format(PyExc_ValueError,
1577 "%S does not support cross-interpreter data", obj);
1578 return getdata;
1579}
1580
1581int
1582_PyObject_CheckCrossInterpreterData(PyObject *obj)
1583{
1584 crossinterpdatafunc getdata = _lookup_getdata(obj);
1585 if (getdata == NULL) {
1586 return -1;
1587 }
1588 return 0;
1589}
1590
1591static int
Victor Stinner71a35222020-03-26 22:46:14 +01001592_check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001593{
1594 // data->data can be anything, including NULL, so we don't check it.
1595
1596 // data->obj may be NULL, so we don't check it.
1597
1598 if (data->interp < 0) {
Victor Stinner71a35222020-03-26 22:46:14 +01001599 _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001600 return -1;
1601 }
1602
1603 if (data->new_object == NULL) {
Victor Stinner71a35222020-03-26 22:46:14 +01001604 _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001605 return -1;
1606 }
1607
1608 // data->free may be NULL, so we don't check it.
1609
1610 return 0;
1611}
1612
1613int
1614_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1615{
Victor Stinner71a35222020-03-26 22:46:14 +01001616 // PyThreadState_Get() aborts if tstate is NULL.
1617 PyThreadState *tstate = PyThreadState_Get();
1618 PyInterpreterState *interp = tstate->interp;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001619
1620 // Reset data before re-populating.
1621 *data = (_PyCrossInterpreterData){0};
1622 data->free = PyMem_RawFree; // Set a default that may be overridden.
1623
1624 // Call the "getdata" func for the object.
1625 Py_INCREF(obj);
1626 crossinterpdatafunc getdata = _lookup_getdata(obj);
1627 if (getdata == NULL) {
1628 Py_DECREF(obj);
1629 return -1;
1630 }
1631 int res = getdata(obj, data);
1632 Py_DECREF(obj);
1633 if (res != 0) {
1634 return -1;
1635 }
1636
1637 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001638 data->interp = interp->id;
Victor Stinner71a35222020-03-26 22:46:14 +01001639 if (_check_xidata(tstate, data) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001640 _PyCrossInterpreterData_Release(data);
1641 return -1;
1642 }
1643
1644 return 0;
1645}
1646
Victor Stinnere225beb2019-06-03 18:14:24 +02001647static void
Eric Snow63799132018-06-01 18:45:20 -06001648_release_xidata(void *arg)
1649{
1650 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1651 if (data->free != NULL) {
1652 data->free(data->data);
1653 }
1654 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001655}
1656
1657static void
1658_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1659 PyInterpreterState *interp,
1660 void (*func)(void *), void *arg)
1661{
1662 /* We would use Py_AddPendingCall() if it weren't specific to the
1663 * main interpreter (see bpo-33608). In the meantime we take a
1664 * naive approach.
1665 */
1666 PyThreadState *save_tstate = NULL;
1667 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1668 // XXX Using the "head" thread isn't strictly correct.
1669 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1670 // XXX Possible GILState issues?
1671 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1672 }
1673
1674 func(arg);
1675
1676 // Switch back.
1677 if (save_tstate != NULL) {
1678 _PyThreadState_Swap(gilstate, save_tstate);
1679 }
Eric Snow63799132018-06-01 18:45:20 -06001680}
1681
Eric Snow7f8bfc92018-01-29 18:23:44 -07001682void
1683_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1684{
1685 if (data->data == NULL && data->obj == NULL) {
1686 // Nothing to release!
1687 return;
1688 }
1689
Victor Stinnere225beb2019-06-03 18:14:24 +02001690 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001691 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1692 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001693 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001694 if (data->free != NULL) {
1695 // XXX Someone leaked some memory...
1696 }
1697 return;
1698 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001699
Eric Snow7f8bfc92018-01-29 18:23:44 -07001700 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001701 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1702 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001703}
1704
1705PyObject *
1706_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1707{
1708 return data->new_object(data);
1709}
1710
1711/* registry of {type -> crossinterpdatafunc} */
1712
1713/* For now we use a global registry of shareable classes. An
1714 alternative would be to add a tp_* slot for a class's
1715 crossinterpdatafunc. It would be simpler and more efficient. */
1716
1717static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001718_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1719 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001720{
1721 // Note that we effectively replace already registered classes
1722 // rather than failing.
1723 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1724 if (newhead == NULL)
1725 return -1;
1726 newhead->cls = cls;
1727 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001728 newhead->next = xidregistry->head;
1729 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001730 return 0;
1731}
1732
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001733static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001734
1735int
Eric Snowc11183c2019-03-15 16:35:46 -06001736_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001737 crossinterpdatafunc getdata)
1738{
1739 if (!PyType_Check(cls)) {
1740 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1741 return -1;
1742 }
1743 if (getdata == NULL) {
1744 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1745 return -1;
1746 }
1747
1748 // Make sure the class isn't ever deallocated.
1749 Py_INCREF((PyObject *)cls);
1750
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001751 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1752 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1753 if (xidregistry->head == NULL) {
1754 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001755 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001756 int res = _register_xidata(xidregistry, cls, getdata);
1757 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001758 return res;
1759}
1760
Eric Snow6d2cd902018-05-16 15:04:57 -04001761/* Cross-interpreter objects are looked up by exact match on the class.
1762 We can reassess this policy when we move from a global registry to a
1763 tp_* slot. */
1764
Eric Snow7f8bfc92018-01-29 18:23:44 -07001765crossinterpdatafunc
1766_PyCrossInterpreterData_Lookup(PyObject *obj)
1767{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001768 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001769 PyObject *cls = PyObject_Type(obj);
1770 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001771 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1772 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001773 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001774 _register_builtins_for_crossinterpreter_data(xidregistry);
1775 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001776 }
1777 for(; cur != NULL; cur = cur->next) {
1778 if (cur->cls == (PyTypeObject *)cls) {
1779 getdata = cur->getdata;
1780 break;
1781 }
1782 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001783 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001784 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001785 return getdata;
1786}
1787
1788/* cross-interpreter data for builtin types */
1789
Eric Snow6d2cd902018-05-16 15:04:57 -04001790struct _shared_bytes_data {
1791 char *bytes;
1792 Py_ssize_t len;
1793};
1794
Eric Snow7f8bfc92018-01-29 18:23:44 -07001795static PyObject *
1796_new_bytes_object(_PyCrossInterpreterData *data)
1797{
Eric Snow6d2cd902018-05-16 15:04:57 -04001798 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1799 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001800}
1801
1802static int
1803_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1804{
Eric Snow6d2cd902018-05-16 15:04:57 -04001805 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1806 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1807 return -1;
1808 }
1809 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001810 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001811 data->obj = obj; // Will be "released" (decref'ed) when data released.
1812 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001813 data->free = PyMem_Free;
1814 return 0;
1815}
1816
1817struct _shared_str_data {
1818 int kind;
1819 const void *buffer;
1820 Py_ssize_t len;
1821};
1822
1823static PyObject *
1824_new_str_object(_PyCrossInterpreterData *data)
1825{
1826 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1827 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1828}
1829
1830static int
1831_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1832{
1833 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1834 shared->kind = PyUnicode_KIND(obj);
1835 shared->buffer = PyUnicode_DATA(obj);
An Long29c11722020-06-13 20:26:01 +08001836 shared->len = PyUnicode_GET_LENGTH(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001837 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001838 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001839 data->obj = obj; // Will be "released" (decref'ed) when data released.
1840 data->new_object = _new_str_object;
1841 data->free = PyMem_Free;
1842 return 0;
1843}
1844
1845static PyObject *
1846_new_long_object(_PyCrossInterpreterData *data)
1847{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001848 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001849}
1850
1851static int
1852_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1853{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001854 /* Note that this means the size of shareable ints is bounded by
1855 * sys.maxsize. Hence on 32-bit architectures that is half the
1856 * size of maximum shareable ints on 64-bit.
1857 */
1858 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001859 if (value == -1 && PyErr_Occurred()) {
1860 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1861 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1862 }
1863 return -1;
1864 }
1865 data->data = (void *)value;
1866 data->obj = NULL;
1867 data->new_object = _new_long_object;
1868 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001869 return 0;
1870}
1871
1872static PyObject *
1873_new_none_object(_PyCrossInterpreterData *data)
1874{
1875 // XXX Singleton refcounts are problematic across interpreters...
1876 Py_INCREF(Py_None);
1877 return Py_None;
1878}
1879
1880static int
1881_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1882{
1883 data->data = NULL;
1884 // data->obj remains NULL
1885 data->new_object = _new_none_object;
1886 data->free = NULL; // There is nothing to free.
1887 return 0;
1888}
1889
1890static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001891_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001892{
1893 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001894 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001895 Py_FatalError("could not register None for cross-interpreter sharing");
1896 }
1897
Eric Snow6d2cd902018-05-16 15:04:57 -04001898 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001899 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001900 Py_FatalError("could not register int for cross-interpreter sharing");
1901 }
1902
Eric Snow7f8bfc92018-01-29 18:23:44 -07001903 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001904 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001905 Py_FatalError("could not register bytes for cross-interpreter sharing");
1906 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001907
1908 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001909 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001910 Py_FatalError("could not register str for cross-interpreter sharing");
1911 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001912}
1913
1914
Victor Stinner0b72b232020-03-12 23:18:39 +01001915_PyFrameEvalFunction
1916_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1917{
1918 return interp->eval_frame;
1919}
1920
1921
1922void
1923_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1924 _PyFrameEvalFunction eval_frame)
1925{
1926 interp->eval_frame = eval_frame;
1927}
1928
Victor Stinnerda7933e2020-04-13 03:04:28 +02001929
1930const PyConfig*
1931_PyInterpreterState_GetConfig(PyInterpreterState *interp)
1932{
1933 return &interp->config;
1934}
1935
1936
Victor Stinner048a3562020-11-05 00:45:56 +01001937int
1938_PyInterpreterState_GetConfigCopy(PyConfig *config)
Victor Stinnerda7933e2020-04-13 03:04:28 +02001939{
Victor Stinner048a3562020-11-05 00:45:56 +01001940 PyInterpreterState *interp = PyInterpreterState_Get();
1941
1942 PyStatus status = _PyConfig_Copy(config, &interp->config);
1943 if (PyStatus_Exception(status)) {
1944 _PyErr_SetFromPyStatus(status);
1945 return -1;
1946 }
1947 return 0;
Victor Stinnerda7933e2020-04-13 03:04:28 +02001948}
1949
1950
1951const PyConfig*
1952_Py_GetConfig(void)
1953{
1954 assert(PyGILState_Check());
1955 PyThreadState *tstate = _PyThreadState_GET();
1956 return _PyInterpreterState_GetConfig(tstate->interp);
1957}
1958
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001959#ifdef __cplusplus
1960}
1961#endif