blob: eea666b7e5b6d21515b52bcd6fa7aeff024939ee [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 Stinner621cebe2018-11-12 16:53:38 +01007#include "pycore_pymem.h"
8#include "pycore_pystate.h"
Eric Snow86ea5812019-05-10 13:29:55 -04009#include "pycore_pylifecycle.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +000010
Tim Peters84705582004-10-10 02:47:33 +000011/* --------------------------------------------------------------------------
12CAUTION
13
Victor Stinner1a7425f2013-07-07 16:25:15 +020014Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
15number of these functions are advertised as safe to call when the GIL isn't
16held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
17debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
18to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000019-------------------------------------------------------------------------- */
20
Martin v. Löwisf0473d52001-07-18 16:17:16 +000021#ifdef HAVE_DLOPEN
22#ifdef HAVE_DLFCN_H
23#include <dlfcn.h>
24#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030025#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000026#define RTLD_LAZY 1
27#endif
28#endif
29
Benjamin Peterson43162b82012-04-13 11:58:27 -040030#ifdef __cplusplus
31extern "C" {
32#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000033
Victor Stinner10c8e6a2019-04-26 01:53:18 +020034#define _PyRuntimeGILState_GetThreadState(gilstate) \
35 ((PyThreadState*)_Py_atomic_load_relaxed(&(gilstate)->tstate_current))
36#define _PyRuntimeGILState_SetThreadState(gilstate, value) \
37 _Py_atomic_store_relaxed(&(gilstate)->tstate_current, \
38 (uintptr_t)(value))
39
Victor Stinner23ef89d2020-03-18 02:26:04 +010040static void
41ensure_tstate_not_null(const char *func, PyThreadState *tstate)
42{
43 if (tstate == NULL) {
44 _Py_FatalErrorFunc(func,
45 "current thread state is NULL (released GIL?)");
46 }
47}
48
49
Victor Stinner10c8e6a2019-04-26 01:53:18 +020050/* Forward declarations */
51static PyThreadState *_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate);
Victor Stinner9da74302019-11-20 11:17:17 +010052static void _PyThreadState_Delete(PyThreadState *tstate, int check_current);
Victor Stinner10c8e6a2019-04-26 01:53:18 +020053
54
Victor Stinner331a6a52019-05-27 16:39:22 +020055static PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010056_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060057{
Steve Dowerb82e17e2019-05-23 08:45:22 -070058 /* We preserve the hook across init, because there is
59 currently no public API to set it between runtime
60 initialization and interpreter initialization. */
61 void *open_code_hook = runtime->open_code_hook;
62 void *open_code_userdata = runtime->open_code_userdata;
63 _Py_AuditHookEntry *audit_hook_head = runtime->audit_hook_head;
64
Eric Snow2ebc5ce2017-09-07 23:51:28 -060065 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010066
Steve Dowerb82e17e2019-05-23 08:45:22 -070067 runtime->open_code_hook = open_code_hook;
68 runtime->open_code_userdata = open_code_userdata;
69 runtime->audit_hook_head = audit_hook_head;
70
Victor Stinnerdab84232020-03-17 18:56:44 +010071 _PyEval_InitRuntimeState(&runtime->ceval);
Victor Stinner441b10c2019-09-28 04:28:35 +020072
Victor Stinner3c30a762019-10-01 10:56:37 +020073 PyPreConfig_InitPythonConfig(&runtime->preconfig);
Michael W. Hudson188d4362005-06-20 16:52:57 +000074
Eric Snow2ebc5ce2017-09-07 23:51:28 -060075 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080076
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090077 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
78 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079 Py_tss_t initial = Py_tss_NEEDS_INIT;
80 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000081
Eric Snow2ebc5ce2017-09-07 23:51:28 -060082 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080083 if (runtime->interpreters.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020084 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080085 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060086 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070087
88 runtime->xidregistry.mutex = PyThread_allocate_lock();
89 if (runtime->xidregistry.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020090 return _PyStatus_ERR("Can't initialize threads for cross-interpreter data registry");
Eric Snow7f8bfc92018-01-29 18:23:44 -070091 }
92
Eric Snow8479a342019-03-08 23:44:33 -070093 // Set it to the ID of the main thread of the main interpreter.
94 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070095
Victor Stinner331a6a52019-05-27 16:39:22 +020096 return _PyStatus_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060097}
Eric Snow05351c12017-09-05 21:43:08 -070098
Victor Stinner331a6a52019-05-27 16:39:22 +020099PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +0100100_PyRuntimeState_Init(_PyRuntimeState *runtime)
101{
102 /* Force default allocator, since _PyRuntimeState_Fini() must
103 use the same allocator than this function. */
104 PyMemAllocatorEx old_alloc;
105 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
106
Victor Stinner331a6a52019-05-27 16:39:22 +0200107 PyStatus status = _PyRuntimeState_Init_impl(runtime);
Victor Stinner5d39e042017-11-29 17:20:38 +0100108
109 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinner331a6a52019-05-27 16:39:22 +0200110 return status;
Victor Stinner5d39e042017-11-29 17:20:38 +0100111}
112
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600113void
114_PyRuntimeState_Fini(_PyRuntimeState *runtime)
115{
Victor Stinner5d39e042017-11-29 17:20:38 +0100116 /* Force the allocator used by _PyRuntimeState_Init(). */
117 PyMemAllocatorEx old_alloc;
118 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -0800119
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600120 if (runtime->interpreters.mutex != NULL) {
121 PyThread_free_lock(runtime->interpreters.mutex);
122 runtime->interpreters.mutex = NULL;
123 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800124
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100125 if (runtime->xidregistry.mutex != NULL) {
126 PyThread_free_lock(runtime->xidregistry.mutex);
127 runtime->xidregistry.mutex = NULL;
128 }
129
Victor Stinnerccb04422017-11-16 03:20:31 -0800130 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600131}
132
Eric Snow8479a342019-03-08 23:44:33 -0700133/* This function is called from PyOS_AfterFork_Child to ensure that
134 * newly created child processes do not share locks with the parent.
135 */
136
137void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200138_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700139{
140 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200141 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700142
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200143 /* Force default allocator, since _PyRuntimeState_Fini() must
144 use the same allocator than this function. */
145 PyMemAllocatorEx old_alloc;
146 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
147
148 runtime->interpreters.mutex = PyThread_allocate_lock();
149 runtime->interpreters.main->id_mutex = PyThread_allocate_lock();
150 runtime->xidregistry.mutex = PyThread_allocate_lock();
151
152 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
153
154 if (runtime->interpreters.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700155 Py_FatalError("Can't initialize lock for runtime interpreters");
156 }
157
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200158 if (runtime->interpreters.main->id_mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700159 Py_FatalError("Can't initialize ID lock for main interpreter");
160 }
161
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200162 if (runtime->xidregistry.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700163 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
164 }
165}
166
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200167#define HEAD_LOCK(runtime) \
168 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
169#define HEAD_UNLOCK(runtime) \
170 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700171
Victor Stinner8bb32302019-04-24 16:47:40 +0200172/* Forward declaration */
173static void _PyGILState_NoteThreadState(
174 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000175
Victor Stinner331a6a52019-05-27 16:39:22 +0200176PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600177_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700178{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200179 struct pyinterpreters *interpreters = &runtime->interpreters;
180 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100181
182 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
183 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200184 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100185 /* Force default allocator, since _PyRuntimeState_Fini() must
186 use the same allocator than this function. */
187 PyMemAllocatorEx old_alloc;
188 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
189
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200190 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100191
192 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
193
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200194 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200195 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800196 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600197 }
Victor Stinner5d926472018-03-06 14:31:37 +0100198
Victor Stinner331a6a52019-05-27 16:39:22 +0200199 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700200}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000201
202PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000203PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000204{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700205 if (PySys_Audit("cpython.PyInterpreterState_New", NULL) < 0) {
206 return NULL;
207 }
208
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200209 PyInterpreterState *interp = PyMem_RawMalloc(sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100210 if (interp == NULL) {
211 return NULL;
212 }
213
Eric Snow5be45a62019-03-08 22:47:07 -0700214 memset(interp, 0, sizeof(*interp));
Eric Snow4c6955e2018-02-16 18:53:40 -0700215 interp->id_refcount = -1;
Victor Stinner022be022019-05-22 23:58:50 +0200216
Victor Stinner01b1cc12019-11-20 02:27:56 +0100217 _PyRuntimeState *runtime = &_PyRuntime;
218 interp->runtime = runtime;
219
Victor Stinnerdab84232020-03-17 18:56:44 +0100220 _PyEval_InitState(&interp->ceval);
Victor Stinner72474072019-11-20 12:25:50 +0100221 _PyGC_InitState(&interp->gc);
Victor Stinner8462a492019-10-01 12:06:16 +0200222 PyConfig_InitPythonConfig(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200223
Victor Stinnerd4341102017-11-23 00:12:09 +0100224 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000225#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300226#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100227 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000228#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100229 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000230#endif
231#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000232
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200233 struct pyinterpreters *interpreters = &runtime->interpreters;
234
235 HEAD_LOCK(runtime);
236 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100237 /* overflow or Py_Initialize() not called! */
238 PyErr_SetString(PyExc_RuntimeError,
239 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100240 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100241 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100242 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200243 else {
244 interp->id = interpreters->next_id;
245 interpreters->next_id += 1;
246 interp->next = interpreters->head;
247 if (interpreters->main == NULL) {
248 interpreters->main = interp;
249 }
250 interpreters->head = interp;
251 }
252 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000253
Pablo Galindo95d630e2018-08-31 22:49:29 +0100254 if (interp == NULL) {
255 return NULL;
256 }
257
Yury Selivanovf23746a2018-01-22 19:11:18 -0500258 interp->tstate_next_unique_id = 0;
259
Steve Dowerb82e17e2019-05-23 08:45:22 -0700260 interp->audit_hooks = NULL;
261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000263}
264
265
Victor Stinner01b1cc12019-11-20 02:27:56 +0100266void
267PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000268{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100269 _PyRuntimeState *runtime = interp->runtime;
270
Steve Dowerb82e17e2019-05-23 08:45:22 -0700271 if (PySys_Audit("cpython.PyInterpreterState_Clear", NULL) < 0) {
272 PyErr_Clear();
273 }
274
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200275 HEAD_LOCK(runtime);
276 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200278 }
279 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700280
281 Py_CLEAR(interp->audit_hooks);
282
Victor Stinner331a6a52019-05-27 16:39:22 +0200283 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 Py_CLEAR(interp->codec_search_path);
285 Py_CLEAR(interp->codec_search_cache);
286 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700287 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 Py_CLEAR(interp->sysdict);
290 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200291 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400292 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300293 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600294 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200295#ifdef HAVE_FORK
296 Py_CLEAR(interp->before_forkers);
297 Py_CLEAR(interp->after_forkers_parent);
298 Py_CLEAR(interp->after_forkers_child);
299#endif
Victor Stinner7b3c2522020-03-07 00:24:23 +0100300 if (_PyRuntimeState_GetFinalizing(runtime) == NULL) {
Eric Snow86ea5812019-05-10 13:29:55 -0400301 _PyWarnings_Fini(interp);
302 }
Eric Snow5be45a62019-03-08 22:47:07 -0700303 // XXX Once we have one allocator per interpreter (i.e.
304 // per-interpreter GC) we must ensure that all of the interpreter's
305 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000306}
307
308
309static void
Victor Stinner9da74302019-11-20 11:17:17 +0100310zapthreads(PyInterpreterState *interp, int check_current)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000311{
Victor Stinner9da74302019-11-20 11:17:17 +0100312 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 /* No need to lock the mutex here because this should only happen
314 when the threads are all really dead (XXX famous last words). */
Victor Stinner9da74302019-11-20 11:17:17 +0100315 while ((tstate = interp->tstate_head) != NULL) {
316 _PyThreadState_Delete(tstate, check_current);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000318}
319
320
Victor Stinner01b1cc12019-11-20 02:27:56 +0100321void
322PyInterpreterState_Delete(PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200323{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100324 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200325 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner9da74302019-11-20 11:17:17 +0100326 zapthreads(interp, 0);
327
328 /* Delete current thread. After this, many C API calls become crashy. */
329 _PyThreadState_Swap(&runtime->gilstate, NULL);
330
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200331 HEAD_LOCK(runtime);
332 PyInterpreterState **p;
333 for (p = &interpreters->head; ; p = &(*p)->next) {
334 if (*p == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100335 Py_FatalError("invalid interp");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200336 }
337 if (*p == interp) {
338 break;
339 }
340 }
341 if (interp->tstate_head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100342 Py_FatalError("remaining threads");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200343 }
344 *p = interp->next;
345 if (interpreters->main == interp) {
346 interpreters->main = NULL;
347 if (interpreters->head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100348 Py_FatalError("remaining subinterpreters");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200349 }
350 }
351 HEAD_UNLOCK(runtime);
352 if (interp->id_mutex != NULL) {
353 PyThread_free_lock(interp->id_mutex);
354 }
355 PyMem_RawFree(interp);
356}
357
358
Eric Snow59032962018-09-14 14:17:20 -0700359/*
360 * Delete all interpreter states except the main interpreter. If there
361 * is a current interpreter state, it *must* be the main interpreter.
362 */
363void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200364_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700365{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200366 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200367 struct pyinterpreters *interpreters = &runtime->interpreters;
368
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200369 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200370 if (tstate != NULL && tstate->interp != interpreters->main) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100371 Py_FatalError("not main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700372 }
373
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200374 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200375 PyInterpreterState *interp = interpreters->head;
376 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100377 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200378 if (interp == interpreters->main) {
379 interpreters->main->next = NULL;
380 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100381 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700382 continue;
383 }
384
Victor Stinner01b1cc12019-11-20 02:27:56 +0100385 PyInterpreterState_Clear(interp); // XXX must activate?
Victor Stinner9da74302019-11-20 11:17:17 +0100386 zapthreads(interp, 1);
Eric Snow59032962018-09-14 14:17:20 -0700387 if (interp->id_mutex != NULL) {
388 PyThread_free_lock(interp->id_mutex);
389 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100390 PyInterpreterState *prev_interp = interp;
391 interp = interp->next;
392 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700393 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200394 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700395
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200396 if (interpreters->head == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100397 Py_FatalError("missing main");
Eric Snow59032962018-09-14 14:17:20 -0700398 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200399 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700400}
401
402
Victor Stinnercaba55b2018-08-03 15:33:52 +0200403PyInterpreterState *
Victor Stinnerbe793732020-03-13 18:15:33 +0100404PyInterpreterState_Get(void)
Victor Stinnercaba55b2018-08-03 15:33:52 +0200405{
Victor Stinner50b48572018-11-01 01:51:40 +0100406 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner23ef89d2020-03-18 02:26:04 +0100407 ensure_tstate_not_null(__func__, tstate);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200408 PyInterpreterState *interp = tstate->interp;
409 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100410 Py_FatalError("no current interpreter");
Victor Stinnercaba55b2018-08-03 15:33:52 +0200411 }
412 return interp;
413}
414
415
Eric Snowe3774162017-05-22 19:46:40 -0700416int64_t
417PyInterpreterState_GetID(PyInterpreterState *interp)
418{
419 if (interp == NULL) {
420 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
421 return -1;
422 }
423 return interp->id;
424}
425
426
Eric Snow5be45a62019-03-08 22:47:07 -0700427static PyInterpreterState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200428interp_look_up_id(_PyRuntimeState *runtime, PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700429{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200430 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100431 while (interp != NULL) {
432 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700433 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100434 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700435 }
436 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100437 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700438 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100439 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700440 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100441 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700442}
443
Eric Snow5be45a62019-03-08 22:47:07 -0700444PyInterpreterState *
445_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
446{
447 PyInterpreterState *interp = NULL;
448 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200449 _PyRuntimeState *runtime = &_PyRuntime;
450 HEAD_LOCK(runtime);
451 interp = interp_look_up_id(runtime, requested_id);
452 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700453 }
454 if (interp == NULL && !PyErr_Occurred()) {
455 PyErr_Format(PyExc_RuntimeError,
456 "unrecognized interpreter ID %lld", requested_id);
457 }
458 return interp;
459}
460
Eric Snow4c6955e2018-02-16 18:53:40 -0700461
462int
463_PyInterpreterState_IDInitref(PyInterpreterState *interp)
464{
465 if (interp->id_mutex != NULL) {
466 return 0;
467 }
468 interp->id_mutex = PyThread_allocate_lock();
469 if (interp->id_mutex == NULL) {
470 PyErr_SetString(PyExc_RuntimeError,
471 "failed to create init interpreter ID mutex");
472 return -1;
473 }
474 interp->id_refcount = 0;
475 return 0;
476}
477
478
479void
480_PyInterpreterState_IDIncref(PyInterpreterState *interp)
481{
482 if (interp->id_mutex == NULL) {
483 return;
484 }
485 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
486 interp->id_refcount += 1;
487 PyThread_release_lock(interp->id_mutex);
488}
489
490
491void
492_PyInterpreterState_IDDecref(PyInterpreterState *interp)
493{
494 if (interp->id_mutex == NULL) {
495 return;
496 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200497 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700498 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
499 assert(interp->id_refcount != 0);
500 interp->id_refcount -= 1;
501 int64_t refcount = interp->id_refcount;
502 PyThread_release_lock(interp->id_mutex);
503
Eric Snowc11183c2019-03-15 16:35:46 -0600504 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700505 // XXX Using the "head" thread isn't strictly correct.
506 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
507 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200508 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700509 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200510 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700511 }
512}
513
Eric Snowc11183c2019-03-15 16:35:46 -0600514int
515_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
516{
517 return interp->requires_idref;
518}
519
520void
521_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
522{
523 interp->requires_idref = required ? 1 : 0;
524}
525
Eric Snowc11183c2019-03-15 16:35:46 -0600526PyObject *
527_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
528{
529 if (interp->modules == NULL) {
530 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
531 return NULL;
532 }
533 return PyMapping_GetItemString(interp->modules, "__main__");
534}
535
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600536PyObject *
537PyInterpreterState_GetDict(PyInterpreterState *interp)
538{
539 if (interp->dict == NULL) {
540 interp->dict = PyDict_New();
541 if (interp->dict == NULL) {
542 PyErr_Clear();
543 }
544 }
545 /* Returning NULL means no per-interpreter dict is available. */
546 return interp->dict;
547}
548
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000549/* Default implementation for _PyThreadState_GetFrame */
550static struct _frame *
551threadstate_getframe(PyThreadState *self)
552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000554}
555
Victor Stinner45b9be52010-03-03 23:28:07 +0000556static PyThreadState *
557new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000558{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100559 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200560 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200561 if (tstate == NULL) {
562 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564
Victor Stinner8bb32302019-04-24 16:47:40 +0200565 if (_PyThreadState_GetFrame == NULL) {
566 _PyThreadState_GetFrame = threadstate_getframe;
567 }
568
569 tstate->interp = interp;
570
571 tstate->frame = NULL;
572 tstate->recursion_depth = 0;
573 tstate->overflowed = 0;
574 tstate->recursion_critical = 0;
575 tstate->stackcheck_counter = 0;
576 tstate->tracing = 0;
577 tstate->use_tracing = 0;
578 tstate->gilstate_counter = 0;
579 tstate->async_exc = NULL;
580 tstate->thread_id = PyThread_get_thread_ident();
581
582 tstate->dict = NULL;
583
584 tstate->curexc_type = NULL;
585 tstate->curexc_value = NULL;
586 tstate->curexc_traceback = NULL;
587
588 tstate->exc_state.exc_type = NULL;
589 tstate->exc_state.exc_value = NULL;
590 tstate->exc_state.exc_traceback = NULL;
591 tstate->exc_state.previous_item = NULL;
592 tstate->exc_info = &tstate->exc_state;
593
594 tstate->c_profilefunc = NULL;
595 tstate->c_tracefunc = NULL;
596 tstate->c_profileobj = NULL;
597 tstate->c_traceobj = NULL;
598
599 tstate->trash_delete_nesting = 0;
600 tstate->trash_delete_later = NULL;
601 tstate->on_delete = NULL;
602 tstate->on_delete_data = NULL;
603
604 tstate->coroutine_origin_tracking_depth = 0;
605
Victor Stinner8bb32302019-04-24 16:47:40 +0200606 tstate->async_gen_firstiter = NULL;
607 tstate->async_gen_finalizer = NULL;
608
609 tstate->context = NULL;
610 tstate->context_ver = 1;
611
Victor Stinner8bb32302019-04-24 16:47:40 +0200612 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100613 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200614 }
615
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200616 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100617 tstate->id = ++interp->tstate_next_unique_id;
Victor Stinner8bb32302019-04-24 16:47:40 +0200618 tstate->prev = NULL;
619 tstate->next = interp->tstate_head;
620 if (tstate->next)
621 tstate->next->prev = tstate;
622 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200623 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000626}
627
Victor Stinner45b9be52010-03-03 23:28:07 +0000628PyThreadState *
629PyThreadState_New(PyInterpreterState *interp)
630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000632}
633
634PyThreadState *
635_PyThreadState_Prealloc(PyInterpreterState *interp)
636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000638}
639
640void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100641_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000642{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100643 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000644}
645
Martin v. Löwis1a214512008-06-11 05:26:20 +0000646PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200647PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000648{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200649 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100650 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000652 if (module->m_slots) {
653 return NULL;
654 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 if (index == 0)
656 return NULL;
657 if (state->modules_by_index == NULL)
658 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200659 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 return NULL;
661 res = PyList_GET_ITEM(state->modules_by_index, index);
662 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000663}
664
665int
Victor Stinner82c83bd2019-11-22 18:52:27 +0100666_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000667{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300668 if (!def) {
669 assert(PyErr_Occurred());
670 return -1;
671 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000672 if (def->m_slots) {
673 PyErr_SetString(PyExc_SystemError,
674 "PyState_AddModule called on module with slots");
675 return -1;
676 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100677
678 PyInterpreterState *interp = tstate->interp;
679 if (!interp->modules_by_index) {
680 interp->modules_by_index = PyList_New(0);
681 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100683 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100685
686 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
687 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100689 }
690 }
691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100693 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000695}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000696
Martin v. Löwis7800f752012-06-22 12:20:55 +0200697int
698PyState_AddModule(PyObject* module, struct PyModuleDef* def)
699{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200700 if (!def) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100701 Py_FatalError("Module Definition is NULL");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200702 return -1;
703 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100704
705 PyThreadState *tstate = _PyThreadState_GET();
706 PyInterpreterState *interp = tstate->interp;
707 Py_ssize_t index = def->m_base.m_index;
708 if (interp->modules_by_index &&
709 index < PyList_GET_SIZE(interp->modules_by_index) &&
710 module == PyList_GET_ITEM(interp->modules_by_index, index))
711 {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100712 Py_FatalError("Module already added");
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100713 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200714 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100715 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200716}
717
718int
719PyState_RemoveModule(struct PyModuleDef* def)
720{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000721 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200722 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000723 if (def->m_slots) {
724 PyErr_SetString(PyExc_SystemError,
725 "PyState_RemoveModule called on module with slots");
726 return -1;
727 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100728 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200729 if (index == 0) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100730 Py_FatalError("Module index invalid");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200731 return -1;
732 }
733 if (state->modules_by_index == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100734 Py_FatalError("Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200735 return -1;
736 }
737 if (index > PyList_GET_SIZE(state->modules_by_index)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100738 Py_FatalError("Module index out of bounds.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200739 return -1;
740 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700741 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200742 return PyList_SetItem(state->modules_by_index, index, Py_None);
743}
744
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200745/* Used by PyImport_Cleanup() */
Antoine Pitrou40322e62013-08-11 00:30:09 +0200746void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200747_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200748{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200749 if (!interp->modules_by_index) {
750 return;
751 }
752
753 Py_ssize_t i;
754 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
755 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
756 if (PyModule_Check(m)) {
757 /* cleanup the saved copy of module dicts */
758 PyModuleDef *md = PyModule_GetDef(m);
759 if (md) {
760 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200761 }
762 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200763 }
764
765 /* Setting modules_by_index to NULL could be dangerous, so we
766 clear the list instead. */
767 if (PyList_SetSlice(interp->modules_by_index,
768 0, PyList_GET_SIZE(interp->modules_by_index),
769 NULL)) {
770 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200771 }
772}
773
Guido van Rossuma027efa1997-05-05 20:56:21 +0000774void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000775PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000776{
Victor Stinner331a6a52019-05-27 16:39:22 +0200777 int verbose = tstate->interp->config.verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200778
779 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 fprintf(stderr,
781 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 Py_CLEAR(tstate->dict);
786 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 Py_CLEAR(tstate->curexc_type);
789 Py_CLEAR(tstate->curexc_value);
790 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000791
Mark Shannonae3087c2017-10-22 22:41:51 +0100792 Py_CLEAR(tstate->exc_state.exc_type);
793 Py_CLEAR(tstate->exc_state.exc_value);
794 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300795
Mark Shannonae3087c2017-10-22 22:41:51 +0100796 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200797 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100798 fprintf(stderr,
799 "PyThreadState_Clear: warning: thread still has a generator\n");
800 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 tstate->c_profilefunc = NULL;
803 tstate->c_tracefunc = NULL;
804 Py_CLEAR(tstate->c_profileobj);
805 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400806
Yury Selivanoveb636452016-09-08 22:01:51 -0700807 Py_CLEAR(tstate->async_gen_firstiter);
808 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500809
810 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100811
812 if (tstate->on_delete != NULL) {
813 tstate->on_delete(tstate->on_delete_data);
814 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000815}
816
817
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300818/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000819static void
Victor Stinner9da74302019-11-20 11:17:17 +0100820tstate_delete_common(PyThreadState *tstate,
821 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000822{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100823 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner23ef89d2020-03-18 02:26:04 +0100824 ensure_tstate_not_null(__func__, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200825 PyInterpreterState *interp = tstate->interp;
826 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100827 Py_FatalError("NULL interp");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200828 }
829 HEAD_LOCK(runtime);
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200830 if (tstate->prev)
831 tstate->prev->next = tstate->next;
832 else
833 interp->tstate_head = tstate->next;
834 if (tstate->next)
835 tstate->next->prev = tstate->prev;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200836 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100837
Victor Stinner9da74302019-11-20 11:17:17 +0100838 if (gilstate->autoInterpreterState &&
839 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
840 {
841 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
842 }
843}
844
845
846static void
847_PyThreadState_Delete(PyThreadState *tstate, int check_current)
848{
849 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
850 if (check_current) {
851 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100852 Py_FatalError("tstate is still current");
Victor Stinner9da74302019-11-20 11:17:17 +0100853 }
854 }
855 tstate_delete_common(tstate, gilstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100856 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000857}
858
859
Victor Stinner01b1cc12019-11-20 02:27:56 +0100860void
861PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000862{
Victor Stinner9da74302019-11-20 11:17:17 +0100863 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200864}
865
866
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300867void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100868_PyThreadState_DeleteCurrent(PyThreadState *tstate)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200869{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100870 ensure_tstate_not_null(__func__, tstate);
871 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner9da74302019-11-20 11:17:17 +0100872 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200873 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100874 _PyEval_ReleaseLock(tstate);
875 PyMem_RawFree(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000876}
Guido van Rossum29757862001-01-23 01:46:06 +0000877
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300878void
879PyThreadState_DeleteCurrent(void)
880{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100881 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
882 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
883 _PyThreadState_DeleteCurrent(tstate);
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300884}
885
Guido van Rossum29757862001-01-23 01:46:06 +0000886
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200887/*
888 * Delete all thread states except the one passed as argument.
889 * Note that, if there is a current thread state, it *must* be the one
890 * passed as argument. Also, this won't touch any other interpreters
891 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000892 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200893 */
894void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200895_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200896{
897 PyInterpreterState *interp = tstate->interp;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100898
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200899 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200900 /* Remove all thread states, except tstate, from the linked list of
901 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200902 without holding the lock. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100903 PyThreadState *list = interp->tstate_head;
904 if (list == tstate) {
905 list = tstate->next;
906 }
907 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200908 tstate->prev->next = tstate->next;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100909 }
910 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200911 tstate->next->prev = tstate->prev;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100912 }
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200913 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200914 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200915 HEAD_UNLOCK(runtime);
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100916
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200917 /* Clear and deallocate all stale thread states. Even if this
918 executes Python code, we should be safe since it executes
919 in the current thread, not one of the stale threads. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100920 PyThreadState *p, *next;
921 for (p = list; p; p = next) {
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200922 next = p->next;
923 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200924 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200925 }
926}
927
928
Guido van Rossuma027efa1997-05-05 20:56:21 +0000929PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100930_PyThreadState_UncheckedGet(void)
931{
Victor Stinner50b48572018-11-01 01:51:40 +0100932 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100933}
934
935
936PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000937PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000938{
Victor Stinner50b48572018-11-01 01:51:40 +0100939 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner23ef89d2020-03-18 02:26:04 +0100940 ensure_tstate_not_null(__func__, tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000942}
943
944
Victor Stinner09532fe2019-05-10 23:39:09 +0200945PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200946_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000947{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200948 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000949
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200950 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 /* It should not be possible for more than one thread state
952 to be used for a thread. Check this the best we can in debug
953 builds.
954 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200955#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 if (newts) {
957 /* This can be called from PyEval_RestoreThread(). Similar
958 to it, we need to ensure errno doesn't change.
959 */
960 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200961 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 if (check && check->interp == newts->interp && check != newts)
963 Py_FatalError("Invalid thread state for this thread");
964 errno = err;
965 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000966#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000968}
Guido van Rossumede04391998-04-10 20:18:25 +0000969
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200970PyThreadState *
971PyThreadState_Swap(PyThreadState *newts)
972{
973 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
974}
975
Guido van Rossumede04391998-04-10 20:18:25 +0000976/* An extension mechanism to store arbitrary additional per-thread state.
977 PyThreadState_GetDict() returns a dictionary that can be used to hold such
978 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000979 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
980 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000981
982PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000983PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000984{
Victor Stinner50b48572018-11-01 01:51:40 +0100985 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (tstate == NULL)
987 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (tstate->dict == NULL) {
990 PyObject *d;
991 tstate->dict = d = PyDict_New();
992 if (d == NULL)
993 PyErr_Clear();
994 }
995 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000996}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000997
998
Victor Stinner8fb02b62020-03-13 23:38:08 +0100999PyInterpreterState *
1000PyThreadState_GetInterpreter(PyThreadState *tstate)
1001{
1002 assert(tstate != NULL);
1003 if (tstate == NULL) {
1004 return NULL;
1005 }
1006 return tstate->interp;
1007}
1008
1009
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001010struct _frame*
1011PyThreadState_GetFrame(PyThreadState *tstate)
1012{
1013 assert(tstate != NULL);
1014 return _PyThreadState_GetFrame(tstate);
1015}
1016
1017
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001018/* Asynchronously raise an exception in a thread.
1019 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001020 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001021 to call this, or use ctypes. Must be called with the GIL held.
1022 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1023 match any known thread id). Can be called with exc=NULL to clear an
1024 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001025
1026int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001027PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1028{
Victor Stinner09532fe2019-05-10 23:39:09 +02001029 _PyRuntimeState *runtime = &_PyRuntime;
1030 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 /* Although the GIL is held, a few C API functions can be called
1033 * without the GIL held, and in particular some that create and
1034 * destroy thread and interpreter states. Those can mutate the
1035 * list of thread states we're traversing, so to prevent that we lock
1036 * head_mutex for the duration.
1037 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001038 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001039 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1040 if (tstate->thread_id != id) {
1041 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001043
1044 /* Tricky: we need to decref the current value
1045 * (if any) in tstate->async_exc, but that can in turn
1046 * allow arbitrary Python code to run, including
1047 * perhaps calls to this function. To prevent
1048 * deadlock, we need to release head_mutex before
1049 * the decref.
1050 */
1051 PyObject *old_exc = tstate->async_exc;
1052 Py_XINCREF(exc);
1053 tstate->async_exc = exc;
1054 HEAD_UNLOCK(runtime);
1055
1056 Py_XDECREF(old_exc);
1057 _PyEval_SignalAsyncExc(tstate);
1058 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001060 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001062}
1063
1064
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001065/* Routines for advanced debuggers, requested by David Beazley.
1066 Don't use unless you know what you are doing! */
1067
1068PyInterpreterState *
1069PyInterpreterState_Head(void)
1070{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001071 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001072}
1073
1074PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001075PyInterpreterState_Main(void)
1076{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001077 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001078}
1079
1080PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001081PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001083}
1084
1085PyThreadState *
1086PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001088}
1089
1090PyThreadState *
1091PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001093}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001094
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001095/* The implementation of sys._current_frames(). This is intended to be
1096 called with the GIL held, as it will be when called via
1097 sys._current_frames(). It's possible it would work fine even without
1098 the GIL held, but haven't thought enough about that.
1099*/
1100PyObject *
1101_PyThread_CurrentFrames(void)
1102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 PyObject *result;
1104 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001105
Steve Dowerb82e17e2019-05-23 08:45:22 -07001106 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1107 return NULL;
1108 }
1109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 result = PyDict_New();
1111 if (result == NULL)
1112 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 /* for i in all interpreters:
1115 * for t in all of i's thread states:
1116 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001117 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 * need to grab head_mutex for the duration.
1119 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001120 _PyRuntimeState *runtime = &_PyRuntime;
1121 HEAD_LOCK(runtime);
1122 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 PyThreadState *t;
1124 for (t = i->tstate_head; t != NULL; t = t->next) {
1125 PyObject *id;
1126 int stat;
1127 struct _frame *frame = t->frame;
1128 if (frame == NULL)
1129 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001130 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 if (id == NULL)
1132 goto Fail;
1133 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1134 Py_DECREF(id);
1135 if (stat < 0)
1136 goto Fail;
1137 }
1138 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001139 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001141
1142 Fail:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001143 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 Py_DECREF(result);
1145 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001146}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001147
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001148/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001149
1150/* Keep this as a static, as it is not reliable! It can only
1151 ever be compared to the state for the *current* thread.
1152 * If not equal, then it doesn't matter that the actual
1153 value may change immediately after comparison, as it can't
1154 possibly change to the current thread's state.
1155 * If equal, then the current thread holds the lock, so the value can't
1156 change until we yield the lock.
1157*/
1158static int
1159PyThreadState_IsCurrent(PyThreadState *tstate)
1160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001162 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001163 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1164 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001165}
1166
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001167/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001168 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001169*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001170PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001171_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001172{
Victor Stinner8bb32302019-04-24 16:47:40 +02001173 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001174 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001175 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001176
Victor Stinner01b1cc12019-11-20 02:27:56 +01001177 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001178
1179 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001180 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001181 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001182 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001183 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1184 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001185
Victor Stinner8bb32302019-04-24 16:47:40 +02001186 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001187 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001188}
1189
Victor Stinner861d9ab2016-03-16 22:45:24 +01001190PyInterpreterState *
1191_PyGILState_GetInterpreterStateUnsafe(void)
1192{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001193 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001194}
1195
Tim Peters19717fa2004-10-09 17:38:29 +00001196void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001197_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001198{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001199 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001200 PyThread_tss_delete(&gilstate->autoTSSkey);
1201 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001202}
1203
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001204/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001205 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001206 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001207 */
1208void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001209_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001210{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001211 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001212 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001213
1214 PyThread_tss_delete(&gilstate->autoTSSkey);
1215 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001216 Py_FatalError("Could not allocate TSS entry");
1217 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001218
Charles-François Natalia233df82011-11-22 19:49:51 +01001219 /* If the thread had an associated auto thread state, reassociate it with
1220 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001221 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001222 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001223 {
1224 Py_FatalError("Couldn't create autoTSSkey mapping");
1225 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001226}
1227
Michael W. Hudson188d4362005-06-20 16:52:57 +00001228/* When a thread state is created for a thread by some mechanism other than
1229 PyGILState_Ensure, it's important that the GILState machinery knows about
1230 it so it doesn't try to create another thread state for the thread (this is
1231 a better fix for SF bug #1010677 than the first one attempted).
1232*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001233static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001234_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001235{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001236 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001237 threadstate created in Py_Initialize(). Don't do anything for now
1238 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001239 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001241 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001242
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001243 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 The only situation where you can legitimately have more than one
1246 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001247 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001248
Victor Stinner590cebe2013-12-13 11:08:56 +01001249 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1250 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001251
Victor Stinner590cebe2013-12-13 11:08:56 +01001252 The first thread state created for that given OS level thread will
1253 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001255 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1256 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001257 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001258 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001259 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 /* PyGILState_Release must not try to delete this thread state. */
1262 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001263}
1264
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001265/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001266static PyThreadState *
1267_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1268{
1269 if (gilstate->autoInterpreterState == NULL)
1270 return NULL;
1271 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1272}
1273
Tim Peters19717fa2004-10-09 17:38:29 +00001274PyThreadState *
1275PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001276{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001277 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001278}
1279
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001280int
1281PyGILState_Check(void)
1282{
Victor Stinner8a1be612016-03-14 22:07:55 +01001283
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001284 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001285 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001286 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001287
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001288 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1289 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1290 return 1;
1291 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001292
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001293 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1294 if (tstate == NULL) {
1295 return 0;
1296 }
1297
1298 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001299}
1300
Tim Peters19717fa2004-10-09 17:38:29 +00001301PyGILState_STATE
1302PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001303{
Victor Stinner175a7042020-03-10 00:37:48 +01001304 _PyRuntimeState *runtime = &_PyRuntime;
1305 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 /* Note that we do not auto-init Python here - apart from
1308 potential races with 2 threads auto-initializing, pep-311
1309 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001310 called Py_Initialize(). */
1311
1312 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1313 called by Py_Initialize() */
1314 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001315 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001316
Victor Stinner175a7042020-03-10 00:37:48 +01001317 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1318 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001320 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001321 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001322 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001324 }
1325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 /* This is our thread state! We'll need to delete it in the
1327 matching call to PyGILState_Release(). */
1328 tcur->gilstate_counter = 0;
1329 current = 0; /* new thread state is never current */
1330 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001331 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001333 }
1334
1335 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001337 }
1338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 /* Update our counter in the thread-state - no need for locks:
1340 - tcur will remain valid as we hold the GIL.
1341 - the counter is safe as we are the only thread "allowed"
1342 to modify this value
1343 */
1344 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001347}
1348
Tim Peters19717fa2004-10-09 17:38:29 +00001349void
1350PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001351{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001352 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001353 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1354 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 Py_FatalError("auto-releasing thread-state, "
1356 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001357 }
1358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 /* We must hold the GIL and have our thread state current */
1360 /* XXX - remove the check - the assert should be fine,
1361 but while this is very new (April 2003), the extra check
1362 by release-only users can't hurt.
1363 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001364 if (!PyThreadState_IsCurrent(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 Py_FatalError("This thread state must be current when releasing");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001366 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001367 assert(PyThreadState_IsCurrent(tstate));
1368 --tstate->gilstate_counter;
1369 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 /* If we're going to destroy this thread-state, we must
1372 * clear it while the GIL is held, as destructors may run.
1373 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001374 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 /* can't have been locked when we created it */
1376 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001377 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 /* Delete the thread-state. Note this releases the GIL too!
1379 * It's vital that the GIL be held here, to avoid shutdown
1380 * races; see bugs 225673 and 1061968 (that nasty bug has a
1381 * habit of coming back).
1382 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001383 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1384 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 }
1386 /* Release the lock if necessary */
1387 else if (oldstate == PyGILState_UNLOCKED)
1388 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001389}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001390
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001391
Eric Snow7f8bfc92018-01-29 18:23:44 -07001392/**************************/
1393/* cross-interpreter data */
1394/**************************/
1395
1396/* cross-interpreter data */
1397
1398crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1399
1400/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1401 to keep the registry code separate. */
1402static crossinterpdatafunc
1403_lookup_getdata(PyObject *obj)
1404{
1405 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1406 if (getdata == NULL && PyErr_Occurred() == 0)
1407 PyErr_Format(PyExc_ValueError,
1408 "%S does not support cross-interpreter data", obj);
1409 return getdata;
1410}
1411
1412int
1413_PyObject_CheckCrossInterpreterData(PyObject *obj)
1414{
1415 crossinterpdatafunc getdata = _lookup_getdata(obj);
1416 if (getdata == NULL) {
1417 return -1;
1418 }
1419 return 0;
1420}
1421
1422static int
1423_check_xidata(_PyCrossInterpreterData *data)
1424{
1425 // data->data can be anything, including NULL, so we don't check it.
1426
1427 // data->obj may be NULL, so we don't check it.
1428
1429 if (data->interp < 0) {
1430 PyErr_SetString(PyExc_SystemError, "missing interp");
1431 return -1;
1432 }
1433
1434 if (data->new_object == NULL) {
1435 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1436 return -1;
1437 }
1438
1439 // data->free may be NULL, so we don't check it.
1440
1441 return 0;
1442}
1443
1444int
1445_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1446{
Victor Stinnerbe793732020-03-13 18:15:33 +01001447 // PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001448 // to check the result for NULL.
Victor Stinnerbe793732020-03-13 18:15:33 +01001449 PyInterpreterState *interp = PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001450
1451 // Reset data before re-populating.
1452 *data = (_PyCrossInterpreterData){0};
1453 data->free = PyMem_RawFree; // Set a default that may be overridden.
1454
1455 // Call the "getdata" func for the object.
1456 Py_INCREF(obj);
1457 crossinterpdatafunc getdata = _lookup_getdata(obj);
1458 if (getdata == NULL) {
1459 Py_DECREF(obj);
1460 return -1;
1461 }
1462 int res = getdata(obj, data);
1463 Py_DECREF(obj);
1464 if (res != 0) {
1465 return -1;
1466 }
1467
1468 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001469 data->interp = interp->id;
1470 if (_check_xidata(data) != 0) {
1471 _PyCrossInterpreterData_Release(data);
1472 return -1;
1473 }
1474
1475 return 0;
1476}
1477
Victor Stinnere225beb2019-06-03 18:14:24 +02001478static void
Eric Snow63799132018-06-01 18:45:20 -06001479_release_xidata(void *arg)
1480{
1481 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1482 if (data->free != NULL) {
1483 data->free(data->data);
1484 }
1485 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001486}
1487
1488static void
1489_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1490 PyInterpreterState *interp,
1491 void (*func)(void *), void *arg)
1492{
1493 /* We would use Py_AddPendingCall() if it weren't specific to the
1494 * main interpreter (see bpo-33608). In the meantime we take a
1495 * naive approach.
1496 */
1497 PyThreadState *save_tstate = NULL;
1498 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1499 // XXX Using the "head" thread isn't strictly correct.
1500 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1501 // XXX Possible GILState issues?
1502 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1503 }
1504
1505 func(arg);
1506
1507 // Switch back.
1508 if (save_tstate != NULL) {
1509 _PyThreadState_Swap(gilstate, save_tstate);
1510 }
Eric Snow63799132018-06-01 18:45:20 -06001511}
1512
Eric Snow7f8bfc92018-01-29 18:23:44 -07001513void
1514_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1515{
1516 if (data->data == NULL && data->obj == NULL) {
1517 // Nothing to release!
1518 return;
1519 }
1520
Victor Stinnere225beb2019-06-03 18:14:24 +02001521 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001522 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1523 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001524 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001525 if (data->free != NULL) {
1526 // XXX Someone leaked some memory...
1527 }
1528 return;
1529 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001530
Eric Snow7f8bfc92018-01-29 18:23:44 -07001531 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001532 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1533 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001534}
1535
1536PyObject *
1537_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1538{
1539 return data->new_object(data);
1540}
1541
1542/* registry of {type -> crossinterpdatafunc} */
1543
1544/* For now we use a global registry of shareable classes. An
1545 alternative would be to add a tp_* slot for a class's
1546 crossinterpdatafunc. It would be simpler and more efficient. */
1547
1548static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001549_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1550 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001551{
1552 // Note that we effectively replace already registered classes
1553 // rather than failing.
1554 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1555 if (newhead == NULL)
1556 return -1;
1557 newhead->cls = cls;
1558 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001559 newhead->next = xidregistry->head;
1560 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001561 return 0;
1562}
1563
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001564static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001565
1566int
Eric Snowc11183c2019-03-15 16:35:46 -06001567_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001568 crossinterpdatafunc getdata)
1569{
1570 if (!PyType_Check(cls)) {
1571 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1572 return -1;
1573 }
1574 if (getdata == NULL) {
1575 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1576 return -1;
1577 }
1578
1579 // Make sure the class isn't ever deallocated.
1580 Py_INCREF((PyObject *)cls);
1581
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001582 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1583 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1584 if (xidregistry->head == NULL) {
1585 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001586 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001587 int res = _register_xidata(xidregistry, cls, getdata);
1588 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001589 return res;
1590}
1591
Eric Snow6d2cd902018-05-16 15:04:57 -04001592/* Cross-interpreter objects are looked up by exact match on the class.
1593 We can reassess this policy when we move from a global registry to a
1594 tp_* slot. */
1595
Eric Snow7f8bfc92018-01-29 18:23:44 -07001596crossinterpdatafunc
1597_PyCrossInterpreterData_Lookup(PyObject *obj)
1598{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001599 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001600 PyObject *cls = PyObject_Type(obj);
1601 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001602 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1603 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001604 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001605 _register_builtins_for_crossinterpreter_data(xidregistry);
1606 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001607 }
1608 for(; cur != NULL; cur = cur->next) {
1609 if (cur->cls == (PyTypeObject *)cls) {
1610 getdata = cur->getdata;
1611 break;
1612 }
1613 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001614 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001615 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001616 return getdata;
1617}
1618
1619/* cross-interpreter data for builtin types */
1620
Eric Snow6d2cd902018-05-16 15:04:57 -04001621struct _shared_bytes_data {
1622 char *bytes;
1623 Py_ssize_t len;
1624};
1625
Eric Snow7f8bfc92018-01-29 18:23:44 -07001626static PyObject *
1627_new_bytes_object(_PyCrossInterpreterData *data)
1628{
Eric Snow6d2cd902018-05-16 15:04:57 -04001629 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1630 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001631}
1632
1633static int
1634_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1635{
Eric Snow6d2cd902018-05-16 15:04:57 -04001636 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1637 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1638 return -1;
1639 }
1640 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001641 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001642 data->obj = obj; // Will be "released" (decref'ed) when data released.
1643 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001644 data->free = PyMem_Free;
1645 return 0;
1646}
1647
1648struct _shared_str_data {
1649 int kind;
1650 const void *buffer;
1651 Py_ssize_t len;
1652};
1653
1654static PyObject *
1655_new_str_object(_PyCrossInterpreterData *data)
1656{
1657 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1658 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1659}
1660
1661static int
1662_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1663{
1664 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1665 shared->kind = PyUnicode_KIND(obj);
1666 shared->buffer = PyUnicode_DATA(obj);
1667 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1668 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001669 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001670 data->obj = obj; // Will be "released" (decref'ed) when data released.
1671 data->new_object = _new_str_object;
1672 data->free = PyMem_Free;
1673 return 0;
1674}
1675
1676static PyObject *
1677_new_long_object(_PyCrossInterpreterData *data)
1678{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001679 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001680}
1681
1682static int
1683_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1684{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001685 /* Note that this means the size of shareable ints is bounded by
1686 * sys.maxsize. Hence on 32-bit architectures that is half the
1687 * size of maximum shareable ints on 64-bit.
1688 */
1689 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001690 if (value == -1 && PyErr_Occurred()) {
1691 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1692 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1693 }
1694 return -1;
1695 }
1696 data->data = (void *)value;
1697 data->obj = NULL;
1698 data->new_object = _new_long_object;
1699 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001700 return 0;
1701}
1702
1703static PyObject *
1704_new_none_object(_PyCrossInterpreterData *data)
1705{
1706 // XXX Singleton refcounts are problematic across interpreters...
1707 Py_INCREF(Py_None);
1708 return Py_None;
1709}
1710
1711static int
1712_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1713{
1714 data->data = NULL;
1715 // data->obj remains NULL
1716 data->new_object = _new_none_object;
1717 data->free = NULL; // There is nothing to free.
1718 return 0;
1719}
1720
1721static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001722_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001723{
1724 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001725 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001726 Py_FatalError("could not register None for cross-interpreter sharing");
1727 }
1728
Eric Snow6d2cd902018-05-16 15:04:57 -04001729 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001730 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001731 Py_FatalError("could not register int for cross-interpreter sharing");
1732 }
1733
Eric Snow7f8bfc92018-01-29 18:23:44 -07001734 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001735 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001736 Py_FatalError("could not register bytes for cross-interpreter sharing");
1737 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001738
1739 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001740 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001741 Py_FatalError("could not register str for cross-interpreter sharing");
1742 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001743}
1744
1745
Victor Stinner0b72b232020-03-12 23:18:39 +01001746_PyFrameEvalFunction
1747_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1748{
1749 return interp->eval_frame;
1750}
1751
1752
1753void
1754_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1755 _PyFrameEvalFunction eval_frame)
1756{
1757 interp->eval_frame = eval_frame;
1758}
1759
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001760#ifdef __cplusplus
1761}
1762#endif