blob: 8f0b6b87d651a954361f4746c30ad6306b4e182b [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
Victor Stinner45b9be52010-03-03 23:28:07 +0000549static PyThreadState *
550new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000551{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100552 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200553 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200554 if (tstate == NULL) {
555 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000557
Victor Stinner8bb32302019-04-24 16:47:40 +0200558 tstate->interp = interp;
559
560 tstate->frame = NULL;
561 tstate->recursion_depth = 0;
562 tstate->overflowed = 0;
563 tstate->recursion_critical = 0;
564 tstate->stackcheck_counter = 0;
565 tstate->tracing = 0;
566 tstate->use_tracing = 0;
567 tstate->gilstate_counter = 0;
568 tstate->async_exc = NULL;
569 tstate->thread_id = PyThread_get_thread_ident();
570
571 tstate->dict = NULL;
572
573 tstate->curexc_type = NULL;
574 tstate->curexc_value = NULL;
575 tstate->curexc_traceback = NULL;
576
577 tstate->exc_state.exc_type = NULL;
578 tstate->exc_state.exc_value = NULL;
579 tstate->exc_state.exc_traceback = NULL;
580 tstate->exc_state.previous_item = NULL;
581 tstate->exc_info = &tstate->exc_state;
582
583 tstate->c_profilefunc = NULL;
584 tstate->c_tracefunc = NULL;
585 tstate->c_profileobj = NULL;
586 tstate->c_traceobj = NULL;
587
588 tstate->trash_delete_nesting = 0;
589 tstate->trash_delete_later = NULL;
590 tstate->on_delete = NULL;
591 tstate->on_delete_data = NULL;
592
593 tstate->coroutine_origin_tracking_depth = 0;
594
Victor Stinner8bb32302019-04-24 16:47:40 +0200595 tstate->async_gen_firstiter = NULL;
596 tstate->async_gen_finalizer = NULL;
597
598 tstate->context = NULL;
599 tstate->context_ver = 1;
600
Victor Stinner8bb32302019-04-24 16:47:40 +0200601 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100602 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200603 }
604
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200605 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100606 tstate->id = ++interp->tstate_next_unique_id;
Victor Stinner8bb32302019-04-24 16:47:40 +0200607 tstate->prev = NULL;
608 tstate->next = interp->tstate_head;
609 if (tstate->next)
610 tstate->next->prev = tstate;
611 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200612 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000615}
616
Victor Stinner45b9be52010-03-03 23:28:07 +0000617PyThreadState *
618PyThreadState_New(PyInterpreterState *interp)
619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000621}
622
623PyThreadState *
624_PyThreadState_Prealloc(PyInterpreterState *interp)
625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000627}
628
629void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100630_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000631{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100632 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000633}
634
Martin v. Löwis1a214512008-06-11 05:26:20 +0000635PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200636PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000637{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200638 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100639 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000641 if (module->m_slots) {
642 return NULL;
643 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if (index == 0)
645 return NULL;
646 if (state->modules_by_index == NULL)
647 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200648 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 return NULL;
650 res = PyList_GET_ITEM(state->modules_by_index, index);
651 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000652}
653
654int
Victor Stinner82c83bd2019-11-22 18:52:27 +0100655_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000656{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300657 if (!def) {
658 assert(PyErr_Occurred());
659 return -1;
660 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000661 if (def->m_slots) {
662 PyErr_SetString(PyExc_SystemError,
663 "PyState_AddModule called on module with slots");
664 return -1;
665 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100666
667 PyInterpreterState *interp = tstate->interp;
668 if (!interp->modules_by_index) {
669 interp->modules_by_index = PyList_New(0);
670 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100672 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100674
675 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
676 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100678 }
679 }
680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100682 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000684}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000685
Martin v. Löwis7800f752012-06-22 12:20:55 +0200686int
687PyState_AddModule(PyObject* module, struct PyModuleDef* def)
688{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200689 if (!def) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100690 Py_FatalError("Module Definition is NULL");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200691 return -1;
692 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100693
694 PyThreadState *tstate = _PyThreadState_GET();
695 PyInterpreterState *interp = tstate->interp;
696 Py_ssize_t index = def->m_base.m_index;
697 if (interp->modules_by_index &&
698 index < PyList_GET_SIZE(interp->modules_by_index) &&
699 module == PyList_GET_ITEM(interp->modules_by_index, index))
700 {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100701 Py_FatalError("Module already added");
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100702 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200703 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100704 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200705}
706
707int
708PyState_RemoveModule(struct PyModuleDef* def)
709{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000710 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200711 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000712 if (def->m_slots) {
713 PyErr_SetString(PyExc_SystemError,
714 "PyState_RemoveModule called on module with slots");
715 return -1;
716 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100717 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200718 if (index == 0) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100719 Py_FatalError("Module index invalid");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200720 return -1;
721 }
722 if (state->modules_by_index == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100723 Py_FatalError("Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200724 return -1;
725 }
726 if (index > PyList_GET_SIZE(state->modules_by_index)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100727 Py_FatalError("Module index out of bounds.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200728 return -1;
729 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700730 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200731 return PyList_SetItem(state->modules_by_index, index, Py_None);
732}
733
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200734/* Used by PyImport_Cleanup() */
Antoine Pitrou40322e62013-08-11 00:30:09 +0200735void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200736_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200737{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200738 if (!interp->modules_by_index) {
739 return;
740 }
741
742 Py_ssize_t i;
743 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
744 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
745 if (PyModule_Check(m)) {
746 /* cleanup the saved copy of module dicts */
747 PyModuleDef *md = PyModule_GetDef(m);
748 if (md) {
749 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200750 }
751 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200752 }
753
754 /* Setting modules_by_index to NULL could be dangerous, so we
755 clear the list instead. */
756 if (PyList_SetSlice(interp->modules_by_index,
757 0, PyList_GET_SIZE(interp->modules_by_index),
758 NULL)) {
759 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200760 }
761}
762
Guido van Rossuma027efa1997-05-05 20:56:21 +0000763void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000764PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000765{
Victor Stinner331a6a52019-05-27 16:39:22 +0200766 int verbose = tstate->interp->config.verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200767
Victor Stinner5804f872020-03-24 16:32:26 +0100768 if (verbose && tstate->frame != NULL) {
769 /* bpo-20526: After the main thread calls
770 _PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
771 exit when trying to take the GIL. If a thread exit in the middle of
772 _PyEval_EvalFrameDefault(), tstate->frame is not reset to its
773 previous value. It is more likely with daemon threads, but it can
774 happen with regular threads if threading._shutdown() fails
775 (ex: interrupted by CTRL+C). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 fprintf(stderr,
777 "PyThreadState_Clear: warning: thread still has a frame\n");
Victor Stinner5804f872020-03-24 16:32:26 +0100778 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000779
Victor Stinner5804f872020-03-24 16:32:26 +0100780 /* Don't clear tstate->frame: it is a borrowed reference */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 Py_CLEAR(tstate->dict);
783 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 Py_CLEAR(tstate->curexc_type);
786 Py_CLEAR(tstate->curexc_value);
787 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000788
Mark Shannonae3087c2017-10-22 22:41:51 +0100789 Py_CLEAR(tstate->exc_state.exc_type);
790 Py_CLEAR(tstate->exc_state.exc_value);
791 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300792
Mark Shannonae3087c2017-10-22 22:41:51 +0100793 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200794 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100795 fprintf(stderr,
796 "PyThreadState_Clear: warning: thread still has a generator\n");
797 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 tstate->c_profilefunc = NULL;
800 tstate->c_tracefunc = NULL;
801 Py_CLEAR(tstate->c_profileobj);
802 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400803
Yury Selivanoveb636452016-09-08 22:01:51 -0700804 Py_CLEAR(tstate->async_gen_firstiter);
805 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500806
807 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100808
809 if (tstate->on_delete != NULL) {
810 tstate->on_delete(tstate->on_delete_data);
811 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000812}
813
814
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300815/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000816static void
Victor Stinner9da74302019-11-20 11:17:17 +0100817tstate_delete_common(PyThreadState *tstate,
818 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000819{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100820 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner23ef89d2020-03-18 02:26:04 +0100821 ensure_tstate_not_null(__func__, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200822 PyInterpreterState *interp = tstate->interp;
823 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100824 Py_FatalError("NULL interp");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200825 }
826 HEAD_LOCK(runtime);
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200827 if (tstate->prev)
828 tstate->prev->next = tstate->next;
829 else
830 interp->tstate_head = tstate->next;
831 if (tstate->next)
832 tstate->next->prev = tstate->prev;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200833 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100834
Victor Stinner9da74302019-11-20 11:17:17 +0100835 if (gilstate->autoInterpreterState &&
836 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
837 {
838 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
839 }
840}
841
842
843static void
844_PyThreadState_Delete(PyThreadState *tstate, int check_current)
845{
846 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
847 if (check_current) {
848 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100849 Py_FatalError("tstate is still current");
Victor Stinner9da74302019-11-20 11:17:17 +0100850 }
851 }
852 tstate_delete_common(tstate, gilstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100853 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000854}
855
856
Victor Stinner01b1cc12019-11-20 02:27:56 +0100857void
858PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000859{
Victor Stinner9da74302019-11-20 11:17:17 +0100860 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200861}
862
863
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300864void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100865_PyThreadState_DeleteCurrent(PyThreadState *tstate)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200866{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100867 ensure_tstate_not_null(__func__, tstate);
868 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner9da74302019-11-20 11:17:17 +0100869 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200870 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100871 _PyEval_ReleaseLock(tstate);
872 PyMem_RawFree(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000873}
Guido van Rossum29757862001-01-23 01:46:06 +0000874
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300875void
876PyThreadState_DeleteCurrent(void)
877{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100878 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
879 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
880 _PyThreadState_DeleteCurrent(tstate);
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300881}
882
Guido van Rossum29757862001-01-23 01:46:06 +0000883
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200884/*
885 * Delete all thread states except the one passed as argument.
886 * Note that, if there is a current thread state, it *must* be the one
887 * passed as argument. Also, this won't touch any other interpreters
888 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000889 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200890 */
891void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200892_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200893{
894 PyInterpreterState *interp = tstate->interp;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100895
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200896 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200897 /* Remove all thread states, except tstate, from the linked list of
898 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200899 without holding the lock. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100900 PyThreadState *list = interp->tstate_head;
901 if (list == tstate) {
902 list = tstate->next;
903 }
904 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200905 tstate->prev->next = tstate->next;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100906 }
907 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200908 tstate->next->prev = tstate->prev;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100909 }
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200910 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200911 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200912 HEAD_UNLOCK(runtime);
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100913
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200914 /* Clear and deallocate all stale thread states. Even if this
915 executes Python code, we should be safe since it executes
916 in the current thread, not one of the stale threads. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100917 PyThreadState *p, *next;
918 for (p = list; p; p = next) {
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200919 next = p->next;
920 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200921 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200922 }
923}
924
925
Guido van Rossuma027efa1997-05-05 20:56:21 +0000926PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100927_PyThreadState_UncheckedGet(void)
928{
Victor Stinner50b48572018-11-01 01:51:40 +0100929 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100930}
931
932
933PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000934PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000935{
Victor Stinner50b48572018-11-01 01:51:40 +0100936 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner23ef89d2020-03-18 02:26:04 +0100937 ensure_tstate_not_null(__func__, tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000939}
940
941
Victor Stinner09532fe2019-05-10 23:39:09 +0200942PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200943_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000944{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200945 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000946
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200947 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* It should not be possible for more than one thread state
949 to be used for a thread. Check this the best we can in debug
950 builds.
951 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200952#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 if (newts) {
954 /* This can be called from PyEval_RestoreThread(). Similar
955 to it, we need to ensure errno doesn't change.
956 */
957 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200958 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 if (check && check->interp == newts->interp && check != newts)
960 Py_FatalError("Invalid thread state for this thread");
961 errno = err;
962 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000963#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000965}
Guido van Rossumede04391998-04-10 20:18:25 +0000966
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200967PyThreadState *
968PyThreadState_Swap(PyThreadState *newts)
969{
970 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
971}
972
Guido van Rossumede04391998-04-10 20:18:25 +0000973/* An extension mechanism to store arbitrary additional per-thread state.
974 PyThreadState_GetDict() returns a dictionary that can be used to hold such
975 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000976 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
977 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000978
979PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000980PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000981{
Victor Stinner50b48572018-11-01 01:51:40 +0100982 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 if (tstate == NULL)
984 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (tstate->dict == NULL) {
987 PyObject *d;
988 tstate->dict = d = PyDict_New();
989 if (d == NULL)
990 PyErr_Clear();
991 }
992 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000993}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000994
995
Victor Stinner8fb02b62020-03-13 23:38:08 +0100996PyInterpreterState *
997PyThreadState_GetInterpreter(PyThreadState *tstate)
998{
999 assert(tstate != NULL);
Victor Stinner8fb02b62020-03-13 23:38:08 +01001000 return tstate->interp;
1001}
1002
1003
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001004struct _frame*
1005PyThreadState_GetFrame(PyThreadState *tstate)
1006{
1007 assert(tstate != NULL);
Victor Stinner6723e932020-03-20 17:46:56 +01001008 return tstate->frame;
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001009}
1010
1011
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001012/* Asynchronously raise an exception in a thread.
1013 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001014 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001015 to call this, or use ctypes. Must be called with the GIL held.
1016 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1017 match any known thread id). Can be called with exc=NULL to clear an
1018 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001019
1020int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001021PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1022{
Victor Stinner09532fe2019-05-10 23:39:09 +02001023 _PyRuntimeState *runtime = &_PyRuntime;
1024 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 /* Although the GIL is held, a few C API functions can be called
1027 * without the GIL held, and in particular some that create and
1028 * destroy thread and interpreter states. Those can mutate the
1029 * list of thread states we're traversing, so to prevent that we lock
1030 * head_mutex for the duration.
1031 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001032 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001033 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1034 if (tstate->thread_id != id) {
1035 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001037
1038 /* Tricky: we need to decref the current value
1039 * (if any) in tstate->async_exc, but that can in turn
1040 * allow arbitrary Python code to run, including
1041 * perhaps calls to this function. To prevent
1042 * deadlock, we need to release head_mutex before
1043 * the decref.
1044 */
1045 PyObject *old_exc = tstate->async_exc;
1046 Py_XINCREF(exc);
1047 tstate->async_exc = exc;
1048 HEAD_UNLOCK(runtime);
1049
1050 Py_XDECREF(old_exc);
1051 _PyEval_SignalAsyncExc(tstate);
1052 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001054 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001056}
1057
1058
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001059/* Routines for advanced debuggers, requested by David Beazley.
1060 Don't use unless you know what you are doing! */
1061
1062PyInterpreterState *
1063PyInterpreterState_Head(void)
1064{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001065 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001066}
1067
1068PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001069PyInterpreterState_Main(void)
1070{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001071 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001072}
1073
1074PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001075PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001077}
1078
1079PyThreadState *
1080PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001082}
1083
1084PyThreadState *
1085PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001087}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001088
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001089/* The implementation of sys._current_frames(). This is intended to be
1090 called with the GIL held, as it will be when called via
1091 sys._current_frames(). It's possible it would work fine even without
1092 the GIL held, but haven't thought enough about that.
1093*/
1094PyObject *
1095_PyThread_CurrentFrames(void)
1096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 PyObject *result;
1098 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001099
Steve Dowerb82e17e2019-05-23 08:45:22 -07001100 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1101 return NULL;
1102 }
1103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 result = PyDict_New();
1105 if (result == NULL)
1106 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 /* for i in all interpreters:
1109 * for t in all of i's thread states:
1110 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001111 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 * need to grab head_mutex for the duration.
1113 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001114 _PyRuntimeState *runtime = &_PyRuntime;
1115 HEAD_LOCK(runtime);
1116 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 PyThreadState *t;
1118 for (t = i->tstate_head; t != NULL; t = t->next) {
1119 PyObject *id;
1120 int stat;
1121 struct _frame *frame = t->frame;
1122 if (frame == NULL)
1123 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001124 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 if (id == NULL)
1126 goto Fail;
1127 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1128 Py_DECREF(id);
1129 if (stat < 0)
1130 goto Fail;
1131 }
1132 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001133 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001135
1136 Fail:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001137 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 Py_DECREF(result);
1139 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001140}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001141
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001142/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001143
1144/* Keep this as a static, as it is not reliable! It can only
1145 ever be compared to the state for the *current* thread.
1146 * If not equal, then it doesn't matter that the actual
1147 value may change immediately after comparison, as it can't
1148 possibly change to the current thread's state.
1149 * If equal, then the current thread holds the lock, so the value can't
1150 change until we yield the lock.
1151*/
1152static int
1153PyThreadState_IsCurrent(PyThreadState *tstate)
1154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001156 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001157 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1158 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001159}
1160
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001161/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001162 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001163*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001164PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001165_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001166{
Victor Stinner8bb32302019-04-24 16:47:40 +02001167 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001168 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001169 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001170
Victor Stinner01b1cc12019-11-20 02:27:56 +01001171 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001172
1173 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001174 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001175 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001176 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001177 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1178 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001179
Victor Stinner8bb32302019-04-24 16:47:40 +02001180 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001181 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001182}
1183
Victor Stinner861d9ab2016-03-16 22:45:24 +01001184PyInterpreterState *
1185_PyGILState_GetInterpreterStateUnsafe(void)
1186{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001187 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001188}
1189
Tim Peters19717fa2004-10-09 17:38:29 +00001190void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001191_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001192{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001193 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001194 PyThread_tss_delete(&gilstate->autoTSSkey);
1195 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001196}
1197
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001198/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001199 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001200 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001201 */
1202void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001203_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001204{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001205 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001206 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001207
1208 PyThread_tss_delete(&gilstate->autoTSSkey);
1209 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001210 Py_FatalError("Could not allocate TSS entry");
1211 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001212
Charles-François Natalia233df82011-11-22 19:49:51 +01001213 /* If the thread had an associated auto thread state, reassociate it with
1214 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001215 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001216 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001217 {
1218 Py_FatalError("Couldn't create autoTSSkey mapping");
1219 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001220}
1221
Michael W. Hudson188d4362005-06-20 16:52:57 +00001222/* When a thread state is created for a thread by some mechanism other than
1223 PyGILState_Ensure, it's important that the GILState machinery knows about
1224 it so it doesn't try to create another thread state for the thread (this is
1225 a better fix for SF bug #1010677 than the first one attempted).
1226*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001227static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001228_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001229{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001230 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001231 threadstate created in Py_Initialize(). Don't do anything for now
1232 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001233 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001235 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001236
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001237 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 The only situation where you can legitimately have more than one
1240 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001241 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001242
Victor Stinner590cebe2013-12-13 11:08:56 +01001243 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1244 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001245
Victor Stinner590cebe2013-12-13 11:08:56 +01001246 The first thread state created for that given OS level thread will
1247 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001249 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1250 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001251 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001252 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001253 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 /* PyGILState_Release must not try to delete this thread state. */
1256 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001257}
1258
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001259/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001260static PyThreadState *
1261_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1262{
1263 if (gilstate->autoInterpreterState == NULL)
1264 return NULL;
1265 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1266}
1267
Tim Peters19717fa2004-10-09 17:38:29 +00001268PyThreadState *
1269PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001270{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001271 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001272}
1273
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001274int
1275PyGILState_Check(void)
1276{
Victor Stinner8a1be612016-03-14 22:07:55 +01001277
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001278 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001279 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001280 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001281
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001282 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1283 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1284 return 1;
1285 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001286
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001287 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1288 if (tstate == NULL) {
1289 return 0;
1290 }
1291
1292 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001293}
1294
Tim Peters19717fa2004-10-09 17:38:29 +00001295PyGILState_STATE
1296PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001297{
Victor Stinner175a7042020-03-10 00:37:48 +01001298 _PyRuntimeState *runtime = &_PyRuntime;
1299 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 /* Note that we do not auto-init Python here - apart from
1302 potential races with 2 threads auto-initializing, pep-311
1303 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001304 called Py_Initialize(). */
1305
1306 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1307 called by Py_Initialize() */
1308 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001309 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001310
Victor Stinner175a7042020-03-10 00:37:48 +01001311 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1312 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001314 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001315 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001316 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001318 }
1319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 /* This is our thread state! We'll need to delete it in the
1321 matching call to PyGILState_Release(). */
1322 tcur->gilstate_counter = 0;
1323 current = 0; /* new thread state is never current */
1324 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001325 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001327 }
1328
1329 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001331 }
1332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 /* Update our counter in the thread-state - no need for locks:
1334 - tcur will remain valid as we hold the GIL.
1335 - the counter is safe as we are the only thread "allowed"
1336 to modify this value
1337 */
1338 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001341}
1342
Tim Peters19717fa2004-10-09 17:38:29 +00001343void
1344PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001345{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001346 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001347 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1348 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 Py_FatalError("auto-releasing thread-state, "
1350 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001351 }
1352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 /* We must hold the GIL and have our thread state current */
1354 /* XXX - remove the check - the assert should be fine,
1355 but while this is very new (April 2003), the extra check
1356 by release-only users can't hurt.
1357 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001358 if (!PyThreadState_IsCurrent(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 Py_FatalError("This thread state must be current when releasing");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001360 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001361 assert(PyThreadState_IsCurrent(tstate));
1362 --tstate->gilstate_counter;
1363 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 /* If we're going to destroy this thread-state, we must
1366 * clear it while the GIL is held, as destructors may run.
1367 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001368 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 /* can't have been locked when we created it */
1370 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001371 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 /* Delete the thread-state. Note this releases the GIL too!
1373 * It's vital that the GIL be held here, to avoid shutdown
1374 * races; see bugs 225673 and 1061968 (that nasty bug has a
1375 * habit of coming back).
1376 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001377 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1378 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 }
1380 /* Release the lock if necessary */
1381 else if (oldstate == PyGILState_UNLOCKED)
1382 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001383}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001384
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001385
Eric Snow7f8bfc92018-01-29 18:23:44 -07001386/**************************/
1387/* cross-interpreter data */
1388/**************************/
1389
1390/* cross-interpreter data */
1391
1392crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1393
1394/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1395 to keep the registry code separate. */
1396static crossinterpdatafunc
1397_lookup_getdata(PyObject *obj)
1398{
1399 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1400 if (getdata == NULL && PyErr_Occurred() == 0)
1401 PyErr_Format(PyExc_ValueError,
1402 "%S does not support cross-interpreter data", obj);
1403 return getdata;
1404}
1405
1406int
1407_PyObject_CheckCrossInterpreterData(PyObject *obj)
1408{
1409 crossinterpdatafunc getdata = _lookup_getdata(obj);
1410 if (getdata == NULL) {
1411 return -1;
1412 }
1413 return 0;
1414}
1415
1416static int
1417_check_xidata(_PyCrossInterpreterData *data)
1418{
1419 // data->data can be anything, including NULL, so we don't check it.
1420
1421 // data->obj may be NULL, so we don't check it.
1422
1423 if (data->interp < 0) {
1424 PyErr_SetString(PyExc_SystemError, "missing interp");
1425 return -1;
1426 }
1427
1428 if (data->new_object == NULL) {
1429 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1430 return -1;
1431 }
1432
1433 // data->free may be NULL, so we don't check it.
1434
1435 return 0;
1436}
1437
1438int
1439_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1440{
Victor Stinnerbe793732020-03-13 18:15:33 +01001441 // PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001442 // to check the result for NULL.
Victor Stinnerbe793732020-03-13 18:15:33 +01001443 PyInterpreterState *interp = PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001444
1445 // Reset data before re-populating.
1446 *data = (_PyCrossInterpreterData){0};
1447 data->free = PyMem_RawFree; // Set a default that may be overridden.
1448
1449 // Call the "getdata" func for the object.
1450 Py_INCREF(obj);
1451 crossinterpdatafunc getdata = _lookup_getdata(obj);
1452 if (getdata == NULL) {
1453 Py_DECREF(obj);
1454 return -1;
1455 }
1456 int res = getdata(obj, data);
1457 Py_DECREF(obj);
1458 if (res != 0) {
1459 return -1;
1460 }
1461
1462 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001463 data->interp = interp->id;
1464 if (_check_xidata(data) != 0) {
1465 _PyCrossInterpreterData_Release(data);
1466 return -1;
1467 }
1468
1469 return 0;
1470}
1471
Victor Stinnere225beb2019-06-03 18:14:24 +02001472static void
Eric Snow63799132018-06-01 18:45:20 -06001473_release_xidata(void *arg)
1474{
1475 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1476 if (data->free != NULL) {
1477 data->free(data->data);
1478 }
1479 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001480}
1481
1482static void
1483_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1484 PyInterpreterState *interp,
1485 void (*func)(void *), void *arg)
1486{
1487 /* We would use Py_AddPendingCall() if it weren't specific to the
1488 * main interpreter (see bpo-33608). In the meantime we take a
1489 * naive approach.
1490 */
1491 PyThreadState *save_tstate = NULL;
1492 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1493 // XXX Using the "head" thread isn't strictly correct.
1494 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1495 // XXX Possible GILState issues?
1496 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1497 }
1498
1499 func(arg);
1500
1501 // Switch back.
1502 if (save_tstate != NULL) {
1503 _PyThreadState_Swap(gilstate, save_tstate);
1504 }
Eric Snow63799132018-06-01 18:45:20 -06001505}
1506
Eric Snow7f8bfc92018-01-29 18:23:44 -07001507void
1508_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1509{
1510 if (data->data == NULL && data->obj == NULL) {
1511 // Nothing to release!
1512 return;
1513 }
1514
Victor Stinnere225beb2019-06-03 18:14:24 +02001515 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001516 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1517 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001518 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001519 if (data->free != NULL) {
1520 // XXX Someone leaked some memory...
1521 }
1522 return;
1523 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001524
Eric Snow7f8bfc92018-01-29 18:23:44 -07001525 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001526 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1527 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001528}
1529
1530PyObject *
1531_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1532{
1533 return data->new_object(data);
1534}
1535
1536/* registry of {type -> crossinterpdatafunc} */
1537
1538/* For now we use a global registry of shareable classes. An
1539 alternative would be to add a tp_* slot for a class's
1540 crossinterpdatafunc. It would be simpler and more efficient. */
1541
1542static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001543_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1544 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001545{
1546 // Note that we effectively replace already registered classes
1547 // rather than failing.
1548 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1549 if (newhead == NULL)
1550 return -1;
1551 newhead->cls = cls;
1552 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001553 newhead->next = xidregistry->head;
1554 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001555 return 0;
1556}
1557
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001558static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001559
1560int
Eric Snowc11183c2019-03-15 16:35:46 -06001561_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001562 crossinterpdatafunc getdata)
1563{
1564 if (!PyType_Check(cls)) {
1565 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1566 return -1;
1567 }
1568 if (getdata == NULL) {
1569 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1570 return -1;
1571 }
1572
1573 // Make sure the class isn't ever deallocated.
1574 Py_INCREF((PyObject *)cls);
1575
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001576 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1577 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1578 if (xidregistry->head == NULL) {
1579 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001580 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001581 int res = _register_xidata(xidregistry, cls, getdata);
1582 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001583 return res;
1584}
1585
Eric Snow6d2cd902018-05-16 15:04:57 -04001586/* Cross-interpreter objects are looked up by exact match on the class.
1587 We can reassess this policy when we move from a global registry to a
1588 tp_* slot. */
1589
Eric Snow7f8bfc92018-01-29 18:23:44 -07001590crossinterpdatafunc
1591_PyCrossInterpreterData_Lookup(PyObject *obj)
1592{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001593 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001594 PyObject *cls = PyObject_Type(obj);
1595 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001596 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1597 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001598 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001599 _register_builtins_for_crossinterpreter_data(xidregistry);
1600 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001601 }
1602 for(; cur != NULL; cur = cur->next) {
1603 if (cur->cls == (PyTypeObject *)cls) {
1604 getdata = cur->getdata;
1605 break;
1606 }
1607 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001608 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001609 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001610 return getdata;
1611}
1612
1613/* cross-interpreter data for builtin types */
1614
Eric Snow6d2cd902018-05-16 15:04:57 -04001615struct _shared_bytes_data {
1616 char *bytes;
1617 Py_ssize_t len;
1618};
1619
Eric Snow7f8bfc92018-01-29 18:23:44 -07001620static PyObject *
1621_new_bytes_object(_PyCrossInterpreterData *data)
1622{
Eric Snow6d2cd902018-05-16 15:04:57 -04001623 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1624 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001625}
1626
1627static int
1628_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1629{
Eric Snow6d2cd902018-05-16 15:04:57 -04001630 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1631 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1632 return -1;
1633 }
1634 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001635 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001636 data->obj = obj; // Will be "released" (decref'ed) when data released.
1637 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001638 data->free = PyMem_Free;
1639 return 0;
1640}
1641
1642struct _shared_str_data {
1643 int kind;
1644 const void *buffer;
1645 Py_ssize_t len;
1646};
1647
1648static PyObject *
1649_new_str_object(_PyCrossInterpreterData *data)
1650{
1651 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1652 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1653}
1654
1655static int
1656_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1657{
1658 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1659 shared->kind = PyUnicode_KIND(obj);
1660 shared->buffer = PyUnicode_DATA(obj);
1661 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1662 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001663 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001664 data->obj = obj; // Will be "released" (decref'ed) when data released.
1665 data->new_object = _new_str_object;
1666 data->free = PyMem_Free;
1667 return 0;
1668}
1669
1670static PyObject *
1671_new_long_object(_PyCrossInterpreterData *data)
1672{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001673 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001674}
1675
1676static int
1677_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1678{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001679 /* Note that this means the size of shareable ints is bounded by
1680 * sys.maxsize. Hence on 32-bit architectures that is half the
1681 * size of maximum shareable ints on 64-bit.
1682 */
1683 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001684 if (value == -1 && PyErr_Occurred()) {
1685 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1686 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1687 }
1688 return -1;
1689 }
1690 data->data = (void *)value;
1691 data->obj = NULL;
1692 data->new_object = _new_long_object;
1693 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001694 return 0;
1695}
1696
1697static PyObject *
1698_new_none_object(_PyCrossInterpreterData *data)
1699{
1700 // XXX Singleton refcounts are problematic across interpreters...
1701 Py_INCREF(Py_None);
1702 return Py_None;
1703}
1704
1705static int
1706_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1707{
1708 data->data = NULL;
1709 // data->obj remains NULL
1710 data->new_object = _new_none_object;
1711 data->free = NULL; // There is nothing to free.
1712 return 0;
1713}
1714
1715static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001716_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001717{
1718 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001719 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001720 Py_FatalError("could not register None for cross-interpreter sharing");
1721 }
1722
Eric Snow6d2cd902018-05-16 15:04:57 -04001723 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001724 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001725 Py_FatalError("could not register int for cross-interpreter sharing");
1726 }
1727
Eric Snow7f8bfc92018-01-29 18:23:44 -07001728 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001729 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001730 Py_FatalError("could not register bytes for cross-interpreter sharing");
1731 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001732
1733 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001734 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001735 Py_FatalError("could not register str for cross-interpreter sharing");
1736 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001737}
1738
1739
Victor Stinner0b72b232020-03-12 23:18:39 +01001740_PyFrameEvalFunction
1741_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1742{
1743 return interp->eval_frame;
1744}
1745
1746
1747void
1748_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1749 _PyFrameEvalFunction eval_frame)
1750{
1751 interp->eval_frame = eval_frame;
1752}
1753
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001754#ifdef __cplusplus
1755}
1756#endif