blob: 621318f4b5a582fe32b478930002f91d460b02ca [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
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001010/* Asynchronously raise an exception in a thread.
1011 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001012 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001013 to call this, or use ctypes. Must be called with the GIL held.
1014 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1015 match any known thread id). Can be called with exc=NULL to clear an
1016 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001017
1018int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001019PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1020{
Victor Stinner09532fe2019-05-10 23:39:09 +02001021 _PyRuntimeState *runtime = &_PyRuntime;
1022 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001023
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 /* Although the GIL is held, a few C API functions can be called
1025 * without the GIL held, and in particular some that create and
1026 * destroy thread and interpreter states. Those can mutate the
1027 * list of thread states we're traversing, so to prevent that we lock
1028 * head_mutex for the duration.
1029 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001030 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001031 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1032 if (tstate->thread_id != id) {
1033 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001035
1036 /* Tricky: we need to decref the current value
1037 * (if any) in tstate->async_exc, but that can in turn
1038 * allow arbitrary Python code to run, including
1039 * perhaps calls to this function. To prevent
1040 * deadlock, we need to release head_mutex before
1041 * the decref.
1042 */
1043 PyObject *old_exc = tstate->async_exc;
1044 Py_XINCREF(exc);
1045 tstate->async_exc = exc;
1046 HEAD_UNLOCK(runtime);
1047
1048 Py_XDECREF(old_exc);
1049 _PyEval_SignalAsyncExc(tstate);
1050 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001052 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001054}
1055
1056
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001057/* Routines for advanced debuggers, requested by David Beazley.
1058 Don't use unless you know what you are doing! */
1059
1060PyInterpreterState *
1061PyInterpreterState_Head(void)
1062{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001063 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001064}
1065
1066PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001067PyInterpreterState_Main(void)
1068{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001069 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001070}
1071
1072PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001073PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001075}
1076
1077PyThreadState *
1078PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001080}
1081
1082PyThreadState *
1083PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001085}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001086
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001087/* The implementation of sys._current_frames(). This is intended to be
1088 called with the GIL held, as it will be when called via
1089 sys._current_frames(). It's possible it would work fine even without
1090 the GIL held, but haven't thought enough about that.
1091*/
1092PyObject *
1093_PyThread_CurrentFrames(void)
1094{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 PyObject *result;
1096 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001097
Steve Dowerb82e17e2019-05-23 08:45:22 -07001098 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1099 return NULL;
1100 }
1101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 result = PyDict_New();
1103 if (result == NULL)
1104 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 /* for i in all interpreters:
1107 * for t in all of i's thread states:
1108 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001109 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 * need to grab head_mutex for the duration.
1111 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001112 _PyRuntimeState *runtime = &_PyRuntime;
1113 HEAD_LOCK(runtime);
1114 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyThreadState *t;
1116 for (t = i->tstate_head; t != NULL; t = t->next) {
1117 PyObject *id;
1118 int stat;
1119 struct _frame *frame = t->frame;
1120 if (frame == NULL)
1121 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001122 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 if (id == NULL)
1124 goto Fail;
1125 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1126 Py_DECREF(id);
1127 if (stat < 0)
1128 goto Fail;
1129 }
1130 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001131 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001133
1134 Fail:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001135 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 Py_DECREF(result);
1137 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001138}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001139
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001140/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001141
1142/* Keep this as a static, as it is not reliable! It can only
1143 ever be compared to the state for the *current* thread.
1144 * If not equal, then it doesn't matter that the actual
1145 value may change immediately after comparison, as it can't
1146 possibly change to the current thread's state.
1147 * If equal, then the current thread holds the lock, so the value can't
1148 change until we yield the lock.
1149*/
1150static int
1151PyThreadState_IsCurrent(PyThreadState *tstate)
1152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001154 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001155 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1156 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001157}
1158
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001159/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001160 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001161*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001162PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001163_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001164{
Victor Stinner8bb32302019-04-24 16:47:40 +02001165 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001166 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001167 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001168
Victor Stinner01b1cc12019-11-20 02:27:56 +01001169 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001170
1171 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001172 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001173 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001174 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001175 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1176 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001177
Victor Stinner8bb32302019-04-24 16:47:40 +02001178 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001179 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001180}
1181
Victor Stinner861d9ab2016-03-16 22:45:24 +01001182PyInterpreterState *
1183_PyGILState_GetInterpreterStateUnsafe(void)
1184{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001185 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001186}
1187
Tim Peters19717fa2004-10-09 17:38:29 +00001188void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001189_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001190{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001191 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001192 PyThread_tss_delete(&gilstate->autoTSSkey);
1193 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001194}
1195
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001196/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001197 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001198 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001199 */
1200void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001201_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001202{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001203 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001204 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001205
1206 PyThread_tss_delete(&gilstate->autoTSSkey);
1207 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001208 Py_FatalError("Could not allocate TSS entry");
1209 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001210
Charles-François Natalia233df82011-11-22 19:49:51 +01001211 /* If the thread had an associated auto thread state, reassociate it with
1212 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001213 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001214 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001215 {
1216 Py_FatalError("Couldn't create autoTSSkey mapping");
1217 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001218}
1219
Michael W. Hudson188d4362005-06-20 16:52:57 +00001220/* When a thread state is created for a thread by some mechanism other than
1221 PyGILState_Ensure, it's important that the GILState machinery knows about
1222 it so it doesn't try to create another thread state for the thread (this is
1223 a better fix for SF bug #1010677 than the first one attempted).
1224*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001225static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001226_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001227{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001228 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001229 threadstate created in Py_Initialize(). Don't do anything for now
1230 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001231 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001233 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001234
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001235 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 The only situation where you can legitimately have more than one
1238 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001239 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001240
Victor Stinner590cebe2013-12-13 11:08:56 +01001241 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1242 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001243
Victor Stinner590cebe2013-12-13 11:08:56 +01001244 The first thread state created for that given OS level thread will
1245 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001247 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1248 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001249 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001250 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001251 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 /* PyGILState_Release must not try to delete this thread state. */
1254 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001255}
1256
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001257/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001258static PyThreadState *
1259_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1260{
1261 if (gilstate->autoInterpreterState == NULL)
1262 return NULL;
1263 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1264}
1265
Tim Peters19717fa2004-10-09 17:38:29 +00001266PyThreadState *
1267PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001268{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001269 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001270}
1271
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001272int
1273PyGILState_Check(void)
1274{
Victor Stinner8a1be612016-03-14 22:07:55 +01001275
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001276 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001277 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001278 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001279
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001280 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1281 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1282 return 1;
1283 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001284
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001285 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1286 if (tstate == NULL) {
1287 return 0;
1288 }
1289
1290 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001291}
1292
Tim Peters19717fa2004-10-09 17:38:29 +00001293PyGILState_STATE
1294PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001295{
Victor Stinner175a7042020-03-10 00:37:48 +01001296 _PyRuntimeState *runtime = &_PyRuntime;
1297 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 /* Note that we do not auto-init Python here - apart from
1300 potential races with 2 threads auto-initializing, pep-311
1301 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001302 called Py_Initialize(). */
1303
1304 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1305 called by Py_Initialize() */
1306 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001307 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001308
Victor Stinner175a7042020-03-10 00:37:48 +01001309 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1310 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001312 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001313 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001314 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001316 }
1317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 /* This is our thread state! We'll need to delete it in the
1319 matching call to PyGILState_Release(). */
1320 tcur->gilstate_counter = 0;
1321 current = 0; /* new thread state is never current */
1322 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001323 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001325 }
1326
1327 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001329 }
1330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /* Update our counter in the thread-state - no need for locks:
1332 - tcur will remain valid as we hold the GIL.
1333 - the counter is safe as we are the only thread "allowed"
1334 to modify this value
1335 */
1336 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001339}
1340
Tim Peters19717fa2004-10-09 17:38:29 +00001341void
1342PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001343{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001344 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001345 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1346 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 Py_FatalError("auto-releasing thread-state, "
1348 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001349 }
1350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 /* We must hold the GIL and have our thread state current */
1352 /* XXX - remove the check - the assert should be fine,
1353 but while this is very new (April 2003), the extra check
1354 by release-only users can't hurt.
1355 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001356 if (!PyThreadState_IsCurrent(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 Py_FatalError("This thread state must be current when releasing");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001358 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001359 assert(PyThreadState_IsCurrent(tstate));
1360 --tstate->gilstate_counter;
1361 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 /* If we're going to destroy this thread-state, we must
1364 * clear it while the GIL is held, as destructors may run.
1365 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001366 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 /* can't have been locked when we created it */
1368 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001369 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 /* Delete the thread-state. Note this releases the GIL too!
1371 * It's vital that the GIL be held here, to avoid shutdown
1372 * races; see bugs 225673 and 1061968 (that nasty bug has a
1373 * habit of coming back).
1374 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001375 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1376 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 }
1378 /* Release the lock if necessary */
1379 else if (oldstate == PyGILState_UNLOCKED)
1380 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001381}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001382
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001383
Eric Snow7f8bfc92018-01-29 18:23:44 -07001384/**************************/
1385/* cross-interpreter data */
1386/**************************/
1387
1388/* cross-interpreter data */
1389
1390crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1391
1392/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1393 to keep the registry code separate. */
1394static crossinterpdatafunc
1395_lookup_getdata(PyObject *obj)
1396{
1397 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1398 if (getdata == NULL && PyErr_Occurred() == 0)
1399 PyErr_Format(PyExc_ValueError,
1400 "%S does not support cross-interpreter data", obj);
1401 return getdata;
1402}
1403
1404int
1405_PyObject_CheckCrossInterpreterData(PyObject *obj)
1406{
1407 crossinterpdatafunc getdata = _lookup_getdata(obj);
1408 if (getdata == NULL) {
1409 return -1;
1410 }
1411 return 0;
1412}
1413
1414static int
1415_check_xidata(_PyCrossInterpreterData *data)
1416{
1417 // data->data can be anything, including NULL, so we don't check it.
1418
1419 // data->obj may be NULL, so we don't check it.
1420
1421 if (data->interp < 0) {
1422 PyErr_SetString(PyExc_SystemError, "missing interp");
1423 return -1;
1424 }
1425
1426 if (data->new_object == NULL) {
1427 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1428 return -1;
1429 }
1430
1431 // data->free may be NULL, so we don't check it.
1432
1433 return 0;
1434}
1435
1436int
1437_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1438{
Victor Stinnerbe793732020-03-13 18:15:33 +01001439 // PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001440 // to check the result for NULL.
Victor Stinnerbe793732020-03-13 18:15:33 +01001441 PyInterpreterState *interp = PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001442
1443 // Reset data before re-populating.
1444 *data = (_PyCrossInterpreterData){0};
1445 data->free = PyMem_RawFree; // Set a default that may be overridden.
1446
1447 // Call the "getdata" func for the object.
1448 Py_INCREF(obj);
1449 crossinterpdatafunc getdata = _lookup_getdata(obj);
1450 if (getdata == NULL) {
1451 Py_DECREF(obj);
1452 return -1;
1453 }
1454 int res = getdata(obj, data);
1455 Py_DECREF(obj);
1456 if (res != 0) {
1457 return -1;
1458 }
1459
1460 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001461 data->interp = interp->id;
1462 if (_check_xidata(data) != 0) {
1463 _PyCrossInterpreterData_Release(data);
1464 return -1;
1465 }
1466
1467 return 0;
1468}
1469
Victor Stinnere225beb2019-06-03 18:14:24 +02001470static void
Eric Snow63799132018-06-01 18:45:20 -06001471_release_xidata(void *arg)
1472{
1473 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1474 if (data->free != NULL) {
1475 data->free(data->data);
1476 }
1477 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001478}
1479
1480static void
1481_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1482 PyInterpreterState *interp,
1483 void (*func)(void *), void *arg)
1484{
1485 /* We would use Py_AddPendingCall() if it weren't specific to the
1486 * main interpreter (see bpo-33608). In the meantime we take a
1487 * naive approach.
1488 */
1489 PyThreadState *save_tstate = NULL;
1490 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1491 // XXX Using the "head" thread isn't strictly correct.
1492 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1493 // XXX Possible GILState issues?
1494 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1495 }
1496
1497 func(arg);
1498
1499 // Switch back.
1500 if (save_tstate != NULL) {
1501 _PyThreadState_Swap(gilstate, save_tstate);
1502 }
Eric Snow63799132018-06-01 18:45:20 -06001503}
1504
Eric Snow7f8bfc92018-01-29 18:23:44 -07001505void
1506_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1507{
1508 if (data->data == NULL && data->obj == NULL) {
1509 // Nothing to release!
1510 return;
1511 }
1512
Victor Stinnere225beb2019-06-03 18:14:24 +02001513 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001514 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1515 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001516 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001517 if (data->free != NULL) {
1518 // XXX Someone leaked some memory...
1519 }
1520 return;
1521 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001522
Eric Snow7f8bfc92018-01-29 18:23:44 -07001523 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001524 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1525 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001526}
1527
1528PyObject *
1529_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1530{
1531 return data->new_object(data);
1532}
1533
1534/* registry of {type -> crossinterpdatafunc} */
1535
1536/* For now we use a global registry of shareable classes. An
1537 alternative would be to add a tp_* slot for a class's
1538 crossinterpdatafunc. It would be simpler and more efficient. */
1539
1540static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001541_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1542 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001543{
1544 // Note that we effectively replace already registered classes
1545 // rather than failing.
1546 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1547 if (newhead == NULL)
1548 return -1;
1549 newhead->cls = cls;
1550 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001551 newhead->next = xidregistry->head;
1552 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001553 return 0;
1554}
1555
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001556static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001557
1558int
Eric Snowc11183c2019-03-15 16:35:46 -06001559_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001560 crossinterpdatafunc getdata)
1561{
1562 if (!PyType_Check(cls)) {
1563 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1564 return -1;
1565 }
1566 if (getdata == NULL) {
1567 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1568 return -1;
1569 }
1570
1571 // Make sure the class isn't ever deallocated.
1572 Py_INCREF((PyObject *)cls);
1573
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001574 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1575 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1576 if (xidregistry->head == NULL) {
1577 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001578 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001579 int res = _register_xidata(xidregistry, cls, getdata);
1580 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001581 return res;
1582}
1583
Eric Snow6d2cd902018-05-16 15:04:57 -04001584/* Cross-interpreter objects are looked up by exact match on the class.
1585 We can reassess this policy when we move from a global registry to a
1586 tp_* slot. */
1587
Eric Snow7f8bfc92018-01-29 18:23:44 -07001588crossinterpdatafunc
1589_PyCrossInterpreterData_Lookup(PyObject *obj)
1590{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001591 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001592 PyObject *cls = PyObject_Type(obj);
1593 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001594 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1595 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001596 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001597 _register_builtins_for_crossinterpreter_data(xidregistry);
1598 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001599 }
1600 for(; cur != NULL; cur = cur->next) {
1601 if (cur->cls == (PyTypeObject *)cls) {
1602 getdata = cur->getdata;
1603 break;
1604 }
1605 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001606 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001607 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001608 return getdata;
1609}
1610
1611/* cross-interpreter data for builtin types */
1612
Eric Snow6d2cd902018-05-16 15:04:57 -04001613struct _shared_bytes_data {
1614 char *bytes;
1615 Py_ssize_t len;
1616};
1617
Eric Snow7f8bfc92018-01-29 18:23:44 -07001618static PyObject *
1619_new_bytes_object(_PyCrossInterpreterData *data)
1620{
Eric Snow6d2cd902018-05-16 15:04:57 -04001621 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1622 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001623}
1624
1625static int
1626_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1627{
Eric Snow6d2cd902018-05-16 15:04:57 -04001628 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1629 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1630 return -1;
1631 }
1632 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001633 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001634 data->obj = obj; // Will be "released" (decref'ed) when data released.
1635 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001636 data->free = PyMem_Free;
1637 return 0;
1638}
1639
1640struct _shared_str_data {
1641 int kind;
1642 const void *buffer;
1643 Py_ssize_t len;
1644};
1645
1646static PyObject *
1647_new_str_object(_PyCrossInterpreterData *data)
1648{
1649 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1650 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1651}
1652
1653static int
1654_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1655{
1656 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1657 shared->kind = PyUnicode_KIND(obj);
1658 shared->buffer = PyUnicode_DATA(obj);
1659 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1660 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001661 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001662 data->obj = obj; // Will be "released" (decref'ed) when data released.
1663 data->new_object = _new_str_object;
1664 data->free = PyMem_Free;
1665 return 0;
1666}
1667
1668static PyObject *
1669_new_long_object(_PyCrossInterpreterData *data)
1670{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001671 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001672}
1673
1674static int
1675_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1676{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001677 /* Note that this means the size of shareable ints is bounded by
1678 * sys.maxsize. Hence on 32-bit architectures that is half the
1679 * size of maximum shareable ints on 64-bit.
1680 */
1681 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001682 if (value == -1 && PyErr_Occurred()) {
1683 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1684 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1685 }
1686 return -1;
1687 }
1688 data->data = (void *)value;
1689 data->obj = NULL;
1690 data->new_object = _new_long_object;
1691 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001692 return 0;
1693}
1694
1695static PyObject *
1696_new_none_object(_PyCrossInterpreterData *data)
1697{
1698 // XXX Singleton refcounts are problematic across interpreters...
1699 Py_INCREF(Py_None);
1700 return Py_None;
1701}
1702
1703static int
1704_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1705{
1706 data->data = NULL;
1707 // data->obj remains NULL
1708 data->new_object = _new_none_object;
1709 data->free = NULL; // There is nothing to free.
1710 return 0;
1711}
1712
1713static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001714_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001715{
1716 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001717 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001718 Py_FatalError("could not register None for cross-interpreter sharing");
1719 }
1720
Eric Snow6d2cd902018-05-16 15:04:57 -04001721 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001722 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001723 Py_FatalError("could not register int for cross-interpreter sharing");
1724 }
1725
Eric Snow7f8bfc92018-01-29 18:23:44 -07001726 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001727 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001728 Py_FatalError("could not register bytes for cross-interpreter sharing");
1729 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001730
1731 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001732 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001733 Py_FatalError("could not register str for cross-interpreter sharing");
1734 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001735}
1736
1737
Victor Stinner0b72b232020-03-12 23:18:39 +01001738_PyFrameEvalFunction
1739_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1740{
1741 return interp->eval_frame;
1742}
1743
1744
1745void
1746_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1747 _PyFrameEvalFunction eval_frame)
1748{
1749 interp->eval_frame = eval_frame;
1750}
1751
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001752#ifdef __cplusplus
1753}
1754#endif