blob: a792cc5622d0414cf650a3ea03683314e9298684 [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 Stinnerfff7bbf2019-11-20 17:34:39 +0100172int
173_Py_IsMainInterpreter(PyThreadState* tstate)
174{
175 return (tstate->interp == tstate->interp->runtime->interpreters.main);
176}
177
Victor Stinner8bb32302019-04-24 16:47:40 +0200178/* Forward declaration */
179static void _PyGILState_NoteThreadState(
180 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000181
Victor Stinner331a6a52019-05-27 16:39:22 +0200182PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600183_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700184{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200185 struct pyinterpreters *interpreters = &runtime->interpreters;
186 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100187
188 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
189 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200190 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100191 /* Force default allocator, since _PyRuntimeState_Fini() must
192 use the same allocator than this function. */
193 PyMemAllocatorEx old_alloc;
194 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
195
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200196 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100197
198 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
199
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200200 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200201 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800202 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600203 }
Victor Stinner5d926472018-03-06 14:31:37 +0100204
Victor Stinner331a6a52019-05-27 16:39:22 +0200205 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700206}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000207
208PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000209PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000210{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700211 if (PySys_Audit("cpython.PyInterpreterState_New", NULL) < 0) {
212 return NULL;
213 }
214
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200215 PyInterpreterState *interp = PyMem_RawMalloc(sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100216 if (interp == NULL) {
217 return NULL;
218 }
219
Eric Snow5be45a62019-03-08 22:47:07 -0700220 memset(interp, 0, sizeof(*interp));
Eric Snow4c6955e2018-02-16 18:53:40 -0700221 interp->id_refcount = -1;
Victor Stinner022be022019-05-22 23:58:50 +0200222
Victor Stinner01b1cc12019-11-20 02:27:56 +0100223 _PyRuntimeState *runtime = &_PyRuntime;
224 interp->runtime = runtime;
225
Victor Stinnerdab84232020-03-17 18:56:44 +0100226 _PyEval_InitState(&interp->ceval);
Victor Stinner72474072019-11-20 12:25:50 +0100227 _PyGC_InitState(&interp->gc);
Victor Stinner8462a492019-10-01 12:06:16 +0200228 PyConfig_InitPythonConfig(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200229
Victor Stinnerd4341102017-11-23 00:12:09 +0100230 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000231#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300232#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100233 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000234#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100235 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000236#endif
237#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000238
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200239 struct pyinterpreters *interpreters = &runtime->interpreters;
240
241 HEAD_LOCK(runtime);
242 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100243 /* overflow or Py_Initialize() not called! */
244 PyErr_SetString(PyExc_RuntimeError,
245 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100246 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100247 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100248 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200249 else {
250 interp->id = interpreters->next_id;
251 interpreters->next_id += 1;
252 interp->next = interpreters->head;
253 if (interpreters->main == NULL) {
254 interpreters->main = interp;
255 }
256 interpreters->head = interp;
257 }
258 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000259
Pablo Galindo95d630e2018-08-31 22:49:29 +0100260 if (interp == NULL) {
261 return NULL;
262 }
263
Yury Selivanovf23746a2018-01-22 19:11:18 -0500264 interp->tstate_next_unique_id = 0;
265
Steve Dowerb82e17e2019-05-23 08:45:22 -0700266 interp->audit_hooks = NULL;
267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000269}
270
271
Victor Stinner01b1cc12019-11-20 02:27:56 +0100272void
273PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000274{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100275 _PyRuntimeState *runtime = interp->runtime;
276
Steve Dowerb82e17e2019-05-23 08:45:22 -0700277 if (PySys_Audit("cpython.PyInterpreterState_Clear", NULL) < 0) {
278 PyErr_Clear();
279 }
280
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200281 HEAD_LOCK(runtime);
282 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200284 }
285 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700286
287 Py_CLEAR(interp->audit_hooks);
288
Victor Stinner331a6a52019-05-27 16:39:22 +0200289 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 Py_CLEAR(interp->codec_search_path);
291 Py_CLEAR(interp->codec_search_cache);
292 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700293 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 Py_CLEAR(interp->sysdict);
296 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200297 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400298 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300299 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600300 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200301#ifdef HAVE_FORK
302 Py_CLEAR(interp->before_forkers);
303 Py_CLEAR(interp->after_forkers_parent);
304 Py_CLEAR(interp->after_forkers_child);
305#endif
Victor Stinner7b3c2522020-03-07 00:24:23 +0100306 if (_PyRuntimeState_GetFinalizing(runtime) == NULL) {
Eric Snow86ea5812019-05-10 13:29:55 -0400307 _PyWarnings_Fini(interp);
308 }
Eric Snow5be45a62019-03-08 22:47:07 -0700309 // XXX Once we have one allocator per interpreter (i.e.
310 // per-interpreter GC) we must ensure that all of the interpreter's
311 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000312}
313
314
315static void
Victor Stinner9da74302019-11-20 11:17:17 +0100316zapthreads(PyInterpreterState *interp, int check_current)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000317{
Victor Stinner9da74302019-11-20 11:17:17 +0100318 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 /* No need to lock the mutex here because this should only happen
320 when the threads are all really dead (XXX famous last words). */
Victor Stinner9da74302019-11-20 11:17:17 +0100321 while ((tstate = interp->tstate_head) != NULL) {
322 _PyThreadState_Delete(tstate, check_current);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000324}
325
326
Victor Stinner01b1cc12019-11-20 02:27:56 +0100327void
328PyInterpreterState_Delete(PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200329{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100330 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200331 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner9da74302019-11-20 11:17:17 +0100332 zapthreads(interp, 0);
333
334 /* Delete current thread. After this, many C API calls become crashy. */
335 _PyThreadState_Swap(&runtime->gilstate, NULL);
336
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200337 HEAD_LOCK(runtime);
338 PyInterpreterState **p;
339 for (p = &interpreters->head; ; p = &(*p)->next) {
340 if (*p == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100341 Py_FatalError("invalid interp");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200342 }
343 if (*p == interp) {
344 break;
345 }
346 }
347 if (interp->tstate_head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100348 Py_FatalError("remaining threads");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200349 }
350 *p = interp->next;
351 if (interpreters->main == interp) {
352 interpreters->main = NULL;
353 if (interpreters->head != NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100354 Py_FatalError("remaining subinterpreters");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200355 }
356 }
357 HEAD_UNLOCK(runtime);
358 if (interp->id_mutex != NULL) {
359 PyThread_free_lock(interp->id_mutex);
360 }
361 PyMem_RawFree(interp);
362}
363
364
Eric Snow59032962018-09-14 14:17:20 -0700365/*
366 * Delete all interpreter states except the main interpreter. If there
367 * is a current interpreter state, it *must* be the main interpreter.
368 */
369void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200370_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700371{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200372 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200373 struct pyinterpreters *interpreters = &runtime->interpreters;
374
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200375 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200376 if (tstate != NULL && tstate->interp != interpreters->main) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100377 Py_FatalError("not main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700378 }
379
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200380 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200381 PyInterpreterState *interp = interpreters->head;
382 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100383 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200384 if (interp == interpreters->main) {
385 interpreters->main->next = NULL;
386 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100387 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700388 continue;
389 }
390
Victor Stinner01b1cc12019-11-20 02:27:56 +0100391 PyInterpreterState_Clear(interp); // XXX must activate?
Victor Stinner9da74302019-11-20 11:17:17 +0100392 zapthreads(interp, 1);
Eric Snow59032962018-09-14 14:17:20 -0700393 if (interp->id_mutex != NULL) {
394 PyThread_free_lock(interp->id_mutex);
395 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100396 PyInterpreterState *prev_interp = interp;
397 interp = interp->next;
398 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700399 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200400 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700401
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200402 if (interpreters->head == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100403 Py_FatalError("missing main");
Eric Snow59032962018-09-14 14:17:20 -0700404 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200405 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700406}
407
408
Victor Stinnercaba55b2018-08-03 15:33:52 +0200409PyInterpreterState *
Victor Stinnerbe793732020-03-13 18:15:33 +0100410PyInterpreterState_Get(void)
Victor Stinnercaba55b2018-08-03 15:33:52 +0200411{
Victor Stinner50b48572018-11-01 01:51:40 +0100412 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner23ef89d2020-03-18 02:26:04 +0100413 ensure_tstate_not_null(__func__, tstate);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200414 PyInterpreterState *interp = tstate->interp;
415 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100416 Py_FatalError("no current interpreter");
Victor Stinnercaba55b2018-08-03 15:33:52 +0200417 }
418 return interp;
419}
420
421
Eric Snowe3774162017-05-22 19:46:40 -0700422int64_t
423PyInterpreterState_GetID(PyInterpreterState *interp)
424{
425 if (interp == NULL) {
426 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
427 return -1;
428 }
429 return interp->id;
430}
431
432
Eric Snow5be45a62019-03-08 22:47:07 -0700433static PyInterpreterState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200434interp_look_up_id(_PyRuntimeState *runtime, PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700435{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200436 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100437 while (interp != NULL) {
438 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700439 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100440 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700441 }
442 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100443 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700444 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100445 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700446 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100447 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700448}
449
Eric Snow5be45a62019-03-08 22:47:07 -0700450PyInterpreterState *
451_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
452{
453 PyInterpreterState *interp = NULL;
454 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200455 _PyRuntimeState *runtime = &_PyRuntime;
456 HEAD_LOCK(runtime);
457 interp = interp_look_up_id(runtime, requested_id);
458 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700459 }
460 if (interp == NULL && !PyErr_Occurred()) {
461 PyErr_Format(PyExc_RuntimeError,
462 "unrecognized interpreter ID %lld", requested_id);
463 }
464 return interp;
465}
466
Eric Snow4c6955e2018-02-16 18:53:40 -0700467
468int
469_PyInterpreterState_IDInitref(PyInterpreterState *interp)
470{
471 if (interp->id_mutex != NULL) {
472 return 0;
473 }
474 interp->id_mutex = PyThread_allocate_lock();
475 if (interp->id_mutex == NULL) {
476 PyErr_SetString(PyExc_RuntimeError,
477 "failed to create init interpreter ID mutex");
478 return -1;
479 }
480 interp->id_refcount = 0;
481 return 0;
482}
483
484
485void
486_PyInterpreterState_IDIncref(PyInterpreterState *interp)
487{
488 if (interp->id_mutex == NULL) {
489 return;
490 }
491 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
492 interp->id_refcount += 1;
493 PyThread_release_lock(interp->id_mutex);
494}
495
496
497void
498_PyInterpreterState_IDDecref(PyInterpreterState *interp)
499{
500 if (interp->id_mutex == NULL) {
501 return;
502 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200503 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700504 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
505 assert(interp->id_refcount != 0);
506 interp->id_refcount -= 1;
507 int64_t refcount = interp->id_refcount;
508 PyThread_release_lock(interp->id_mutex);
509
Eric Snowc11183c2019-03-15 16:35:46 -0600510 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700511 // XXX Using the "head" thread isn't strictly correct.
512 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
513 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200514 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700515 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200516 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700517 }
518}
519
Eric Snowc11183c2019-03-15 16:35:46 -0600520int
521_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
522{
523 return interp->requires_idref;
524}
525
526void
527_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
528{
529 interp->requires_idref = required ? 1 : 0;
530}
531
Eric Snowc11183c2019-03-15 16:35:46 -0600532PyObject *
533_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
534{
535 if (interp->modules == NULL) {
536 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
537 return NULL;
538 }
539 return PyMapping_GetItemString(interp->modules, "__main__");
540}
541
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600542PyObject *
543PyInterpreterState_GetDict(PyInterpreterState *interp)
544{
545 if (interp->dict == NULL) {
546 interp->dict = PyDict_New();
547 if (interp->dict == NULL) {
548 PyErr_Clear();
549 }
550 }
551 /* Returning NULL means no per-interpreter dict is available. */
552 return interp->dict;
553}
554
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000555/* Default implementation for _PyThreadState_GetFrame */
556static struct _frame *
557threadstate_getframe(PyThreadState *self)
558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000560}
561
Victor Stinner45b9be52010-03-03 23:28:07 +0000562static PyThreadState *
563new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000564{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100565 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200566 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200567 if (tstate == NULL) {
568 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000570
Victor Stinner8bb32302019-04-24 16:47:40 +0200571 if (_PyThreadState_GetFrame == NULL) {
572 _PyThreadState_GetFrame = threadstate_getframe;
573 }
574
575 tstate->interp = interp;
576
577 tstate->frame = NULL;
578 tstate->recursion_depth = 0;
579 tstate->overflowed = 0;
580 tstate->recursion_critical = 0;
581 tstate->stackcheck_counter = 0;
582 tstate->tracing = 0;
583 tstate->use_tracing = 0;
584 tstate->gilstate_counter = 0;
585 tstate->async_exc = NULL;
586 tstate->thread_id = PyThread_get_thread_ident();
587
588 tstate->dict = NULL;
589
590 tstate->curexc_type = NULL;
591 tstate->curexc_value = NULL;
592 tstate->curexc_traceback = NULL;
593
594 tstate->exc_state.exc_type = NULL;
595 tstate->exc_state.exc_value = NULL;
596 tstate->exc_state.exc_traceback = NULL;
597 tstate->exc_state.previous_item = NULL;
598 tstate->exc_info = &tstate->exc_state;
599
600 tstate->c_profilefunc = NULL;
601 tstate->c_tracefunc = NULL;
602 tstate->c_profileobj = NULL;
603 tstate->c_traceobj = NULL;
604
605 tstate->trash_delete_nesting = 0;
606 tstate->trash_delete_later = NULL;
607 tstate->on_delete = NULL;
608 tstate->on_delete_data = NULL;
609
610 tstate->coroutine_origin_tracking_depth = 0;
611
Victor Stinner8bb32302019-04-24 16:47:40 +0200612 tstate->async_gen_firstiter = NULL;
613 tstate->async_gen_finalizer = NULL;
614
615 tstate->context = NULL;
616 tstate->context_ver = 1;
617
Victor Stinner8bb32302019-04-24 16:47:40 +0200618 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100619 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200620 }
621
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200622 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100623 tstate->id = ++interp->tstate_next_unique_id;
Victor Stinner8bb32302019-04-24 16:47:40 +0200624 tstate->prev = NULL;
625 tstate->next = interp->tstate_head;
626 if (tstate->next)
627 tstate->next->prev = tstate;
628 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200629 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000632}
633
Victor Stinner45b9be52010-03-03 23:28:07 +0000634PyThreadState *
635PyThreadState_New(PyInterpreterState *interp)
636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000638}
639
640PyThreadState *
641_PyThreadState_Prealloc(PyInterpreterState *interp)
642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000644}
645
646void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100647_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000648{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100649 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000650}
651
Martin v. Löwis1a214512008-06-11 05:26:20 +0000652PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200653PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000654{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200655 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100656 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000658 if (module->m_slots) {
659 return NULL;
660 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 if (index == 0)
662 return NULL;
663 if (state->modules_by_index == NULL)
664 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200665 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 return NULL;
667 res = PyList_GET_ITEM(state->modules_by_index, index);
668 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000669}
670
671int
Victor Stinner82c83bd2019-11-22 18:52:27 +0100672_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000673{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300674 if (!def) {
675 assert(PyErr_Occurred());
676 return -1;
677 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000678 if (def->m_slots) {
679 PyErr_SetString(PyExc_SystemError,
680 "PyState_AddModule called on module with slots");
681 return -1;
682 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100683
684 PyInterpreterState *interp = tstate->interp;
685 if (!interp->modules_by_index) {
686 interp->modules_by_index = PyList_New(0);
687 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100689 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100691
692 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
693 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100695 }
696 }
697
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100699 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000701}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000702
Martin v. Löwis7800f752012-06-22 12:20:55 +0200703int
704PyState_AddModule(PyObject* module, struct PyModuleDef* def)
705{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200706 if (!def) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100707 Py_FatalError("Module Definition is NULL");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200708 return -1;
709 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100710
711 PyThreadState *tstate = _PyThreadState_GET();
712 PyInterpreterState *interp = tstate->interp;
713 Py_ssize_t index = def->m_base.m_index;
714 if (interp->modules_by_index &&
715 index < PyList_GET_SIZE(interp->modules_by_index) &&
716 module == PyList_GET_ITEM(interp->modules_by_index, index))
717 {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100718 Py_FatalError("Module already added");
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100719 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200720 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100721 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200722}
723
724int
725PyState_RemoveModule(struct PyModuleDef* def)
726{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000727 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200728 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000729 if (def->m_slots) {
730 PyErr_SetString(PyExc_SystemError,
731 "PyState_RemoveModule called on module with slots");
732 return -1;
733 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100734 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200735 if (index == 0) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100736 Py_FatalError("Module index invalid");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200737 return -1;
738 }
739 if (state->modules_by_index == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100740 Py_FatalError("Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200741 return -1;
742 }
743 if (index > PyList_GET_SIZE(state->modules_by_index)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100744 Py_FatalError("Module index out of bounds.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200745 return -1;
746 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700747 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200748 return PyList_SetItem(state->modules_by_index, index, Py_None);
749}
750
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200751/* Used by PyImport_Cleanup() */
Antoine Pitrou40322e62013-08-11 00:30:09 +0200752void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200753_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200754{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200755 if (!interp->modules_by_index) {
756 return;
757 }
758
759 Py_ssize_t i;
760 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
761 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
762 if (PyModule_Check(m)) {
763 /* cleanup the saved copy of module dicts */
764 PyModuleDef *md = PyModule_GetDef(m);
765 if (md) {
766 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200767 }
768 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200769 }
770
771 /* Setting modules_by_index to NULL could be dangerous, so we
772 clear the list instead. */
773 if (PyList_SetSlice(interp->modules_by_index,
774 0, PyList_GET_SIZE(interp->modules_by_index),
775 NULL)) {
776 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200777 }
778}
779
Guido van Rossuma027efa1997-05-05 20:56:21 +0000780void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000781PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000782{
Victor Stinner331a6a52019-05-27 16:39:22 +0200783 int verbose = tstate->interp->config.verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200784
785 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 fprintf(stderr,
787 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 Py_CLEAR(tstate->dict);
792 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 Py_CLEAR(tstate->curexc_type);
795 Py_CLEAR(tstate->curexc_value);
796 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000797
Mark Shannonae3087c2017-10-22 22:41:51 +0100798 Py_CLEAR(tstate->exc_state.exc_type);
799 Py_CLEAR(tstate->exc_state.exc_value);
800 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300801
Mark Shannonae3087c2017-10-22 22:41:51 +0100802 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200803 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100804 fprintf(stderr,
805 "PyThreadState_Clear: warning: thread still has a generator\n");
806 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 tstate->c_profilefunc = NULL;
809 tstate->c_tracefunc = NULL;
810 Py_CLEAR(tstate->c_profileobj);
811 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400812
Yury Selivanoveb636452016-09-08 22:01:51 -0700813 Py_CLEAR(tstate->async_gen_firstiter);
814 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500815
816 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100817
818 if (tstate->on_delete != NULL) {
819 tstate->on_delete(tstate->on_delete_data);
820 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000821}
822
823
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300824/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000825static void
Victor Stinner9da74302019-11-20 11:17:17 +0100826tstate_delete_common(PyThreadState *tstate,
827 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000828{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100829 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner23ef89d2020-03-18 02:26:04 +0100830 ensure_tstate_not_null(__func__, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200831 PyInterpreterState *interp = tstate->interp;
832 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100833 Py_FatalError("NULL interp");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200834 }
835 HEAD_LOCK(runtime);
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200836 if (tstate->prev)
837 tstate->prev->next = tstate->next;
838 else
839 interp->tstate_head = tstate->next;
840 if (tstate->next)
841 tstate->next->prev = tstate->prev;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200842 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100843
Victor Stinner9da74302019-11-20 11:17:17 +0100844 if (gilstate->autoInterpreterState &&
845 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
846 {
847 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
848 }
849}
850
851
852static void
853_PyThreadState_Delete(PyThreadState *tstate, int check_current)
854{
855 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
856 if (check_current) {
857 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100858 Py_FatalError("tstate is still current");
Victor Stinner9da74302019-11-20 11:17:17 +0100859 }
860 }
861 tstate_delete_common(tstate, gilstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100862 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000863}
864
865
Victor Stinner01b1cc12019-11-20 02:27:56 +0100866void
867PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000868{
Victor Stinner9da74302019-11-20 11:17:17 +0100869 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200870}
871
872
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300873void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100874_PyThreadState_DeleteCurrent(PyThreadState *tstate)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200875{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100876 ensure_tstate_not_null(__func__, tstate);
877 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner9da74302019-11-20 11:17:17 +0100878 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200879 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100880 _PyEval_ReleaseLock(tstate);
881 PyMem_RawFree(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000882}
Guido van Rossum29757862001-01-23 01:46:06 +0000883
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300884void
885PyThreadState_DeleteCurrent(void)
886{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100887 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
888 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
889 _PyThreadState_DeleteCurrent(tstate);
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300890}
891
Guido van Rossum29757862001-01-23 01:46:06 +0000892
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200893/*
894 * Delete all thread states except the one passed as argument.
895 * Note that, if there is a current thread state, it *must* be the one
896 * passed as argument. Also, this won't touch any other interpreters
897 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000898 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200899 */
900void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200901_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200902{
903 PyInterpreterState *interp = tstate->interp;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100904
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200905 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200906 /* Remove all thread states, except tstate, from the linked list of
907 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200908 without holding the lock. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100909 PyThreadState *list = interp->tstate_head;
910 if (list == tstate) {
911 list = tstate->next;
912 }
913 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200914 tstate->prev->next = tstate->next;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100915 }
916 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200917 tstate->next->prev = tstate->prev;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100918 }
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200919 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200920 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200921 HEAD_UNLOCK(runtime);
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100922
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200923 /* Clear and deallocate all stale thread states. Even if this
924 executes Python code, we should be safe since it executes
925 in the current thread, not one of the stale threads. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100926 PyThreadState *p, *next;
927 for (p = list; p; p = next) {
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200928 next = p->next;
929 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200930 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200931 }
932}
933
934
Guido van Rossuma027efa1997-05-05 20:56:21 +0000935PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100936_PyThreadState_UncheckedGet(void)
937{
Victor Stinner50b48572018-11-01 01:51:40 +0100938 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100939}
940
941
942PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000943PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000944{
Victor Stinner50b48572018-11-01 01:51:40 +0100945 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner23ef89d2020-03-18 02:26:04 +0100946 ensure_tstate_not_null(__func__, tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000948}
949
950
Victor Stinner09532fe2019-05-10 23:39:09 +0200951PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200952_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000953{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200954 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000955
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200956 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 /* It should not be possible for more than one thread state
958 to be used for a thread. Check this the best we can in debug
959 builds.
960 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200961#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 if (newts) {
963 /* This can be called from PyEval_RestoreThread(). Similar
964 to it, we need to ensure errno doesn't change.
965 */
966 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200967 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 if (check && check->interp == newts->interp && check != newts)
969 Py_FatalError("Invalid thread state for this thread");
970 errno = err;
971 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000972#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000974}
Guido van Rossumede04391998-04-10 20:18:25 +0000975
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200976PyThreadState *
977PyThreadState_Swap(PyThreadState *newts)
978{
979 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
980}
981
Guido van Rossumede04391998-04-10 20:18:25 +0000982/* An extension mechanism to store arbitrary additional per-thread state.
983 PyThreadState_GetDict() returns a dictionary that can be used to hold such
984 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000985 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
986 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000987
988PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000989PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000990{
Victor Stinner50b48572018-11-01 01:51:40 +0100991 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 if (tstate == NULL)
993 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 if (tstate->dict == NULL) {
996 PyObject *d;
997 tstate->dict = d = PyDict_New();
998 if (d == NULL)
999 PyErr_Clear();
1000 }
1001 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +00001002}
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001003
1004
Victor Stinner8fb02b62020-03-13 23:38:08 +01001005PyInterpreterState *
1006PyThreadState_GetInterpreter(PyThreadState *tstate)
1007{
1008 assert(tstate != NULL);
1009 if (tstate == NULL) {
1010 return NULL;
1011 }
1012 return tstate->interp;
1013}
1014
1015
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001016/* Asynchronously raise an exception in a thread.
1017 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001018 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001019 to call this, or use ctypes. Must be called with the GIL held.
1020 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1021 match any known thread id). Can be called with exc=NULL to clear an
1022 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001023
1024int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001025PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1026{
Victor Stinner09532fe2019-05-10 23:39:09 +02001027 _PyRuntimeState *runtime = &_PyRuntime;
1028 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 /* Although the GIL is held, a few C API functions can be called
1031 * without the GIL held, and in particular some that create and
1032 * destroy thread and interpreter states. Those can mutate the
1033 * list of thread states we're traversing, so to prevent that we lock
1034 * head_mutex for the duration.
1035 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001036 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001037 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1038 if (tstate->thread_id != id) {
1039 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001041
1042 /* Tricky: we need to decref the current value
1043 * (if any) in tstate->async_exc, but that can in turn
1044 * allow arbitrary Python code to run, including
1045 * perhaps calls to this function. To prevent
1046 * deadlock, we need to release head_mutex before
1047 * the decref.
1048 */
1049 PyObject *old_exc = tstate->async_exc;
1050 Py_XINCREF(exc);
1051 tstate->async_exc = exc;
1052 HEAD_UNLOCK(runtime);
1053
1054 Py_XDECREF(old_exc);
1055 _PyEval_SignalAsyncExc(tstate);
1056 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001058 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001060}
1061
1062
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001063/* Routines for advanced debuggers, requested by David Beazley.
1064 Don't use unless you know what you are doing! */
1065
1066PyInterpreterState *
1067PyInterpreterState_Head(void)
1068{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001069 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001070}
1071
1072PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001073PyInterpreterState_Main(void)
1074{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001075 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001076}
1077
1078PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001079PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001081}
1082
1083PyThreadState *
1084PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001086}
1087
1088PyThreadState *
1089PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001091}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001092
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001093/* The implementation of sys._current_frames(). This is intended to be
1094 called with the GIL held, as it will be when called via
1095 sys._current_frames(). It's possible it would work fine even without
1096 the GIL held, but haven't thought enough about that.
1097*/
1098PyObject *
1099_PyThread_CurrentFrames(void)
1100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 PyObject *result;
1102 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001103
Steve Dowerb82e17e2019-05-23 08:45:22 -07001104 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1105 return NULL;
1106 }
1107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 result = PyDict_New();
1109 if (result == NULL)
1110 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 /* for i in all interpreters:
1113 * for t in all of i's thread states:
1114 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001115 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 * need to grab head_mutex for the duration.
1117 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001118 _PyRuntimeState *runtime = &_PyRuntime;
1119 HEAD_LOCK(runtime);
1120 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 PyThreadState *t;
1122 for (t = i->tstate_head; t != NULL; t = t->next) {
1123 PyObject *id;
1124 int stat;
1125 struct _frame *frame = t->frame;
1126 if (frame == NULL)
1127 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001128 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 if (id == NULL)
1130 goto Fail;
1131 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1132 Py_DECREF(id);
1133 if (stat < 0)
1134 goto Fail;
1135 }
1136 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001137 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001139
1140 Fail:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001141 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 Py_DECREF(result);
1143 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001144}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001145
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001146/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001147
1148/* Keep this as a static, as it is not reliable! It can only
1149 ever be compared to the state for the *current* thread.
1150 * If not equal, then it doesn't matter that the actual
1151 value may change immediately after comparison, as it can't
1152 possibly change to the current thread's state.
1153 * If equal, then the current thread holds the lock, so the value can't
1154 change until we yield the lock.
1155*/
1156static int
1157PyThreadState_IsCurrent(PyThreadState *tstate)
1158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001160 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001161 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1162 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001163}
1164
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001165/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001166 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001167*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001168PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001169_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001170{
Victor Stinner8bb32302019-04-24 16:47:40 +02001171 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001172 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001173 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001174
Victor Stinner01b1cc12019-11-20 02:27:56 +01001175 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001176
1177 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001178 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001179 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001180 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001181 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1182 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001183
Victor Stinner8bb32302019-04-24 16:47:40 +02001184 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001185 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001186}
1187
Victor Stinner861d9ab2016-03-16 22:45:24 +01001188PyInterpreterState *
1189_PyGILState_GetInterpreterStateUnsafe(void)
1190{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001191 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001192}
1193
Tim Peters19717fa2004-10-09 17:38:29 +00001194void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001195_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001196{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001197 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001198 PyThread_tss_delete(&gilstate->autoTSSkey);
1199 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001200}
1201
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001202/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001203 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001204 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001205 */
1206void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001207_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001208{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001209 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001210 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001211
1212 PyThread_tss_delete(&gilstate->autoTSSkey);
1213 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001214 Py_FatalError("Could not allocate TSS entry");
1215 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001216
Charles-François Natalia233df82011-11-22 19:49:51 +01001217 /* If the thread had an associated auto thread state, reassociate it with
1218 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001219 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001220 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001221 {
1222 Py_FatalError("Couldn't create autoTSSkey mapping");
1223 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001224}
1225
Michael W. Hudson188d4362005-06-20 16:52:57 +00001226/* When a thread state is created for a thread by some mechanism other than
1227 PyGILState_Ensure, it's important that the GILState machinery knows about
1228 it so it doesn't try to create another thread state for the thread (this is
1229 a better fix for SF bug #1010677 than the first one attempted).
1230*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001231static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001232_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001233{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001234 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001235 threadstate created in Py_Initialize(). Don't do anything for now
1236 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001237 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001239 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001240
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001241 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 The only situation where you can legitimately have more than one
1244 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001245 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001246
Victor Stinner590cebe2013-12-13 11:08:56 +01001247 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1248 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001249
Victor Stinner590cebe2013-12-13 11:08:56 +01001250 The first thread state created for that given OS level thread will
1251 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001253 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1254 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001255 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001256 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001257 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 /* PyGILState_Release must not try to delete this thread state. */
1260 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001261}
1262
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001263/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001264static PyThreadState *
1265_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1266{
1267 if (gilstate->autoInterpreterState == NULL)
1268 return NULL;
1269 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1270}
1271
Tim Peters19717fa2004-10-09 17:38:29 +00001272PyThreadState *
1273PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001274{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001275 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001276}
1277
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001278int
1279PyGILState_Check(void)
1280{
Victor Stinner8a1be612016-03-14 22:07:55 +01001281
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001282 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001283 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001284 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001285
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001286 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1287 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1288 return 1;
1289 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001290
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001291 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1292 if (tstate == NULL) {
1293 return 0;
1294 }
1295
1296 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001297}
1298
Tim Peters19717fa2004-10-09 17:38:29 +00001299PyGILState_STATE
1300PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001301{
Victor Stinner175a7042020-03-10 00:37:48 +01001302 _PyRuntimeState *runtime = &_PyRuntime;
1303 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 /* Note that we do not auto-init Python here - apart from
1306 potential races with 2 threads auto-initializing, pep-311
1307 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001308 called Py_Initialize(). */
1309
1310 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1311 called by Py_Initialize() */
1312 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001313 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001314
Victor Stinner175a7042020-03-10 00:37:48 +01001315 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1316 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001318 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001319 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001320 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001322 }
1323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 /* This is our thread state! We'll need to delete it in the
1325 matching call to PyGILState_Release(). */
1326 tcur->gilstate_counter = 0;
1327 current = 0; /* new thread state is never current */
1328 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001329 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001331 }
1332
1333 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001335 }
1336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 /* Update our counter in the thread-state - no need for locks:
1338 - tcur will remain valid as we hold the GIL.
1339 - the counter is safe as we are the only thread "allowed"
1340 to modify this value
1341 */
1342 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001345}
1346
Tim Peters19717fa2004-10-09 17:38:29 +00001347void
1348PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001349{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001350 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001351 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1352 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 Py_FatalError("auto-releasing thread-state, "
1354 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001355 }
1356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001357 /* We must hold the GIL and have our thread state current */
1358 /* XXX - remove the check - the assert should be fine,
1359 but while this is very new (April 2003), the extra check
1360 by release-only users can't hurt.
1361 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001362 if (!PyThreadState_IsCurrent(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 Py_FatalError("This thread state must be current when releasing");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001364 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001365 assert(PyThreadState_IsCurrent(tstate));
1366 --tstate->gilstate_counter;
1367 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 /* If we're going to destroy this thread-state, we must
1370 * clear it while the GIL is held, as destructors may run.
1371 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001372 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 /* can't have been locked when we created it */
1374 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001375 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 /* Delete the thread-state. Note this releases the GIL too!
1377 * It's vital that the GIL be held here, to avoid shutdown
1378 * races; see bugs 225673 and 1061968 (that nasty bug has a
1379 * habit of coming back).
1380 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001381 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1382 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 }
1384 /* Release the lock if necessary */
1385 else if (oldstate == PyGILState_UNLOCKED)
1386 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001387}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001388
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001389
Eric Snow7f8bfc92018-01-29 18:23:44 -07001390/**************************/
1391/* cross-interpreter data */
1392/**************************/
1393
1394/* cross-interpreter data */
1395
1396crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1397
1398/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1399 to keep the registry code separate. */
1400static crossinterpdatafunc
1401_lookup_getdata(PyObject *obj)
1402{
1403 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1404 if (getdata == NULL && PyErr_Occurred() == 0)
1405 PyErr_Format(PyExc_ValueError,
1406 "%S does not support cross-interpreter data", obj);
1407 return getdata;
1408}
1409
1410int
1411_PyObject_CheckCrossInterpreterData(PyObject *obj)
1412{
1413 crossinterpdatafunc getdata = _lookup_getdata(obj);
1414 if (getdata == NULL) {
1415 return -1;
1416 }
1417 return 0;
1418}
1419
1420static int
1421_check_xidata(_PyCrossInterpreterData *data)
1422{
1423 // data->data can be anything, including NULL, so we don't check it.
1424
1425 // data->obj may be NULL, so we don't check it.
1426
1427 if (data->interp < 0) {
1428 PyErr_SetString(PyExc_SystemError, "missing interp");
1429 return -1;
1430 }
1431
1432 if (data->new_object == NULL) {
1433 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1434 return -1;
1435 }
1436
1437 // data->free may be NULL, so we don't check it.
1438
1439 return 0;
1440}
1441
1442int
1443_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1444{
Victor Stinnerbe793732020-03-13 18:15:33 +01001445 // PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001446 // to check the result for NULL.
Victor Stinnerbe793732020-03-13 18:15:33 +01001447 PyInterpreterState *interp = PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001448
1449 // Reset data before re-populating.
1450 *data = (_PyCrossInterpreterData){0};
1451 data->free = PyMem_RawFree; // Set a default that may be overridden.
1452
1453 // Call the "getdata" func for the object.
1454 Py_INCREF(obj);
1455 crossinterpdatafunc getdata = _lookup_getdata(obj);
1456 if (getdata == NULL) {
1457 Py_DECREF(obj);
1458 return -1;
1459 }
1460 int res = getdata(obj, data);
1461 Py_DECREF(obj);
1462 if (res != 0) {
1463 return -1;
1464 }
1465
1466 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001467 data->interp = interp->id;
1468 if (_check_xidata(data) != 0) {
1469 _PyCrossInterpreterData_Release(data);
1470 return -1;
1471 }
1472
1473 return 0;
1474}
1475
Victor Stinnere225beb2019-06-03 18:14:24 +02001476static void
Eric Snow63799132018-06-01 18:45:20 -06001477_release_xidata(void *arg)
1478{
1479 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1480 if (data->free != NULL) {
1481 data->free(data->data);
1482 }
1483 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001484}
1485
1486static void
1487_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1488 PyInterpreterState *interp,
1489 void (*func)(void *), void *arg)
1490{
1491 /* We would use Py_AddPendingCall() if it weren't specific to the
1492 * main interpreter (see bpo-33608). In the meantime we take a
1493 * naive approach.
1494 */
1495 PyThreadState *save_tstate = NULL;
1496 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1497 // XXX Using the "head" thread isn't strictly correct.
1498 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1499 // XXX Possible GILState issues?
1500 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1501 }
1502
1503 func(arg);
1504
1505 // Switch back.
1506 if (save_tstate != NULL) {
1507 _PyThreadState_Swap(gilstate, save_tstate);
1508 }
Eric Snow63799132018-06-01 18:45:20 -06001509}
1510
Eric Snow7f8bfc92018-01-29 18:23:44 -07001511void
1512_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1513{
1514 if (data->data == NULL && data->obj == NULL) {
1515 // Nothing to release!
1516 return;
1517 }
1518
Victor Stinnere225beb2019-06-03 18:14:24 +02001519 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001520 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1521 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001522 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001523 if (data->free != NULL) {
1524 // XXX Someone leaked some memory...
1525 }
1526 return;
1527 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001528
Eric Snow7f8bfc92018-01-29 18:23:44 -07001529 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001530 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1531 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001532}
1533
1534PyObject *
1535_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1536{
1537 return data->new_object(data);
1538}
1539
1540/* registry of {type -> crossinterpdatafunc} */
1541
1542/* For now we use a global registry of shareable classes. An
1543 alternative would be to add a tp_* slot for a class's
1544 crossinterpdatafunc. It would be simpler and more efficient. */
1545
1546static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001547_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1548 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001549{
1550 // Note that we effectively replace already registered classes
1551 // rather than failing.
1552 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1553 if (newhead == NULL)
1554 return -1;
1555 newhead->cls = cls;
1556 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001557 newhead->next = xidregistry->head;
1558 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001559 return 0;
1560}
1561
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001562static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001563
1564int
Eric Snowc11183c2019-03-15 16:35:46 -06001565_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001566 crossinterpdatafunc getdata)
1567{
1568 if (!PyType_Check(cls)) {
1569 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1570 return -1;
1571 }
1572 if (getdata == NULL) {
1573 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1574 return -1;
1575 }
1576
1577 // Make sure the class isn't ever deallocated.
1578 Py_INCREF((PyObject *)cls);
1579
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001580 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1581 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1582 if (xidregistry->head == NULL) {
1583 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001584 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001585 int res = _register_xidata(xidregistry, cls, getdata);
1586 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001587 return res;
1588}
1589
Eric Snow6d2cd902018-05-16 15:04:57 -04001590/* Cross-interpreter objects are looked up by exact match on the class.
1591 We can reassess this policy when we move from a global registry to a
1592 tp_* slot. */
1593
Eric Snow7f8bfc92018-01-29 18:23:44 -07001594crossinterpdatafunc
1595_PyCrossInterpreterData_Lookup(PyObject *obj)
1596{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001597 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001598 PyObject *cls = PyObject_Type(obj);
1599 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001600 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1601 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001602 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001603 _register_builtins_for_crossinterpreter_data(xidregistry);
1604 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001605 }
1606 for(; cur != NULL; cur = cur->next) {
1607 if (cur->cls == (PyTypeObject *)cls) {
1608 getdata = cur->getdata;
1609 break;
1610 }
1611 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001612 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001613 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001614 return getdata;
1615}
1616
1617/* cross-interpreter data for builtin types */
1618
Eric Snow6d2cd902018-05-16 15:04:57 -04001619struct _shared_bytes_data {
1620 char *bytes;
1621 Py_ssize_t len;
1622};
1623
Eric Snow7f8bfc92018-01-29 18:23:44 -07001624static PyObject *
1625_new_bytes_object(_PyCrossInterpreterData *data)
1626{
Eric Snow6d2cd902018-05-16 15:04:57 -04001627 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1628 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001629}
1630
1631static int
1632_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1633{
Eric Snow6d2cd902018-05-16 15:04:57 -04001634 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1635 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1636 return -1;
1637 }
1638 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001639 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001640 data->obj = obj; // Will be "released" (decref'ed) when data released.
1641 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001642 data->free = PyMem_Free;
1643 return 0;
1644}
1645
1646struct _shared_str_data {
1647 int kind;
1648 const void *buffer;
1649 Py_ssize_t len;
1650};
1651
1652static PyObject *
1653_new_str_object(_PyCrossInterpreterData *data)
1654{
1655 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1656 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1657}
1658
1659static int
1660_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1661{
1662 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1663 shared->kind = PyUnicode_KIND(obj);
1664 shared->buffer = PyUnicode_DATA(obj);
1665 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1666 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001667 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001668 data->obj = obj; // Will be "released" (decref'ed) when data released.
1669 data->new_object = _new_str_object;
1670 data->free = PyMem_Free;
1671 return 0;
1672}
1673
1674static PyObject *
1675_new_long_object(_PyCrossInterpreterData *data)
1676{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001677 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001678}
1679
1680static int
1681_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1682{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001683 /* Note that this means the size of shareable ints is bounded by
1684 * sys.maxsize. Hence on 32-bit architectures that is half the
1685 * size of maximum shareable ints on 64-bit.
1686 */
1687 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001688 if (value == -1 && PyErr_Occurred()) {
1689 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1690 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1691 }
1692 return -1;
1693 }
1694 data->data = (void *)value;
1695 data->obj = NULL;
1696 data->new_object = _new_long_object;
1697 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001698 return 0;
1699}
1700
1701static PyObject *
1702_new_none_object(_PyCrossInterpreterData *data)
1703{
1704 // XXX Singleton refcounts are problematic across interpreters...
1705 Py_INCREF(Py_None);
1706 return Py_None;
1707}
1708
1709static int
1710_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1711{
1712 data->data = NULL;
1713 // data->obj remains NULL
1714 data->new_object = _new_none_object;
1715 data->free = NULL; // There is nothing to free.
1716 return 0;
1717}
1718
1719static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001720_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001721{
1722 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001723 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001724 Py_FatalError("could not register None for cross-interpreter sharing");
1725 }
1726
Eric Snow6d2cd902018-05-16 15:04:57 -04001727 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001728 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001729 Py_FatalError("could not register int for cross-interpreter sharing");
1730 }
1731
Eric Snow7f8bfc92018-01-29 18:23:44 -07001732 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001733 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001734 Py_FatalError("could not register bytes for cross-interpreter sharing");
1735 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001736
1737 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001738 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001739 Py_FatalError("could not register str for cross-interpreter sharing");
1740 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001741}
1742
1743
Victor Stinner0b72b232020-03-12 23:18:39 +01001744_PyFrameEvalFunction
1745_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1746{
1747 return interp->eval_frame;
1748}
1749
1750
1751void
1752_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1753 _PyFrameEvalFunction eval_frame)
1754{
1755 interp->eval_frame = eval_frame;
1756}
1757
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001758#ifdef __cplusplus
1759}
1760#endif