blob: eb24f2b800607fd8381d337f01dc45c8e95b20f6 [file] [log] [blame]
Guido van Rossuma027efa1997-05-05 20:56:21 +00001
2/* Thread and interpreter state structures and their interfaces */
3
4#include "Python.h"
Victor Stinner09532fe2019-05-10 23:39:09 +02005#include "pycore_ceval.h"
Victor Stinner331a6a52019-05-27 16:39:22 +02006#include "pycore_initconfig.h"
Victor Stinner0e427c62020-03-25 21:22:55 +01007#include "pycore_pyerrors.h"
8#include "pycore_pylifecycle.h"
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +02009#include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
Victor Stinnere5014be2020-04-14 17:52:15 +020010#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner71a35222020-03-26 22:46:14 +010011#include "pycore_sysmodule.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +000012
Tim Peters84705582004-10-10 02:47:33 +000013/* --------------------------------------------------------------------------
14CAUTION
15
Victor Stinner1a7425f2013-07-07 16:25:15 +020016Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
17number of these functions are advertised as safe to call when the GIL isn't
18held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
19debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
20to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000021-------------------------------------------------------------------------- */
22
Martin v. Löwisf0473d52001-07-18 16:17:16 +000023#ifdef HAVE_DLOPEN
24#ifdef HAVE_DLFCN_H
25#include <dlfcn.h>
26#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030027#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000028#define RTLD_LAZY 1
29#endif
30#endif
31
Benjamin Peterson43162b82012-04-13 11:58:27 -040032#ifdef __cplusplus
33extern "C" {
34#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000035
Victor Stinner10c8e6a2019-04-26 01:53:18 +020036#define _PyRuntimeGILState_GetThreadState(gilstate) \
37 ((PyThreadState*)_Py_atomic_load_relaxed(&(gilstate)->tstate_current))
38#define _PyRuntimeGILState_SetThreadState(gilstate, value) \
39 _Py_atomic_store_relaxed(&(gilstate)->tstate_current, \
40 (uintptr_t)(value))
41
42/* Forward declarations */
43static PyThreadState *_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate);
Victor Stinner9da74302019-11-20 11:17:17 +010044static void _PyThreadState_Delete(PyThreadState *tstate, int check_current);
Victor Stinner10c8e6a2019-04-26 01:53:18 +020045
46
Victor Stinner331a6a52019-05-27 16:39:22 +020047static PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010048_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060049{
Steve Dowerb82e17e2019-05-23 08:45:22 -070050 /* We preserve the hook across init, because there is
51 currently no public API to set it between runtime
52 initialization and interpreter initialization. */
53 void *open_code_hook = runtime->open_code_hook;
54 void *open_code_userdata = runtime->open_code_userdata;
55 _Py_AuditHookEntry *audit_hook_head = runtime->audit_hook_head;
56
Eric Snow2ebc5ce2017-09-07 23:51:28 -060057 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010058
Steve Dowerb82e17e2019-05-23 08:45:22 -070059 runtime->open_code_hook = open_code_hook;
60 runtime->open_code_userdata = open_code_userdata;
61 runtime->audit_hook_head = audit_hook_head;
62
Victor Stinnerdab84232020-03-17 18:56:44 +010063 _PyEval_InitRuntimeState(&runtime->ceval);
Victor Stinner441b10c2019-09-28 04:28:35 +020064
Victor Stinner3c30a762019-10-01 10:56:37 +020065 PyPreConfig_InitPythonConfig(&runtime->preconfig);
Michael W. Hudson188d4362005-06-20 16:52:57 +000066
Eric Snow2ebc5ce2017-09-07 23:51:28 -060067 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080068
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090069 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
70 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080071 Py_tss_t initial = Py_tss_NEEDS_INIT;
72 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000073
Eric Snow2ebc5ce2017-09-07 23:51:28 -060074 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080075 if (runtime->interpreters.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020076 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080077 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060078 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070079
80 runtime->xidregistry.mutex = PyThread_allocate_lock();
81 if (runtime->xidregistry.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020082 return _PyStatus_ERR("Can't initialize threads for cross-interpreter data registry");
Eric Snow7f8bfc92018-01-29 18:23:44 -070083 }
84
Eric Snow8479a342019-03-08 23:44:33 -070085 // Set it to the ID of the main thread of the main interpreter.
86 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070087
Victor Stinner331a6a52019-05-27 16:39:22 +020088 return _PyStatus_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060089}
Eric Snow05351c12017-09-05 21:43:08 -070090
Victor Stinner331a6a52019-05-27 16:39:22 +020091PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010092_PyRuntimeState_Init(_PyRuntimeState *runtime)
93{
94 /* Force default allocator, since _PyRuntimeState_Fini() must
95 use the same allocator than this function. */
96 PyMemAllocatorEx old_alloc;
97 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
98
Victor Stinner331a6a52019-05-27 16:39:22 +020099 PyStatus status = _PyRuntimeState_Init_impl(runtime);
Victor Stinner5d39e042017-11-29 17:20:38 +0100100
101 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinner331a6a52019-05-27 16:39:22 +0200102 return status;
Victor Stinner5d39e042017-11-29 17:20:38 +0100103}
104
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600105void
106_PyRuntimeState_Fini(_PyRuntimeState *runtime)
107{
Victor Stinner5d39e042017-11-29 17:20:38 +0100108 /* Force the allocator used by _PyRuntimeState_Init(). */
109 PyMemAllocatorEx old_alloc;
110 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -0800111
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600112 if (runtime->interpreters.mutex != NULL) {
113 PyThread_free_lock(runtime->interpreters.mutex);
114 runtime->interpreters.mutex = NULL;
115 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800116
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100117 if (runtime->xidregistry.mutex != NULL) {
118 PyThread_free_lock(runtime->xidregistry.mutex);
119 runtime->xidregistry.mutex = NULL;
120 }
121
Victor Stinnerccb04422017-11-16 03:20:31 -0800122 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600123}
124
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900125#ifdef HAVE_FORK
Eric Snow8479a342019-03-08 23:44:33 -0700126/* This function is called from PyOS_AfterFork_Child to ensure that
Victor Stinner26881c82020-06-02 15:51:37 +0200127 newly created child processes do not share locks with the parent. */
128PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200129_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700130{
131 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200132 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700133
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200134 /* Force default allocator, since _PyRuntimeState_Fini() must
135 use the same allocator than this function. */
136 PyMemAllocatorEx old_alloc;
137 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
138
Victor Stinner26881c82020-06-02 15:51:37 +0200139 int reinit_interp = _PyThread_at_fork_reinit(&runtime->interpreters.mutex);
140 int reinit_main_id = _PyThread_at_fork_reinit(&runtime->interpreters.main->id_mutex);
141 int reinit_xidregistry = _PyThread_at_fork_reinit(&runtime->xidregistry.mutex);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200142
143 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
144
Victor Stinner26881c82020-06-02 15:51:37 +0200145 if (reinit_interp < 0
146 || reinit_main_id < 0
147 || reinit_xidregistry < 0)
148 {
149 return _PyStatus_ERR("Failed to reinitialize runtime locks");
Eric Snow8479a342019-03-08 23:44:33 -0700150
Eric Snow8479a342019-03-08 23:44:33 -0700151 }
Victor Stinner26881c82020-06-02 15:51:37 +0200152 return _PyStatus_OK();
Eric Snow8479a342019-03-08 23:44:33 -0700153}
Dong-hee Na62f75fe2020-04-15 01:16:24 +0900154#endif
Eric Snow8479a342019-03-08 23:44:33 -0700155
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200156#define HEAD_LOCK(runtime) \
157 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
158#define HEAD_UNLOCK(runtime) \
159 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700160
Victor Stinner8bb32302019-04-24 16:47:40 +0200161/* Forward declaration */
162static void _PyGILState_NoteThreadState(
163 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000164
Victor Stinner331a6a52019-05-27 16:39:22 +0200165PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600166_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700167{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200168 struct pyinterpreters *interpreters = &runtime->interpreters;
169 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100170
171 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
172 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200173 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100174 /* Force default allocator, since _PyRuntimeState_Fini() must
175 use the same allocator than this function. */
176 PyMemAllocatorEx old_alloc;
177 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
178
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200179 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100180
181 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
182
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200183 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200184 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800185 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600186 }
Victor Stinner5d926472018-03-06 14:31:37 +0100187
Victor Stinner331a6a52019-05-27 16:39:22 +0200188 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700189}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000190
191PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000192PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000193{
Victor Stinner71a35222020-03-26 22:46:14 +0100194 PyThreadState *tstate = _PyThreadState_GET();
195 /* tstate is NULL when Py_InitializeFromConfig() calls
196 PyInterpreterState_New() to create the main interpreter. */
197 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_New", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700198 return NULL;
199 }
200
Andy Lester7668a8b2020-03-24 23:26:44 -0500201 PyInterpreterState *interp = PyMem_RawCalloc(1, sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100202 if (interp == NULL) {
203 return NULL;
204 }
205
Eric Snow4c6955e2018-02-16 18:53:40 -0700206 interp->id_refcount = -1;
Victor Stinner022be022019-05-22 23:58:50 +0200207
Victor Stinner71a35222020-03-26 22:46:14 +0100208 /* Don't get runtime from tstate since tstate can be NULL */
Victor Stinner01b1cc12019-11-20 02:27:56 +0100209 _PyRuntimeState *runtime = &_PyRuntime;
210 interp->runtime = runtime;
211
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200212 if (_PyEval_InitState(&interp->ceval) < 0) {
213 goto out_of_memory;
214 }
215
Victor Stinner72474072019-11-20 12:25:50 +0100216 _PyGC_InitState(&interp->gc);
Victor Stinner8462a492019-10-01 12:06:16 +0200217 PyConfig_InitPythonConfig(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200218
Victor Stinnerd4341102017-11-23 00:12:09 +0100219 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000220#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300221#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100222 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000223#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100224 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000225#endif
226#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000227
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200228 struct pyinterpreters *interpreters = &runtime->interpreters;
229
230 HEAD_LOCK(runtime);
231 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100232 /* overflow or Py_Initialize() not called! */
Victor Stinner71a35222020-03-26 22:46:14 +0100233 if (tstate != NULL) {
234 _PyErr_SetString(tstate, PyExc_RuntimeError,
235 "failed to get an interpreter ID");
236 }
Pablo Galindo95d630e2018-08-31 22:49:29 +0100237 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100238 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100239 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200240 else {
241 interp->id = interpreters->next_id;
242 interpreters->next_id += 1;
243 interp->next = interpreters->head;
244 if (interpreters->main == NULL) {
245 interpreters->main = interp;
246 }
247 interpreters->head = interp;
248 }
249 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000250
Pablo Galindo95d630e2018-08-31 22:49:29 +0100251 if (interp == NULL) {
252 return NULL;
253 }
254
Yury Selivanovf23746a2018-01-22 19:11:18 -0500255 interp->tstate_next_unique_id = 0;
256
Steve Dowerb82e17e2019-05-23 08:45:22 -0700257 interp->audit_hooks = NULL;
258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 return interp;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200260
261out_of_memory:
262 if (tstate != NULL) {
263 _PyErr_NoMemory(tstate);
264 }
265
266 PyMem_RawFree(interp);
267 return NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000268}
269
270
Victor Stinner01b1cc12019-11-20 02:27:56 +0100271void
272PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000273{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100274 _PyRuntimeState *runtime = interp->runtime;
275
Victor Stinner71a35222020-03-26 22:46:14 +0100276 /* Use the current Python thread state to call audit hooks,
277 not the current Python thread state of 'interp'. */
278 PyThreadState *tstate = _PyThreadState_GET();
279 if (_PySys_Audit(tstate, "cpython.PyInterpreterState_Clear", NULL) < 0) {
280 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700281 }
282
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200283 HEAD_LOCK(runtime);
284 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200286 }
287 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700288
289 Py_CLEAR(interp->audit_hooks);
290
Victor Stinner331a6a52019-05-27 16:39:22 +0200291 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 Py_CLEAR(interp->codec_search_path);
293 Py_CLEAR(interp->codec_search_cache);
294 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700295 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 Py_CLEAR(interp->modules_by_index);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200297 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400298 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300299 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600300 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200301#ifdef HAVE_FORK
302 Py_CLEAR(interp->before_forkers);
303 Py_CLEAR(interp->after_forkers_parent);
304 Py_CLEAR(interp->after_forkers_child);
305#endif
Victor Stinner7b3c2522020-03-07 00:24:23 +0100306 if (_PyRuntimeState_GetFinalizing(runtime) == NULL) {
Eric Snow86ea5812019-05-10 13:29:55 -0400307 _PyWarnings_Fini(interp);
308 }
Hai Shi8ecc0c42020-08-13 05:23:30 +0800309 /* We don't clear sysdict and builtins until the end of this function.
310 Because clearing other attributes can execute arbitrary Python code
311 which requires sysdict and builtins. */
312 PyDict_Clear(interp->sysdict);
313 PyDict_Clear(interp->builtins);
314 Py_CLEAR(interp->sysdict);
315 Py_CLEAR(interp->builtins);
316
Eric Snow5be45a62019-03-08 22:47:07 -0700317 // XXX Once we have one allocator per interpreter (i.e.
318 // per-interpreter GC) we must ensure that all of the interpreter's
319 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000320}
321
322
323static void
Victor Stinner9da74302019-11-20 11:17:17 +0100324zapthreads(PyInterpreterState *interp, int check_current)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000325{
Victor Stinner9da74302019-11-20 11:17:17 +0100326 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 /* No need to lock the mutex here because this should only happen
328 when the threads are all really dead (XXX famous last words). */
Victor Stinner9da74302019-11-20 11:17:17 +0100329 while ((tstate = interp->tstate_head) != NULL) {
330 _PyThreadState_Delete(tstate, check_current);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000332}
333
334
Victor Stinner01b1cc12019-11-20 02:27:56 +0100335void
336PyInterpreterState_Delete(PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200337{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100338 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200339 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner9da74302019-11-20 11:17:17 +0100340 zapthreads(interp, 0);
341
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200342 _PyEval_FiniState(&interp->ceval);
343
Victor Stinner9da74302019-11-20 11:17:17 +0100344 /* Delete current thread. After this, many C API calls become crashy. */
345 _PyThreadState_Swap(&runtime->gilstate, NULL);
346
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200347 HEAD_LOCK(runtime);
348 PyInterpreterState **p;
349 for (p = &interpreters->head; ; p = &(*p)->next) {
350 if (*p == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100351 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200352 }
353 if (*p == interp) {
354 break;
355 }
356 }
357 if (interp->tstate_head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100358 Py_FatalError("remaining threads");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200359 }
360 *p = interp->next;
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200361
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200362 if (interpreters->main == interp) {
363 interpreters->main = NULL;
364 if (interpreters->head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100365 Py_FatalError("remaining subinterpreters");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200366 }
367 }
368 HEAD_UNLOCK(runtime);
Victor Stinnerdda5d6e2020-04-08 17:54:59 +0200369
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200370 if (interp->id_mutex != NULL) {
371 PyThread_free_lock(interp->id_mutex);
372 }
373 PyMem_RawFree(interp);
374}
375
376
Victor Stinner26881c82020-06-02 15:51:37 +0200377#ifdef HAVE_FORK
Eric Snow59032962018-09-14 14:17:20 -0700378/*
379 * Delete all interpreter states except the main interpreter. If there
380 * is a current interpreter state, it *must* be the main interpreter.
381 */
Victor Stinner26881c82020-06-02 15:51:37 +0200382PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200383_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700384{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200385 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200386 struct pyinterpreters *interpreters = &runtime->interpreters;
387
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200388 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200389 if (tstate != NULL && tstate->interp != interpreters->main) {
Victor Stinner26881c82020-06-02 15:51:37 +0200390 return _PyStatus_ERR("not main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700391 }
392
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200393 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200394 PyInterpreterState *interp = interpreters->head;
395 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100396 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200397 if (interp == interpreters->main) {
398 interpreters->main->next = NULL;
399 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100400 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700401 continue;
402 }
403
Victor Stinner01b1cc12019-11-20 02:27:56 +0100404 PyInterpreterState_Clear(interp); // XXX must activate?
Victor Stinner9da74302019-11-20 11:17:17 +0100405 zapthreads(interp, 1);
Eric Snow59032962018-09-14 14:17:20 -0700406 if (interp->id_mutex != NULL) {
407 PyThread_free_lock(interp->id_mutex);
408 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100409 PyInterpreterState *prev_interp = interp;
410 interp = interp->next;
411 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700412 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200413 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700414
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200415 if (interpreters->head == NULL) {
Victor Stinner26881c82020-06-02 15:51:37 +0200416 return _PyStatus_ERR("missing main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700417 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200418 _PyThreadState_Swap(gilstate, tstate);
Victor Stinner26881c82020-06-02 15:51:37 +0200419 return _PyStatus_OK();
Eric Snow59032962018-09-14 14:17:20 -0700420}
Victor Stinner26881c82020-06-02 15:51:37 +0200421#endif
Eric Snow59032962018-09-14 14:17:20 -0700422
423
Victor Stinnercaba55b2018-08-03 15:33:52 +0200424PyInterpreterState *
Victor Stinnerbe793732020-03-13 18:15:33 +0100425PyInterpreterState_Get(void)
Victor Stinnercaba55b2018-08-03 15:33:52 +0200426{
Victor Stinner50b48572018-11-01 01:51:40 +0100427 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200428 _Py_EnsureTstateNotNULL(tstate);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200429 PyInterpreterState *interp = tstate->interp;
430 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100431 Py_FatalError("no current interpreter");
Victor Stinnercaba55b2018-08-03 15:33:52 +0200432 }
433 return interp;
434}
435
436
Eric Snowe3774162017-05-22 19:46:40 -0700437int64_t
438PyInterpreterState_GetID(PyInterpreterState *interp)
439{
440 if (interp == NULL) {
441 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
442 return -1;
443 }
444 return interp->id;
445}
446
447
Eric Snow5be45a62019-03-08 22:47:07 -0700448static PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200449interp_look_up_id(_PyRuntimeState *runtime, int64_t requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700450{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200451 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100452 while (interp != NULL) {
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200453 int64_t id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700454 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100455 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700456 }
457 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100458 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700459 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100460 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700461 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100462 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700463}
464
Eric Snow5be45a62019-03-08 22:47:07 -0700465PyInterpreterState *
Victor Stinner1a1bd2e2020-04-17 19:13:06 +0200466_PyInterpreterState_LookUpID(int64_t requested_id)
Eric Snow5be45a62019-03-08 22:47:07 -0700467{
468 PyInterpreterState *interp = NULL;
469 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200470 _PyRuntimeState *runtime = &_PyRuntime;
471 HEAD_LOCK(runtime);
472 interp = interp_look_up_id(runtime, requested_id);
473 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700474 }
475 if (interp == NULL && !PyErr_Occurred()) {
476 PyErr_Format(PyExc_RuntimeError,
477 "unrecognized interpreter ID %lld", requested_id);
478 }
479 return interp;
480}
481
Eric Snow4c6955e2018-02-16 18:53:40 -0700482
483int
484_PyInterpreterState_IDInitref(PyInterpreterState *interp)
485{
486 if (interp->id_mutex != NULL) {
487 return 0;
488 }
489 interp->id_mutex = PyThread_allocate_lock();
490 if (interp->id_mutex == NULL) {
491 PyErr_SetString(PyExc_RuntimeError,
492 "failed to create init interpreter ID mutex");
493 return -1;
494 }
495 interp->id_refcount = 0;
496 return 0;
497}
498
499
500void
501_PyInterpreterState_IDIncref(PyInterpreterState *interp)
502{
503 if (interp->id_mutex == NULL) {
504 return;
505 }
506 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
507 interp->id_refcount += 1;
508 PyThread_release_lock(interp->id_mutex);
509}
510
511
512void
513_PyInterpreterState_IDDecref(PyInterpreterState *interp)
514{
515 if (interp->id_mutex == NULL) {
516 return;
517 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200518 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700519 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
520 assert(interp->id_refcount != 0);
521 interp->id_refcount -= 1;
522 int64_t refcount = interp->id_refcount;
523 PyThread_release_lock(interp->id_mutex);
524
Eric Snowc11183c2019-03-15 16:35:46 -0600525 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700526 // XXX Using the "head" thread isn't strictly correct.
527 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
528 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200529 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700530 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200531 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700532 }
533}
534
Eric Snowc11183c2019-03-15 16:35:46 -0600535int
536_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
537{
538 return interp->requires_idref;
539}
540
541void
542_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
543{
544 interp->requires_idref = required ? 1 : 0;
545}
546
Eric Snowc11183c2019-03-15 16:35:46 -0600547PyObject *
548_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
549{
550 if (interp->modules == NULL) {
551 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
552 return NULL;
553 }
554 return PyMapping_GetItemString(interp->modules, "__main__");
555}
556
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600557PyObject *
558PyInterpreterState_GetDict(PyInterpreterState *interp)
559{
560 if (interp->dict == NULL) {
561 interp->dict = PyDict_New();
562 if (interp->dict == NULL) {
563 PyErr_Clear();
564 }
565 }
566 /* Returning NULL means no per-interpreter dict is available. */
567 return interp->dict;
568}
569
Victor Stinner45b9be52010-03-03 23:28:07 +0000570static PyThreadState *
571new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000572{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100573 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200574 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200575 if (tstate == NULL) {
576 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000578
Victor Stinner8bb32302019-04-24 16:47:40 +0200579 tstate->interp = interp;
580
581 tstate->frame = NULL;
582 tstate->recursion_depth = 0;
583 tstate->overflowed = 0;
Victor Stinner8bb32302019-04-24 16:47:40 +0200584 tstate->stackcheck_counter = 0;
585 tstate->tracing = 0;
586 tstate->use_tracing = 0;
587 tstate->gilstate_counter = 0;
588 tstate->async_exc = NULL;
589 tstate->thread_id = PyThread_get_thread_ident();
590
591 tstate->dict = NULL;
592
593 tstate->curexc_type = NULL;
594 tstate->curexc_value = NULL;
595 tstate->curexc_traceback = NULL;
596
597 tstate->exc_state.exc_type = NULL;
598 tstate->exc_state.exc_value = NULL;
599 tstate->exc_state.exc_traceback = NULL;
600 tstate->exc_state.previous_item = NULL;
601 tstate->exc_info = &tstate->exc_state;
602
603 tstate->c_profilefunc = NULL;
604 tstate->c_tracefunc = NULL;
605 tstate->c_profileobj = NULL;
606 tstate->c_traceobj = NULL;
607
608 tstate->trash_delete_nesting = 0;
609 tstate->trash_delete_later = NULL;
610 tstate->on_delete = NULL;
611 tstate->on_delete_data = NULL;
612
613 tstate->coroutine_origin_tracking_depth = 0;
614
Victor Stinner8bb32302019-04-24 16:47:40 +0200615 tstate->async_gen_firstiter = NULL;
616 tstate->async_gen_finalizer = NULL;
617
618 tstate->context = NULL;
619 tstate->context_ver = 1;
620
Victor Stinner8bb32302019-04-24 16:47:40 +0200621 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100622 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200623 }
624
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200625 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100626 tstate->id = ++interp->tstate_next_unique_id;
Victor Stinner8bb32302019-04-24 16:47:40 +0200627 tstate->prev = NULL;
628 tstate->next = interp->tstate_head;
629 if (tstate->next)
630 tstate->next->prev = tstate;
631 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200632 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000635}
636
Victor Stinner45b9be52010-03-03 23:28:07 +0000637PyThreadState *
638PyThreadState_New(PyInterpreterState *interp)
639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000641}
642
643PyThreadState *
644_PyThreadState_Prealloc(PyInterpreterState *interp)
645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000647}
648
649void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100650_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000651{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100652 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000653}
654
Martin v. Löwis1a214512008-06-11 05:26:20 +0000655PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200656PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000657{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200658 Py_ssize_t index = module->m_base.m_index;
Victor Stinner81a7be32020-04-14 15:14:01 +0200659 PyInterpreterState *state = _PyInterpreterState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000661 if (module->m_slots) {
662 return NULL;
663 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 if (index == 0)
665 return NULL;
666 if (state->modules_by_index == NULL)
667 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200668 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 return NULL;
670 res = PyList_GET_ITEM(state->modules_by_index, index);
671 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000672}
673
674int
Victor Stinner82c83bd2019-11-22 18:52:27 +0100675_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000676{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300677 if (!def) {
Victor Stinner71a35222020-03-26 22:46:14 +0100678 assert(_PyErr_Occurred(tstate));
Berker Peksag4b7b5652016-08-22 18:05:56 +0300679 return -1;
680 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000681 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100682 _PyErr_SetString(tstate,
683 PyExc_SystemError,
684 "PyState_AddModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000685 return -1;
686 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100687
688 PyInterpreterState *interp = tstate->interp;
689 if (!interp->modules_by_index) {
690 interp->modules_by_index = PyList_New(0);
691 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100693 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100695
696 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
697 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100699 }
700 }
701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100703 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000705}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000706
Martin v. Löwis7800f752012-06-22 12:20:55 +0200707int
708PyState_AddModule(PyObject* module, struct PyModuleDef* def)
709{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200710 if (!def) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100711 Py_FatalError("module definition is NULL");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200712 return -1;
713 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100714
715 PyThreadState *tstate = _PyThreadState_GET();
716 PyInterpreterState *interp = tstate->interp;
717 Py_ssize_t index = def->m_base.m_index;
718 if (interp->modules_by_index &&
719 index < PyList_GET_SIZE(interp->modules_by_index) &&
720 module == PyList_GET_ITEM(interp->modules_by_index, index))
721 {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100722 _Py_FatalErrorFormat(__func__, "module %p already added", module);
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100723 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200724 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100725 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200726}
727
728int
729PyState_RemoveModule(struct PyModuleDef* def)
730{
Victor Stinner71a35222020-03-26 22:46:14 +0100731 PyThreadState *tstate = _PyThreadState_GET();
732 PyInterpreterState *interp = tstate->interp;
733
Nick Coghland5cacbb2015-05-23 22:24:10 +1000734 if (def->m_slots) {
Victor Stinner71a35222020-03-26 22:46:14 +0100735 _PyErr_SetString(tstate,
736 PyExc_SystemError,
737 "PyState_RemoveModule called on module with slots");
Nick Coghland5cacbb2015-05-23 22:24:10 +1000738 return -1;
739 }
Victor Stinner71a35222020-03-26 22:46:14 +0100740
741 Py_ssize_t index = def->m_base.m_index;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200742 if (index == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100743 Py_FatalError("invalid module index");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200744 }
Victor Stinner71a35222020-03-26 22:46:14 +0100745 if (interp->modules_by_index == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100746 Py_FatalError("Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200747 }
Victor Stinner71a35222020-03-26 22:46:14 +0100748 if (index > PyList_GET_SIZE(interp->modules_by_index)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100749 Py_FatalError("Module index out of bounds.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200750 }
Victor Stinner71a35222020-03-26 22:46:14 +0100751
Zackery Spytz2a893432018-12-05 00:14:00 -0700752 Py_INCREF(Py_None);
Victor Stinner71a35222020-03-26 22:46:14 +0100753 return PyList_SetItem(interp->modules_by_index, index, Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200754}
755
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200756/* Used by PyImport_Cleanup() */
Antoine Pitrou40322e62013-08-11 00:30:09 +0200757void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200758_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200759{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200760 if (!interp->modules_by_index) {
761 return;
762 }
763
764 Py_ssize_t i;
765 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
766 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
767 if (PyModule_Check(m)) {
768 /* cleanup the saved copy of module dicts */
769 PyModuleDef *md = PyModule_GetDef(m);
770 if (md) {
771 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200772 }
773 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200774 }
775
776 /* Setting modules_by_index to NULL could be dangerous, so we
777 clear the list instead. */
778 if (PyList_SetSlice(interp->modules_by_index,
779 0, PyList_GET_SIZE(interp->modules_by_index),
780 NULL)) {
781 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200782 }
783}
784
Guido van Rossuma027efa1997-05-05 20:56:21 +0000785void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000786PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000787{
Victor Stinnerda7933e2020-04-13 03:04:28 +0200788 int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200789
Victor Stinner5804f872020-03-24 16:32:26 +0100790 if (verbose && tstate->frame != NULL) {
791 /* bpo-20526: After the main thread calls
792 _PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
793 exit when trying to take the GIL. If a thread exit in the middle of
794 _PyEval_EvalFrameDefault(), tstate->frame is not reset to its
795 previous value. It is more likely with daemon threads, but it can
796 happen with regular threads if threading._shutdown() fails
797 (ex: interrupted by CTRL+C). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 fprintf(stderr,
799 "PyThreadState_Clear: warning: thread still has a frame\n");
Victor Stinner5804f872020-03-24 16:32:26 +0100800 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000801
Victor Stinner5804f872020-03-24 16:32:26 +0100802 /* Don't clear tstate->frame: it is a borrowed reference */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 Py_CLEAR(tstate->dict);
805 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 Py_CLEAR(tstate->curexc_type);
808 Py_CLEAR(tstate->curexc_value);
809 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000810
Mark Shannonae3087c2017-10-22 22:41:51 +0100811 Py_CLEAR(tstate->exc_state.exc_type);
812 Py_CLEAR(tstate->exc_state.exc_value);
813 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300814
Mark Shannonae3087c2017-10-22 22:41:51 +0100815 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200816 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100817 fprintf(stderr,
818 "PyThreadState_Clear: warning: thread still has a generator\n");
819 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 tstate->c_profilefunc = NULL;
822 tstate->c_tracefunc = NULL;
823 Py_CLEAR(tstate->c_profileobj);
824 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400825
Yury Selivanoveb636452016-09-08 22:01:51 -0700826 Py_CLEAR(tstate->async_gen_firstiter);
827 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500828
829 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100830
831 if (tstate->on_delete != NULL) {
832 tstate->on_delete(tstate->on_delete_data);
833 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000834}
835
836
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300837/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000838static void
Victor Stinner9da74302019-11-20 11:17:17 +0100839tstate_delete_common(PyThreadState *tstate,
840 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000841{
Victor Stinner3026cad2020-06-01 16:02:40 +0200842 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200843 PyInterpreterState *interp = tstate->interp;
844 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100845 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200846 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100847 _PyRuntimeState *runtime = interp->runtime;
848
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200849 HEAD_LOCK(runtime);
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100850 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200851 tstate->prev->next = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100852 }
853 else {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200854 interp->tstate_head = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100855 }
856 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200857 tstate->next->prev = tstate->prev;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100858 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200859 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100860
Victor Stinner9da74302019-11-20 11:17:17 +0100861 if (gilstate->autoInterpreterState &&
862 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
863 {
864 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
865 }
866}
867
868
869static void
870_PyThreadState_Delete(PyThreadState *tstate, int check_current)
871{
872 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
873 if (check_current) {
874 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100875 _Py_FatalErrorFormat(__func__, "tstate %p is still current", tstate);
Victor Stinner9da74302019-11-20 11:17:17 +0100876 }
877 }
878 tstate_delete_common(tstate, gilstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100879 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000880}
881
882
Victor Stinner01b1cc12019-11-20 02:27:56 +0100883void
884PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000885{
Victor Stinner9da74302019-11-20 11:17:17 +0100886 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200887}
888
889
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300890void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100891_PyThreadState_DeleteCurrent(PyThreadState *tstate)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200892{
Victor Stinner3026cad2020-06-01 16:02:40 +0200893 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100894 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner9da74302019-11-20 11:17:17 +0100895 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200896 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100897 _PyEval_ReleaseLock(tstate);
898 PyMem_RawFree(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000899}
Guido van Rossum29757862001-01-23 01:46:06 +0000900
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300901void
902PyThreadState_DeleteCurrent(void)
903{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100904 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
905 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
906 _PyThreadState_DeleteCurrent(tstate);
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300907}
908
Guido van Rossum29757862001-01-23 01:46:06 +0000909
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200910/*
911 * Delete all thread states except the one passed as argument.
912 * Note that, if there is a current thread state, it *must* be the one
913 * passed as argument. Also, this won't touch any other interpreters
914 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000915 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200916 */
917void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200918_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200919{
920 PyInterpreterState *interp = tstate->interp;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100921
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200922 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200923 /* Remove all thread states, except tstate, from the linked list of
924 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200925 without holding the lock. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100926 PyThreadState *list = interp->tstate_head;
927 if (list == tstate) {
928 list = tstate->next;
929 }
930 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200931 tstate->prev->next = tstate->next;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100932 }
933 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200934 tstate->next->prev = tstate->prev;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100935 }
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200936 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200937 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200938 HEAD_UNLOCK(runtime);
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100939
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200940 /* Clear and deallocate all stale thread states. Even if this
941 executes Python code, we should be safe since it executes
942 in the current thread, not one of the stale threads. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100943 PyThreadState *p, *next;
944 for (p = list; p; p = next) {
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200945 next = p->next;
946 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200947 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200948 }
949}
950
951
Victor Stinnere838a932020-05-05 19:56:48 +0200952#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
953PyThreadState*
954_PyThreadState_GetTSS(void) {
955 return PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
956}
957#endif
958
959
Guido van Rossuma027efa1997-05-05 20:56:21 +0000960PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100961_PyThreadState_UncheckedGet(void)
962{
Victor Stinner50b48572018-11-01 01:51:40 +0100963 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100964}
965
966
967PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000968PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000969{
Victor Stinner50b48572018-11-01 01:51:40 +0100970 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200971 _Py_EnsureTstateNotNULL(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000973}
974
975
Victor Stinner09532fe2019-05-10 23:39:09 +0200976PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200977_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000978{
Victor Stinnere838a932020-05-05 19:56:48 +0200979#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
980 PyThreadState *oldts = _PyThreadState_GetTSS();
981#else
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200982 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Victor Stinnere838a932020-05-05 19:56:48 +0200983#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000984
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200985 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 /* It should not be possible for more than one thread state
987 to be used for a thread. Check this the best we can in debug
988 builds.
989 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200990#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 if (newts) {
992 /* This can be called from PyEval_RestoreThread(). Similar
993 to it, we need to ensure errno doesn't change.
994 */
995 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200996 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 if (check && check->interp == newts->interp && check != newts)
998 Py_FatalError("Invalid thread state for this thread");
999 errno = err;
1000 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001001#endif
Victor Stinnere838a932020-05-05 19:56:48 +02001002#ifdef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
1003 PyThread_tss_set(&gilstate->autoTSSkey, newts);
1004#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +00001006}
Guido van Rossumede04391998-04-10 20:18:25 +00001007
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001008PyThreadState *
1009PyThreadState_Swap(PyThreadState *newts)
1010{
1011 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
1012}
1013
Guido van Rossumede04391998-04-10 20:18:25 +00001014/* An extension mechanism to store arbitrary additional per-thread state.
1015 PyThreadState_GetDict() returns a dictionary that can be used to hold such
1016 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +00001017 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
1018 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +00001019
1020PyObject *
Victor Stinner0e427c62020-03-25 21:22:55 +01001021_PyThreadState_GetDict(PyThreadState *tstate)
1022{
1023 assert(tstate != NULL);
1024 if (tstate->dict == NULL) {
1025 tstate->dict = PyDict_New();
1026 if (tstate->dict == NULL) {
1027 _PyErr_Clear(tstate);
1028 }
1029 }
1030 return tstate->dict;
1031}
1032
1033
1034PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001035PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +00001036{
Victor Stinner50b48572018-11-01 01:51:40 +01001037 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner0e427c62020-03-25 21:22:55 +01001038 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 }
Victor Stinner0e427c62020-03-25 21:22:55 +01001041 return _PyThreadState_GetDict(tstate);
Guido van Rossumede04391998-04-10 20:18:25 +00001042}
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001043
1044
Victor Stinner8fb02b62020-03-13 23:38:08 +01001045PyInterpreterState *
1046PyThreadState_GetInterpreter(PyThreadState *tstate)
1047{
1048 assert(tstate != NULL);
Victor Stinner8fb02b62020-03-13 23:38:08 +01001049 return tstate->interp;
1050}
1051
1052
Victor Stinner4386b902020-04-29 03:01:43 +02001053PyFrameObject*
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001054PyThreadState_GetFrame(PyThreadState *tstate)
1055{
1056 assert(tstate != NULL);
Victor Stinner4386b902020-04-29 03:01:43 +02001057 PyFrameObject *frame = tstate->frame;
1058 Py_XINCREF(frame);
1059 return frame;
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001060}
1061
1062
Victor Stinner5c3cda02020-03-25 21:23:53 +01001063uint64_t
1064PyThreadState_GetID(PyThreadState *tstate)
1065{
1066 assert(tstate != NULL);
1067 return tstate->id;
1068}
1069
1070
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001071/* Asynchronously raise an exception in a thread.
1072 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001073 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001074 to call this, or use ctypes. Must be called with the GIL held.
1075 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1076 match any known thread id). Can be called with exc=NULL to clear an
1077 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001078
1079int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001080PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1081{
Victor Stinner09532fe2019-05-10 23:39:09 +02001082 _PyRuntimeState *runtime = &_PyRuntime;
1083 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 /* Although the GIL is held, a few C API functions can be called
1086 * without the GIL held, and in particular some that create and
1087 * destroy thread and interpreter states. Those can mutate the
1088 * list of thread states we're traversing, so to prevent that we lock
1089 * head_mutex for the duration.
1090 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001091 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001092 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1093 if (tstate->thread_id != id) {
1094 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001096
1097 /* Tricky: we need to decref the current value
1098 * (if any) in tstate->async_exc, but that can in turn
1099 * allow arbitrary Python code to run, including
1100 * perhaps calls to this function. To prevent
1101 * deadlock, we need to release head_mutex before
1102 * the decref.
1103 */
1104 PyObject *old_exc = tstate->async_exc;
1105 Py_XINCREF(exc);
1106 tstate->async_exc = exc;
1107 HEAD_UNLOCK(runtime);
1108
1109 Py_XDECREF(old_exc);
1110 _PyEval_SignalAsyncExc(tstate);
1111 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001113 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001115}
1116
1117
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001118/* Routines for advanced debuggers, requested by David Beazley.
1119 Don't use unless you know what you are doing! */
1120
1121PyInterpreterState *
1122PyInterpreterState_Head(void)
1123{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001124 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001125}
1126
1127PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001128PyInterpreterState_Main(void)
1129{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001130 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001131}
1132
1133PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001134PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001136}
1137
1138PyThreadState *
1139PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001141}
1142
1143PyThreadState *
1144PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001146}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001147
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001148/* The implementation of sys._current_frames(). This is intended to be
1149 called with the GIL held, as it will be when called via
1150 sys._current_frames(). It's possible it would work fine even without
1151 the GIL held, but haven't thought enough about that.
1152*/
1153PyObject *
1154_PyThread_CurrentFrames(void)
1155{
Victor Stinner71a35222020-03-26 22:46:14 +01001156 PyThreadState *tstate = _PyThreadState_GET();
1157 if (_PySys_Audit(tstate, "sys._current_frames", NULL) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -07001158 return NULL;
1159 }
1160
Victor Stinner71a35222020-03-26 22:46:14 +01001161 PyObject *result = PyDict_New();
1162 if (result == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 return NULL;
Victor Stinner71a35222020-03-26 22:46:14 +01001164 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 /* for i in all interpreters:
1167 * for t in all of i's thread states:
1168 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001169 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 * need to grab head_mutex for the duration.
1171 */
Victor Stinner71a35222020-03-26 22:46:14 +01001172 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001173 HEAD_LOCK(runtime);
Victor Stinner71a35222020-03-26 22:46:14 +01001174 PyInterpreterState *i;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001175 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 PyThreadState *t;
1177 for (t = i->tstate_head; t != NULL; t = t->next) {
Victor Stinner4386b902020-04-29 03:01:43 +02001178 PyFrameObject *frame = t->frame;
Victor Stinner71a35222020-03-26 22:46:14 +01001179 if (frame == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 continue;
Victor Stinner71a35222020-03-26 22:46:14 +01001181 }
1182 PyObject *id = PyLong_FromUnsignedLong(t->thread_id);
1183 if (id == NULL) {
1184 goto fail;
1185 }
1186 int stat = PyDict_SetItem(result, id, (PyObject *)frame);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 Py_DECREF(id);
Victor Stinner71a35222020-03-26 22:46:14 +01001188 if (stat < 0) {
1189 goto fail;
1190 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 }
1192 }
Victor Stinner71a35222020-03-26 22:46:14 +01001193 goto done;
1194
1195fail:
1196 Py_CLEAR(result);
1197
1198done:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001199 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001201}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001202
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001203/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001204
1205/* Keep this as a static, as it is not reliable! It can only
1206 ever be compared to the state for the *current* thread.
1207 * If not equal, then it doesn't matter that the actual
1208 value may change immediately after comparison, as it can't
1209 possibly change to the current thread's state.
1210 * If equal, then the current thread holds the lock, so the value can't
1211 change until we yield the lock.
1212*/
1213static int
1214PyThreadState_IsCurrent(PyThreadState *tstate)
1215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001217 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001218 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1219 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001220}
1221
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001222/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001223 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001224*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001225PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001226_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001227{
Victor Stinnerdda5d6e2020-04-08 17:54:59 +02001228 if (!_Py_IsMainInterpreter(tstate)) {
1229 /* Currently, PyGILState is shared by all interpreters. The main
1230 * interpreter is responsible to initialize it. */
1231 return _PyStatus_OK();
1232 }
1233
Victor Stinner8bb32302019-04-24 16:47:40 +02001234 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001235 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001236 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001237
Victor Stinner01b1cc12019-11-20 02:27:56 +01001238 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001239
1240 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001241 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001242 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001243 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001244 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1245 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001246
Victor Stinner8bb32302019-04-24 16:47:40 +02001247 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001248 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001249}
1250
Victor Stinner861d9ab2016-03-16 22:45:24 +01001251PyInterpreterState *
1252_PyGILState_GetInterpreterStateUnsafe(void)
1253{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001254 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001255}
1256
Tim Peters19717fa2004-10-09 17:38:29 +00001257void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001258_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001259{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001260 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001261 PyThread_tss_delete(&gilstate->autoTSSkey);
1262 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001263}
1264
Victor Stinner26881c82020-06-02 15:51:37 +02001265#ifdef HAVE_FORK
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001266/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001267 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001268 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001269 */
Victor Stinner26881c82020-06-02 15:51:37 +02001270PyStatus
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001271_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001272{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001273 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001274 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001275
1276 PyThread_tss_delete(&gilstate->autoTSSkey);
1277 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner26881c82020-06-02 15:51:37 +02001278 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001279 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001280
Charles-François Natalia233df82011-11-22 19:49:51 +01001281 /* If the thread had an associated auto thread state, reassociate it with
1282 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001283 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001284 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001285 {
Victor Stinner26881c82020-06-02 15:51:37 +02001286 return _PyStatus_ERR("failed to set autoTSSkey");
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001287 }
Victor Stinner26881c82020-06-02 15:51:37 +02001288 return _PyStatus_OK();
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001289}
Victor Stinner26881c82020-06-02 15:51:37 +02001290#endif
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001291
Michael W. Hudson188d4362005-06-20 16:52:57 +00001292/* When a thread state is created for a thread by some mechanism other than
1293 PyGILState_Ensure, it's important that the GILState machinery knows about
1294 it so it doesn't try to create another thread state for the thread (this is
1295 a better fix for SF bug #1010677 than the first one attempted).
1296*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001297static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001298_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001299{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001300 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001301 threadstate created in Py_Initialize(). Don't do anything for now
1302 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001303 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001305 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001306
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001307 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 The only situation where you can legitimately have more than one
1310 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001311 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001312
Victor Stinner590cebe2013-12-13 11:08:56 +01001313 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1314 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001315
Victor Stinner590cebe2013-12-13 11:08:56 +01001316 The first thread state created for that given OS level thread will
1317 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001319 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1320 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001321 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001322 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001323 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 /* PyGILState_Release must not try to delete this thread state. */
1326 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001327}
1328
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001329/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001330static PyThreadState *
1331_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1332{
1333 if (gilstate->autoInterpreterState == NULL)
1334 return NULL;
1335 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1336}
1337
Tim Peters19717fa2004-10-09 17:38:29 +00001338PyThreadState *
1339PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001340{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001341 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001342}
1343
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001344int
1345PyGILState_Check(void)
1346{
Victor Stinner1c4cbdf2020-04-13 11:45:21 +02001347 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1348 if (!gilstate->check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001349 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001350 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001351
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001352 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1353 return 1;
1354 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001355
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001356 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1357 if (tstate == NULL) {
1358 return 0;
1359 }
1360
1361 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001362}
1363
Tim Peters19717fa2004-10-09 17:38:29 +00001364PyGILState_STATE
1365PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001366{
Victor Stinner175a7042020-03-10 00:37:48 +01001367 _PyRuntimeState *runtime = &_PyRuntime;
1368 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 /* Note that we do not auto-init Python here - apart from
1371 potential races with 2 threads auto-initializing, pep-311
1372 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001373 called Py_Initialize(). */
1374
1375 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1376 called by Py_Initialize() */
Victor Stinnere838a932020-05-05 19:56:48 +02001377#ifndef EXPERIMENTAL_ISOLATED_SUBINTERPRETERS
Victor Stinner175a7042020-03-10 00:37:48 +01001378 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinnere838a932020-05-05 19:56:48 +02001379#endif
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001380 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001381
Victor Stinner175a7042020-03-10 00:37:48 +01001382 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1383 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001385 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001386 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001387 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001389 }
1390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 /* This is our thread state! We'll need to delete it in the
1392 matching call to PyGILState_Release(). */
1393 tcur->gilstate_counter = 0;
1394 current = 0; /* new thread state is never current */
1395 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001396 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001398 }
1399
1400 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001402 }
1403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 /* Update our counter in the thread-state - no need for locks:
1405 - tcur will remain valid as we hold the GIL.
1406 - the counter is safe as we are the only thread "allowed"
1407 to modify this value
1408 */
1409 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001412}
1413
Tim Peters19717fa2004-10-09 17:38:29 +00001414void
1415PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001416{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001417 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001418 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1419 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 Py_FatalError("auto-releasing thread-state, "
1421 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001422 }
1423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 /* We must hold the GIL and have our thread state current */
1425 /* XXX - remove the check - the assert should be fine,
1426 but while this is very new (April 2003), the extra check
1427 by release-only users can't hurt.
1428 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001429 if (!PyThreadState_IsCurrent(tstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001430 _Py_FatalErrorFormat(__func__,
1431 "thread state %p must be current when releasing",
1432 tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001433 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001434 assert(PyThreadState_IsCurrent(tstate));
1435 --tstate->gilstate_counter;
1436 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 /* If we're going to destroy this thread-state, we must
1439 * clear it while the GIL is held, as destructors may run.
1440 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001441 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 /* can't have been locked when we created it */
1443 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001444 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 /* Delete the thread-state. Note this releases the GIL too!
1446 * It's vital that the GIL be held here, to avoid shutdown
1447 * races; see bugs 225673 and 1061968 (that nasty bug has a
1448 * habit of coming back).
1449 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001450 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1451 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 }
1453 /* Release the lock if necessary */
1454 else if (oldstate == PyGILState_UNLOCKED)
1455 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001456}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001457
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001458
Eric Snow7f8bfc92018-01-29 18:23:44 -07001459/**************************/
1460/* cross-interpreter data */
1461/**************************/
1462
1463/* cross-interpreter data */
1464
1465crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1466
1467/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1468 to keep the registry code separate. */
1469static crossinterpdatafunc
1470_lookup_getdata(PyObject *obj)
1471{
1472 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1473 if (getdata == NULL && PyErr_Occurred() == 0)
1474 PyErr_Format(PyExc_ValueError,
1475 "%S does not support cross-interpreter data", obj);
1476 return getdata;
1477}
1478
1479int
1480_PyObject_CheckCrossInterpreterData(PyObject *obj)
1481{
1482 crossinterpdatafunc getdata = _lookup_getdata(obj);
1483 if (getdata == NULL) {
1484 return -1;
1485 }
1486 return 0;
1487}
1488
1489static int
Victor Stinner71a35222020-03-26 22:46:14 +01001490_check_xidata(PyThreadState *tstate, _PyCrossInterpreterData *data)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001491{
1492 // data->data can be anything, including NULL, so we don't check it.
1493
1494 // data->obj may be NULL, so we don't check it.
1495
1496 if (data->interp < 0) {
Victor Stinner71a35222020-03-26 22:46:14 +01001497 _PyErr_SetString(tstate, PyExc_SystemError, "missing interp");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001498 return -1;
1499 }
1500
1501 if (data->new_object == NULL) {
Victor Stinner71a35222020-03-26 22:46:14 +01001502 _PyErr_SetString(tstate, PyExc_SystemError, "missing new_object func");
Eric Snow7f8bfc92018-01-29 18:23:44 -07001503 return -1;
1504 }
1505
1506 // data->free may be NULL, so we don't check it.
1507
1508 return 0;
1509}
1510
1511int
1512_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1513{
Victor Stinner71a35222020-03-26 22:46:14 +01001514 // PyThreadState_Get() aborts if tstate is NULL.
1515 PyThreadState *tstate = PyThreadState_Get();
1516 PyInterpreterState *interp = tstate->interp;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001517
1518 // Reset data before re-populating.
1519 *data = (_PyCrossInterpreterData){0};
1520 data->free = PyMem_RawFree; // Set a default that may be overridden.
1521
1522 // Call the "getdata" func for the object.
1523 Py_INCREF(obj);
1524 crossinterpdatafunc getdata = _lookup_getdata(obj);
1525 if (getdata == NULL) {
1526 Py_DECREF(obj);
1527 return -1;
1528 }
1529 int res = getdata(obj, data);
1530 Py_DECREF(obj);
1531 if (res != 0) {
1532 return -1;
1533 }
1534
1535 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001536 data->interp = interp->id;
Victor Stinner71a35222020-03-26 22:46:14 +01001537 if (_check_xidata(tstate, data) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001538 _PyCrossInterpreterData_Release(data);
1539 return -1;
1540 }
1541
1542 return 0;
1543}
1544
Victor Stinnere225beb2019-06-03 18:14:24 +02001545static void
Eric Snow63799132018-06-01 18:45:20 -06001546_release_xidata(void *arg)
1547{
1548 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1549 if (data->free != NULL) {
1550 data->free(data->data);
1551 }
1552 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001553}
1554
1555static void
1556_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1557 PyInterpreterState *interp,
1558 void (*func)(void *), void *arg)
1559{
1560 /* We would use Py_AddPendingCall() if it weren't specific to the
1561 * main interpreter (see bpo-33608). In the meantime we take a
1562 * naive approach.
1563 */
1564 PyThreadState *save_tstate = NULL;
1565 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1566 // XXX Using the "head" thread isn't strictly correct.
1567 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1568 // XXX Possible GILState issues?
1569 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1570 }
1571
1572 func(arg);
1573
1574 // Switch back.
1575 if (save_tstate != NULL) {
1576 _PyThreadState_Swap(gilstate, save_tstate);
1577 }
Eric Snow63799132018-06-01 18:45:20 -06001578}
1579
Eric Snow7f8bfc92018-01-29 18:23:44 -07001580void
1581_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1582{
1583 if (data->data == NULL && data->obj == NULL) {
1584 // Nothing to release!
1585 return;
1586 }
1587
Victor Stinnere225beb2019-06-03 18:14:24 +02001588 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001589 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1590 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001591 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001592 if (data->free != NULL) {
1593 // XXX Someone leaked some memory...
1594 }
1595 return;
1596 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001597
Eric Snow7f8bfc92018-01-29 18:23:44 -07001598 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001599 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1600 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001601}
1602
1603PyObject *
1604_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1605{
1606 return data->new_object(data);
1607}
1608
1609/* registry of {type -> crossinterpdatafunc} */
1610
1611/* For now we use a global registry of shareable classes. An
1612 alternative would be to add a tp_* slot for a class's
1613 crossinterpdatafunc. It would be simpler and more efficient. */
1614
1615static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001616_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1617 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001618{
1619 // Note that we effectively replace already registered classes
1620 // rather than failing.
1621 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1622 if (newhead == NULL)
1623 return -1;
1624 newhead->cls = cls;
1625 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001626 newhead->next = xidregistry->head;
1627 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001628 return 0;
1629}
1630
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001631static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001632
1633int
Eric Snowc11183c2019-03-15 16:35:46 -06001634_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001635 crossinterpdatafunc getdata)
1636{
1637 if (!PyType_Check(cls)) {
1638 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1639 return -1;
1640 }
1641 if (getdata == NULL) {
1642 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1643 return -1;
1644 }
1645
1646 // Make sure the class isn't ever deallocated.
1647 Py_INCREF((PyObject *)cls);
1648
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001649 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1650 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1651 if (xidregistry->head == NULL) {
1652 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001653 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001654 int res = _register_xidata(xidregistry, cls, getdata);
1655 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001656 return res;
1657}
1658
Eric Snow6d2cd902018-05-16 15:04:57 -04001659/* Cross-interpreter objects are looked up by exact match on the class.
1660 We can reassess this policy when we move from a global registry to a
1661 tp_* slot. */
1662
Eric Snow7f8bfc92018-01-29 18:23:44 -07001663crossinterpdatafunc
1664_PyCrossInterpreterData_Lookup(PyObject *obj)
1665{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001666 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001667 PyObject *cls = PyObject_Type(obj);
1668 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001669 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1670 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001671 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001672 _register_builtins_for_crossinterpreter_data(xidregistry);
1673 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001674 }
1675 for(; cur != NULL; cur = cur->next) {
1676 if (cur->cls == (PyTypeObject *)cls) {
1677 getdata = cur->getdata;
1678 break;
1679 }
1680 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001681 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001682 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001683 return getdata;
1684}
1685
1686/* cross-interpreter data for builtin types */
1687
Eric Snow6d2cd902018-05-16 15:04:57 -04001688struct _shared_bytes_data {
1689 char *bytes;
1690 Py_ssize_t len;
1691};
1692
Eric Snow7f8bfc92018-01-29 18:23:44 -07001693static PyObject *
1694_new_bytes_object(_PyCrossInterpreterData *data)
1695{
Eric Snow6d2cd902018-05-16 15:04:57 -04001696 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1697 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001698}
1699
1700static int
1701_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1702{
Eric Snow6d2cd902018-05-16 15:04:57 -04001703 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1704 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1705 return -1;
1706 }
1707 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001708 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001709 data->obj = obj; // Will be "released" (decref'ed) when data released.
1710 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001711 data->free = PyMem_Free;
1712 return 0;
1713}
1714
1715struct _shared_str_data {
1716 int kind;
1717 const void *buffer;
1718 Py_ssize_t len;
1719};
1720
1721static PyObject *
1722_new_str_object(_PyCrossInterpreterData *data)
1723{
1724 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1725 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1726}
1727
1728static int
1729_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1730{
1731 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1732 shared->kind = PyUnicode_KIND(obj);
1733 shared->buffer = PyUnicode_DATA(obj);
An Long29c11722020-06-13 20:26:01 +08001734 shared->len = PyUnicode_GET_LENGTH(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001735 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001736 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001737 data->obj = obj; // Will be "released" (decref'ed) when data released.
1738 data->new_object = _new_str_object;
1739 data->free = PyMem_Free;
1740 return 0;
1741}
1742
1743static PyObject *
1744_new_long_object(_PyCrossInterpreterData *data)
1745{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001746 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001747}
1748
1749static int
1750_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1751{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001752 /* Note that this means the size of shareable ints is bounded by
1753 * sys.maxsize. Hence on 32-bit architectures that is half the
1754 * size of maximum shareable ints on 64-bit.
1755 */
1756 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001757 if (value == -1 && PyErr_Occurred()) {
1758 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1759 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1760 }
1761 return -1;
1762 }
1763 data->data = (void *)value;
1764 data->obj = NULL;
1765 data->new_object = _new_long_object;
1766 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001767 return 0;
1768}
1769
1770static PyObject *
1771_new_none_object(_PyCrossInterpreterData *data)
1772{
1773 // XXX Singleton refcounts are problematic across interpreters...
1774 Py_INCREF(Py_None);
1775 return Py_None;
1776}
1777
1778static int
1779_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1780{
1781 data->data = NULL;
1782 // data->obj remains NULL
1783 data->new_object = _new_none_object;
1784 data->free = NULL; // There is nothing to free.
1785 return 0;
1786}
1787
1788static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001789_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001790{
1791 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001792 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001793 Py_FatalError("could not register None for cross-interpreter sharing");
1794 }
1795
Eric Snow6d2cd902018-05-16 15:04:57 -04001796 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001797 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001798 Py_FatalError("could not register int for cross-interpreter sharing");
1799 }
1800
Eric Snow7f8bfc92018-01-29 18:23:44 -07001801 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001802 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001803 Py_FatalError("could not register bytes for cross-interpreter sharing");
1804 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001805
1806 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001807 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001808 Py_FatalError("could not register str for cross-interpreter sharing");
1809 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001810}
1811
1812
Victor Stinner0b72b232020-03-12 23:18:39 +01001813_PyFrameEvalFunction
1814_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1815{
1816 return interp->eval_frame;
1817}
1818
1819
1820void
1821_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1822 _PyFrameEvalFunction eval_frame)
1823{
1824 interp->eval_frame = eval_frame;
1825}
1826
Victor Stinnerda7933e2020-04-13 03:04:28 +02001827
1828const PyConfig*
1829_PyInterpreterState_GetConfig(PyInterpreterState *interp)
1830{
1831 return &interp->config;
1832}
1833
1834
1835PyStatus
1836_PyInterpreterState_SetConfig(PyInterpreterState *interp,
1837 const PyConfig *config)
1838{
1839 return _PyConfig_Copy(&interp->config, config);
1840}
1841
1842
1843const PyConfig*
1844_Py_GetConfig(void)
1845{
1846 assert(PyGILState_Check());
1847 PyThreadState *tstate = _PyThreadState_GET();
1848 return _PyInterpreterState_GetConfig(tstate->interp);
1849}
1850
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001851#ifdef __cplusplus
1852}
1853#endif