blob: 246665b2810b59ab8c3190890387588ec471bbef [file] [log] [blame]
Guido van Rossuma027efa1997-05-05 20:56:21 +00001
2/* Thread and interpreter state structures and their interfaces */
3
4#include "Python.h"
Victor Stinner09532fe2019-05-10 23:39:09 +02005#include "pycore_ceval.h"
Victor Stinner331a6a52019-05-27 16:39:22 +02006#include "pycore_initconfig.h"
Victor Stinner0e427c62020-03-25 21:22:55 +01007#include "pycore_pyerrors.h"
8#include "pycore_pylifecycle.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01009#include "pycore_pymem.h"
10#include "pycore_pystate.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +000011
Tim Peters84705582004-10-10 02:47:33 +000012/* --------------------------------------------------------------------------
13CAUTION
14
Victor Stinner1a7425f2013-07-07 16:25:15 +020015Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
16number of these functions are advertised as safe to call when the GIL isn't
17held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
18debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
19to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000020-------------------------------------------------------------------------- */
21
Martin v. Löwisf0473d52001-07-18 16:17:16 +000022#ifdef HAVE_DLOPEN
23#ifdef HAVE_DLFCN_H
24#include <dlfcn.h>
25#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030026#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000027#define RTLD_LAZY 1
28#endif
29#endif
30
Benjamin Peterson43162b82012-04-13 11:58:27 -040031#ifdef __cplusplus
32extern "C" {
33#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000034
Victor Stinner10c8e6a2019-04-26 01:53:18 +020035#define _PyRuntimeGILState_GetThreadState(gilstate) \
36 ((PyThreadState*)_Py_atomic_load_relaxed(&(gilstate)->tstate_current))
37#define _PyRuntimeGILState_SetThreadState(gilstate, value) \
38 _Py_atomic_store_relaxed(&(gilstate)->tstate_current, \
39 (uintptr_t)(value))
40
Victor Stinner23ef89d2020-03-18 02:26:04 +010041static void
42ensure_tstate_not_null(const char *func, PyThreadState *tstate)
43{
44 if (tstate == NULL) {
45 _Py_FatalErrorFunc(func,
46 "current thread state is NULL (released GIL?)");
47 }
48}
49
50
Victor Stinner10c8e6a2019-04-26 01:53:18 +020051/* Forward declarations */
52static PyThreadState *_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate);
Victor Stinner9da74302019-11-20 11:17:17 +010053static void _PyThreadState_Delete(PyThreadState *tstate, int check_current);
Victor Stinner10c8e6a2019-04-26 01:53:18 +020054
55
Victor Stinner331a6a52019-05-27 16:39:22 +020056static PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010057_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060058{
Steve Dowerb82e17e2019-05-23 08:45:22 -070059 /* We preserve the hook across init, because there is
60 currently no public API to set it between runtime
61 initialization and interpreter initialization. */
62 void *open_code_hook = runtime->open_code_hook;
63 void *open_code_userdata = runtime->open_code_userdata;
64 _Py_AuditHookEntry *audit_hook_head = runtime->audit_hook_head;
65
Eric Snow2ebc5ce2017-09-07 23:51:28 -060066 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010067
Steve Dowerb82e17e2019-05-23 08:45:22 -070068 runtime->open_code_hook = open_code_hook;
69 runtime->open_code_userdata = open_code_userdata;
70 runtime->audit_hook_head = audit_hook_head;
71
Victor Stinnerdab84232020-03-17 18:56:44 +010072 _PyEval_InitRuntimeState(&runtime->ceval);
Victor Stinner441b10c2019-09-28 04:28:35 +020073
Victor Stinner3c30a762019-10-01 10:56:37 +020074 PyPreConfig_InitPythonConfig(&runtime->preconfig);
Michael W. Hudson188d4362005-06-20 16:52:57 +000075
Eric Snow2ebc5ce2017-09-07 23:51:28 -060076 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080077
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090078 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
79 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080080 Py_tss_t initial = Py_tss_NEEDS_INIT;
81 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000082
Eric Snow2ebc5ce2017-09-07 23:51:28 -060083 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080084 if (runtime->interpreters.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020085 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080086 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060087 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070088
89 runtime->xidregistry.mutex = PyThread_allocate_lock();
90 if (runtime->xidregistry.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020091 return _PyStatus_ERR("Can't initialize threads for cross-interpreter data registry");
Eric Snow7f8bfc92018-01-29 18:23:44 -070092 }
93
Eric Snow8479a342019-03-08 23:44:33 -070094 // Set it to the ID of the main thread of the main interpreter.
95 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070096
Victor Stinner331a6a52019-05-27 16:39:22 +020097 return _PyStatus_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060098}
Eric Snow05351c12017-09-05 21:43:08 -070099
Victor Stinner331a6a52019-05-27 16:39:22 +0200100PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +0100101_PyRuntimeState_Init(_PyRuntimeState *runtime)
102{
103 /* Force default allocator, since _PyRuntimeState_Fini() must
104 use the same allocator than this function. */
105 PyMemAllocatorEx old_alloc;
106 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
107
Victor Stinner331a6a52019-05-27 16:39:22 +0200108 PyStatus status = _PyRuntimeState_Init_impl(runtime);
Victor Stinner5d39e042017-11-29 17:20:38 +0100109
110 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinner331a6a52019-05-27 16:39:22 +0200111 return status;
Victor Stinner5d39e042017-11-29 17:20:38 +0100112}
113
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600114void
115_PyRuntimeState_Fini(_PyRuntimeState *runtime)
116{
Victor Stinner5d39e042017-11-29 17:20:38 +0100117 /* Force the allocator used by _PyRuntimeState_Init(). */
118 PyMemAllocatorEx old_alloc;
119 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -0800120
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600121 if (runtime->interpreters.mutex != NULL) {
122 PyThread_free_lock(runtime->interpreters.mutex);
123 runtime->interpreters.mutex = NULL;
124 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800125
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100126 if (runtime->xidregistry.mutex != NULL) {
127 PyThread_free_lock(runtime->xidregistry.mutex);
128 runtime->xidregistry.mutex = NULL;
129 }
130
Victor Stinnerccb04422017-11-16 03:20:31 -0800131 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600132}
133
Eric Snow8479a342019-03-08 23:44:33 -0700134/* This function is called from PyOS_AfterFork_Child to ensure that
135 * newly created child processes do not share locks with the parent.
136 */
137
138void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200139_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700140{
141 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200142 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700143
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200144 /* Force default allocator, since _PyRuntimeState_Fini() must
145 use the same allocator than this function. */
146 PyMemAllocatorEx old_alloc;
147 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
148
149 runtime->interpreters.mutex = PyThread_allocate_lock();
150 runtime->interpreters.main->id_mutex = PyThread_allocate_lock();
151 runtime->xidregistry.mutex = PyThread_allocate_lock();
152
153 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
154
155 if (runtime->interpreters.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700156 Py_FatalError("Can't initialize lock for runtime interpreters");
157 }
158
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200159 if (runtime->interpreters.main->id_mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700160 Py_FatalError("Can't initialize ID lock for main interpreter");
161 }
162
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200163 if (runtime->xidregistry.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700164 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
165 }
166}
167
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200168#define HEAD_LOCK(runtime) \
169 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
170#define HEAD_UNLOCK(runtime) \
171 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700172
Victor Stinner8bb32302019-04-24 16:47:40 +0200173/* Forward declaration */
174static void _PyGILState_NoteThreadState(
175 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000176
Victor Stinner331a6a52019-05-27 16:39:22 +0200177PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600178_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700179{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200180 struct pyinterpreters *interpreters = &runtime->interpreters;
181 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100182
183 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
184 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200185 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100186 /* Force default allocator, since _PyRuntimeState_Fini() must
187 use the same allocator than this function. */
188 PyMemAllocatorEx old_alloc;
189 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
190
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200191 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100192
193 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
194
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200195 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200196 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800197 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600198 }
Victor Stinner5d926472018-03-06 14:31:37 +0100199
Victor Stinner331a6a52019-05-27 16:39:22 +0200200 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700201}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000202
203PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000204PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000205{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700206 if (PySys_Audit("cpython.PyInterpreterState_New", NULL) < 0) {
207 return NULL;
208 }
209
Andy Lester7668a8b2020-03-24 23:26:44 -0500210 PyInterpreterState *interp = PyMem_RawCalloc(1, sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100211 if (interp == NULL) {
212 return NULL;
213 }
214
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 Stinner87d3b9d2020-03-25 19:27:36 +0100335 Py_FatalError("NULL interpreter");
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 Stinner87d3b9d2020-03-25 19:27:36 +0100397 Py_FatalError("missing main interpreter");
Eric Snow59032962018-09-14 14:17:20 -0700398 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200399 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700400}
401
402
Victor Stinnercaba55b2018-08-03 15:33:52 +0200403PyInterpreterState *
Victor Stinnerbe793732020-03-13 18:15:33 +0100404PyInterpreterState_Get(void)
Victor Stinnercaba55b2018-08-03 15:33:52 +0200405{
Victor Stinner50b48572018-11-01 01:51:40 +0100406 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner23ef89d2020-03-18 02:26:04 +0100407 ensure_tstate_not_null(__func__, tstate);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200408 PyInterpreterState *interp = tstate->interp;
409 if (interp == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100410 Py_FatalError("no current interpreter");
Victor Stinnercaba55b2018-08-03 15:33:52 +0200411 }
412 return interp;
413}
414
415
Eric Snowe3774162017-05-22 19:46:40 -0700416int64_t
417PyInterpreterState_GetID(PyInterpreterState *interp)
418{
419 if (interp == NULL) {
420 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
421 return -1;
422 }
423 return interp->id;
424}
425
426
Eric Snow5be45a62019-03-08 22:47:07 -0700427static PyInterpreterState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200428interp_look_up_id(_PyRuntimeState *runtime, PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700429{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200430 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100431 while (interp != NULL) {
432 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700433 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100434 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700435 }
436 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100437 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700438 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100439 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700440 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100441 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700442}
443
Eric Snow5be45a62019-03-08 22:47:07 -0700444PyInterpreterState *
445_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
446{
447 PyInterpreterState *interp = NULL;
448 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200449 _PyRuntimeState *runtime = &_PyRuntime;
450 HEAD_LOCK(runtime);
451 interp = interp_look_up_id(runtime, requested_id);
452 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700453 }
454 if (interp == NULL && !PyErr_Occurred()) {
455 PyErr_Format(PyExc_RuntimeError,
456 "unrecognized interpreter ID %lld", requested_id);
457 }
458 return interp;
459}
460
Eric Snow4c6955e2018-02-16 18:53:40 -0700461
462int
463_PyInterpreterState_IDInitref(PyInterpreterState *interp)
464{
465 if (interp->id_mutex != NULL) {
466 return 0;
467 }
468 interp->id_mutex = PyThread_allocate_lock();
469 if (interp->id_mutex == NULL) {
470 PyErr_SetString(PyExc_RuntimeError,
471 "failed to create init interpreter ID mutex");
472 return -1;
473 }
474 interp->id_refcount = 0;
475 return 0;
476}
477
478
479void
480_PyInterpreterState_IDIncref(PyInterpreterState *interp)
481{
482 if (interp->id_mutex == NULL) {
483 return;
484 }
485 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
486 interp->id_refcount += 1;
487 PyThread_release_lock(interp->id_mutex);
488}
489
490
491void
492_PyInterpreterState_IDDecref(PyInterpreterState *interp)
493{
494 if (interp->id_mutex == NULL) {
495 return;
496 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200497 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700498 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
499 assert(interp->id_refcount != 0);
500 interp->id_refcount -= 1;
501 int64_t refcount = interp->id_refcount;
502 PyThread_release_lock(interp->id_mutex);
503
Eric Snowc11183c2019-03-15 16:35:46 -0600504 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700505 // XXX Using the "head" thread isn't strictly correct.
506 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
507 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200508 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700509 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200510 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700511 }
512}
513
Eric Snowc11183c2019-03-15 16:35:46 -0600514int
515_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
516{
517 return interp->requires_idref;
518}
519
520void
521_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
522{
523 interp->requires_idref = required ? 1 : 0;
524}
525
Eric Snowc11183c2019-03-15 16:35:46 -0600526PyObject *
527_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
528{
529 if (interp->modules == NULL) {
530 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
531 return NULL;
532 }
533 return PyMapping_GetItemString(interp->modules, "__main__");
534}
535
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600536PyObject *
537PyInterpreterState_GetDict(PyInterpreterState *interp)
538{
539 if (interp->dict == NULL) {
540 interp->dict = PyDict_New();
541 if (interp->dict == NULL) {
542 PyErr_Clear();
543 }
544 }
545 /* Returning NULL means no per-interpreter dict is available. */
546 return interp->dict;
547}
548
Victor Stinner45b9be52010-03-03 23:28:07 +0000549static PyThreadState *
550new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000551{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100552 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200553 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200554 if (tstate == NULL) {
555 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000557
Victor Stinner8bb32302019-04-24 16:47:40 +0200558 tstate->interp = interp;
559
560 tstate->frame = NULL;
561 tstate->recursion_depth = 0;
562 tstate->overflowed = 0;
563 tstate->recursion_critical = 0;
564 tstate->stackcheck_counter = 0;
565 tstate->tracing = 0;
566 tstate->use_tracing = 0;
567 tstate->gilstate_counter = 0;
568 tstate->async_exc = NULL;
569 tstate->thread_id = PyThread_get_thread_ident();
570
571 tstate->dict = NULL;
572
573 tstate->curexc_type = NULL;
574 tstate->curexc_value = NULL;
575 tstate->curexc_traceback = NULL;
576
577 tstate->exc_state.exc_type = NULL;
578 tstate->exc_state.exc_value = NULL;
579 tstate->exc_state.exc_traceback = NULL;
580 tstate->exc_state.previous_item = NULL;
581 tstate->exc_info = &tstate->exc_state;
582
583 tstate->c_profilefunc = NULL;
584 tstate->c_tracefunc = NULL;
585 tstate->c_profileobj = NULL;
586 tstate->c_traceobj = NULL;
587
588 tstate->trash_delete_nesting = 0;
589 tstate->trash_delete_later = NULL;
590 tstate->on_delete = NULL;
591 tstate->on_delete_data = NULL;
592
593 tstate->coroutine_origin_tracking_depth = 0;
594
Victor Stinner8bb32302019-04-24 16:47:40 +0200595 tstate->async_gen_firstiter = NULL;
596 tstate->async_gen_finalizer = NULL;
597
598 tstate->context = NULL;
599 tstate->context_ver = 1;
600
Victor Stinner8bb32302019-04-24 16:47:40 +0200601 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100602 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200603 }
604
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200605 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100606 tstate->id = ++interp->tstate_next_unique_id;
Victor Stinner8bb32302019-04-24 16:47:40 +0200607 tstate->prev = NULL;
608 tstate->next = interp->tstate_head;
609 if (tstate->next)
610 tstate->next->prev = tstate;
611 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200612 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000615}
616
Victor Stinner45b9be52010-03-03 23:28:07 +0000617PyThreadState *
618PyThreadState_New(PyInterpreterState *interp)
619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000621}
622
623PyThreadState *
624_PyThreadState_Prealloc(PyInterpreterState *interp)
625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000627}
628
629void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100630_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000631{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100632 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000633}
634
Martin v. Löwis1a214512008-06-11 05:26:20 +0000635PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200636PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000637{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200638 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100639 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000641 if (module->m_slots) {
642 return NULL;
643 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if (index == 0)
645 return NULL;
646 if (state->modules_by_index == NULL)
647 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200648 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 return NULL;
650 res = PyList_GET_ITEM(state->modules_by_index, index);
651 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000652}
653
654int
Victor Stinner82c83bd2019-11-22 18:52:27 +0100655_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000656{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300657 if (!def) {
658 assert(PyErr_Occurred());
659 return -1;
660 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000661 if (def->m_slots) {
662 PyErr_SetString(PyExc_SystemError,
663 "PyState_AddModule called on module with slots");
664 return -1;
665 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100666
667 PyInterpreterState *interp = tstate->interp;
668 if (!interp->modules_by_index) {
669 interp->modules_by_index = PyList_New(0);
670 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100672 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100674
675 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
676 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100678 }
679 }
680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100682 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000684}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000685
Martin v. Löwis7800f752012-06-22 12:20:55 +0200686int
687PyState_AddModule(PyObject* module, struct PyModuleDef* def)
688{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200689 if (!def) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100690 Py_FatalError("module definition is NULL");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200691 return -1;
692 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100693
694 PyThreadState *tstate = _PyThreadState_GET();
695 PyInterpreterState *interp = tstate->interp;
696 Py_ssize_t index = def->m_base.m_index;
697 if (interp->modules_by_index &&
698 index < PyList_GET_SIZE(interp->modules_by_index) &&
699 module == PyList_GET_ITEM(interp->modules_by_index, index))
700 {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100701 _Py_FatalErrorFormat(__func__, "module %p already added", module);
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100702 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200703 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100704 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200705}
706
707int
708PyState_RemoveModule(struct PyModuleDef* def)
709{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000710 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200711 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000712 if (def->m_slots) {
713 PyErr_SetString(PyExc_SystemError,
714 "PyState_RemoveModule called on module with slots");
715 return -1;
716 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100717 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200718 if (index == 0) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100719 Py_FatalError("invalid module index");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200720 return -1;
721 }
722 if (state->modules_by_index == NULL) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100723 Py_FatalError("Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200724 return -1;
725 }
726 if (index > PyList_GET_SIZE(state->modules_by_index)) {
Victor Stinner9e5d30c2020-03-07 00:54:20 +0100727 Py_FatalError("Module index out of bounds.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200728 return -1;
729 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700730 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200731 return PyList_SetItem(state->modules_by_index, index, Py_None);
732}
733
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200734/* Used by PyImport_Cleanup() */
Antoine Pitrou40322e62013-08-11 00:30:09 +0200735void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200736_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200737{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200738 if (!interp->modules_by_index) {
739 return;
740 }
741
742 Py_ssize_t i;
743 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
744 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
745 if (PyModule_Check(m)) {
746 /* cleanup the saved copy of module dicts */
747 PyModuleDef *md = PyModule_GetDef(m);
748 if (md) {
749 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200750 }
751 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200752 }
753
754 /* Setting modules_by_index to NULL could be dangerous, so we
755 clear the list instead. */
756 if (PyList_SetSlice(interp->modules_by_index,
757 0, PyList_GET_SIZE(interp->modules_by_index),
758 NULL)) {
759 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200760 }
761}
762
Guido van Rossuma027efa1997-05-05 20:56:21 +0000763void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000764PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000765{
Victor Stinner331a6a52019-05-27 16:39:22 +0200766 int verbose = tstate->interp->config.verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200767
Victor Stinner5804f872020-03-24 16:32:26 +0100768 if (verbose && tstate->frame != NULL) {
769 /* bpo-20526: After the main thread calls
770 _PyRuntimeState_SetFinalizing() in Py_FinalizeEx(), threads must
771 exit when trying to take the GIL. If a thread exit in the middle of
772 _PyEval_EvalFrameDefault(), tstate->frame is not reset to its
773 previous value. It is more likely with daemon threads, but it can
774 happen with regular threads if threading._shutdown() fails
775 (ex: interrupted by CTRL+C). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 fprintf(stderr,
777 "PyThreadState_Clear: warning: thread still has a frame\n");
Victor Stinner5804f872020-03-24 16:32:26 +0100778 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000779
Victor Stinner5804f872020-03-24 16:32:26 +0100780 /* Don't clear tstate->frame: it is a borrowed reference */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 Py_CLEAR(tstate->dict);
783 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 Py_CLEAR(tstate->curexc_type);
786 Py_CLEAR(tstate->curexc_value);
787 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000788
Mark Shannonae3087c2017-10-22 22:41:51 +0100789 Py_CLEAR(tstate->exc_state.exc_type);
790 Py_CLEAR(tstate->exc_state.exc_value);
791 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300792
Mark Shannonae3087c2017-10-22 22:41:51 +0100793 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200794 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100795 fprintf(stderr,
796 "PyThreadState_Clear: warning: thread still has a generator\n");
797 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 tstate->c_profilefunc = NULL;
800 tstate->c_tracefunc = NULL;
801 Py_CLEAR(tstate->c_profileobj);
802 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400803
Yury Selivanoveb636452016-09-08 22:01:51 -0700804 Py_CLEAR(tstate->async_gen_firstiter);
805 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500806
807 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100808
809 if (tstate->on_delete != NULL) {
810 tstate->on_delete(tstate->on_delete_data);
811 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000812}
813
814
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300815/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000816static void
Victor Stinner9da74302019-11-20 11:17:17 +0100817tstate_delete_common(PyThreadState *tstate,
818 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000819{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100820 ensure_tstate_not_null(__func__, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200821 PyInterpreterState *interp = tstate->interp;
822 if (interp == NULL) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100823 Py_FatalError("NULL interpreter");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200824 }
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100825 _PyRuntimeState *runtime = interp->runtime;
826
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200827 HEAD_LOCK(runtime);
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100828 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200829 tstate->prev->next = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100830 }
831 else {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200832 interp->tstate_head = tstate->next;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100833 }
834 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200835 tstate->next->prev = tstate->prev;
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100836 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200837 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100838
Victor Stinner9da74302019-11-20 11:17:17 +0100839 if (gilstate->autoInterpreterState &&
840 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
841 {
842 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
843 }
844}
845
846
847static void
848_PyThreadState_Delete(PyThreadState *tstate, int check_current)
849{
850 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
851 if (check_current) {
852 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +0100853 _Py_FatalErrorFormat(__func__, "tstate %p is still current", tstate);
Victor Stinner9da74302019-11-20 11:17:17 +0100854 }
855 }
856 tstate_delete_common(tstate, gilstate);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100857 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000858}
859
860
Victor Stinner01b1cc12019-11-20 02:27:56 +0100861void
862PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000863{
Victor Stinner9da74302019-11-20 11:17:17 +0100864 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200865}
866
867
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300868void
Victor Stinner23ef89d2020-03-18 02:26:04 +0100869_PyThreadState_DeleteCurrent(PyThreadState *tstate)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200870{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100871 ensure_tstate_not_null(__func__, tstate);
872 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner9da74302019-11-20 11:17:17 +0100873 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200874 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Victor Stinner23ef89d2020-03-18 02:26:04 +0100875 _PyEval_ReleaseLock(tstate);
876 PyMem_RawFree(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000877}
Guido van Rossum29757862001-01-23 01:46:06 +0000878
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300879void
880PyThreadState_DeleteCurrent(void)
881{
Victor Stinner23ef89d2020-03-18 02:26:04 +0100882 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
883 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
884 _PyThreadState_DeleteCurrent(tstate);
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300885}
886
Guido van Rossum29757862001-01-23 01:46:06 +0000887
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200888/*
889 * Delete all thread states except the one passed as argument.
890 * Note that, if there is a current thread state, it *must* be the one
891 * passed as argument. Also, this won't touch any other interpreters
892 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000893 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200894 */
895void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200896_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200897{
898 PyInterpreterState *interp = tstate->interp;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100899
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200900 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200901 /* Remove all thread states, except tstate, from the linked list of
902 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200903 without holding the lock. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100904 PyThreadState *list = interp->tstate_head;
905 if (list == tstate) {
906 list = tstate->next;
907 }
908 if (tstate->prev) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200909 tstate->prev->next = tstate->next;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100910 }
911 if (tstate->next) {
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200912 tstate->next->prev = tstate->prev;
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100913 }
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200914 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200915 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200916 HEAD_UNLOCK(runtime);
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100917
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200918 /* Clear and deallocate all stale thread states. Even if this
919 executes Python code, we should be safe since it executes
920 in the current thread, not one of the stale threads. */
Victor Stinner9ad58ac2020-03-09 23:37:49 +0100921 PyThreadState *p, *next;
922 for (p = list; p; p = next) {
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200923 next = p->next;
924 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200925 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200926 }
927}
928
929
Guido van Rossuma027efa1997-05-05 20:56:21 +0000930PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100931_PyThreadState_UncheckedGet(void)
932{
Victor Stinner50b48572018-11-01 01:51:40 +0100933 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100934}
935
936
937PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000938PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000939{
Victor Stinner50b48572018-11-01 01:51:40 +0100940 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner23ef89d2020-03-18 02:26:04 +0100941 ensure_tstate_not_null(__func__, tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000943}
944
945
Victor Stinner09532fe2019-05-10 23:39:09 +0200946PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200947_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000948{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200949 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000950
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200951 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 /* It should not be possible for more than one thread state
953 to be used for a thread. Check this the best we can in debug
954 builds.
955 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200956#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 if (newts) {
958 /* This can be called from PyEval_RestoreThread(). Similar
959 to it, we need to ensure errno doesn't change.
960 */
961 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200962 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 if (check && check->interp == newts->interp && check != newts)
964 Py_FatalError("Invalid thread state for this thread");
965 errno = err;
966 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000967#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000969}
Guido van Rossumede04391998-04-10 20:18:25 +0000970
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200971PyThreadState *
972PyThreadState_Swap(PyThreadState *newts)
973{
974 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
975}
976
Guido van Rossumede04391998-04-10 20:18:25 +0000977/* An extension mechanism to store arbitrary additional per-thread state.
978 PyThreadState_GetDict() returns a dictionary that can be used to hold such
979 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000980 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
981 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000982
983PyObject *
Victor Stinner0e427c62020-03-25 21:22:55 +0100984_PyThreadState_GetDict(PyThreadState *tstate)
985{
986 assert(tstate != NULL);
987 if (tstate->dict == NULL) {
988 tstate->dict = PyDict_New();
989 if (tstate->dict == NULL) {
990 _PyErr_Clear(tstate);
991 }
992 }
993 return tstate->dict;
994}
995
996
997PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000998PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000999{
Victor Stinner50b48572018-11-01 01:51:40 +01001000 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner0e427c62020-03-25 21:22:55 +01001001 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 }
Victor Stinner0e427c62020-03-25 21:22:55 +01001004 return _PyThreadState_GetDict(tstate);
Guido van Rossumede04391998-04-10 20:18:25 +00001005}
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001006
1007
Victor Stinner8fb02b62020-03-13 23:38:08 +01001008PyInterpreterState *
1009PyThreadState_GetInterpreter(PyThreadState *tstate)
1010{
1011 assert(tstate != NULL);
Victor Stinner8fb02b62020-03-13 23:38:08 +01001012 return tstate->interp;
1013}
1014
1015
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001016struct _frame*
1017PyThreadState_GetFrame(PyThreadState *tstate)
1018{
1019 assert(tstate != NULL);
Victor Stinner6723e932020-03-20 17:46:56 +01001020 return tstate->frame;
Victor Stinnerfd1e1a12020-03-20 15:51:45 +01001021}
1022
1023
Victor Stinner5c3cda02020-03-25 21:23:53 +01001024uint64_t
1025PyThreadState_GetID(PyThreadState *tstate)
1026{
1027 assert(tstate != NULL);
1028 return tstate->id;
1029}
1030
1031
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001032/* Asynchronously raise an exception in a thread.
1033 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001034 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001035 to call this, or use ctypes. Must be called with the GIL held.
1036 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1037 match any known thread id). Can be called with exc=NULL to clear an
1038 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001039
1040int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001041PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1042{
Victor Stinner09532fe2019-05-10 23:39:09 +02001043 _PyRuntimeState *runtime = &_PyRuntime;
1044 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 /* Although the GIL is held, a few C API functions can be called
1047 * without the GIL held, and in particular some that create and
1048 * destroy thread and interpreter states. Those can mutate the
1049 * list of thread states we're traversing, so to prevent that we lock
1050 * head_mutex for the duration.
1051 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001052 HEAD_LOCK(runtime);
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001053 for (PyThreadState *tstate = interp->tstate_head; tstate != NULL; tstate = tstate->next) {
1054 if (tstate->thread_id != id) {
1055 continue;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 }
Victor Stinner56bfdeb2020-03-18 09:26:25 +01001057
1058 /* Tricky: we need to decref the current value
1059 * (if any) in tstate->async_exc, but that can in turn
1060 * allow arbitrary Python code to run, including
1061 * perhaps calls to this function. To prevent
1062 * deadlock, we need to release head_mutex before
1063 * the decref.
1064 */
1065 PyObject *old_exc = tstate->async_exc;
1066 Py_XINCREF(exc);
1067 tstate->async_exc = exc;
1068 HEAD_UNLOCK(runtime);
1069
1070 Py_XDECREF(old_exc);
1071 _PyEval_SignalAsyncExc(tstate);
1072 return 1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001074 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001076}
1077
1078
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001079/* Routines for advanced debuggers, requested by David Beazley.
1080 Don't use unless you know what you are doing! */
1081
1082PyInterpreterState *
1083PyInterpreterState_Head(void)
1084{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001085 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001086}
1087
1088PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001089PyInterpreterState_Main(void)
1090{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001091 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001092}
1093
1094PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001095PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001097}
1098
1099PyThreadState *
1100PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001102}
1103
1104PyThreadState *
1105PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001107}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001108
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001109/* The implementation of sys._current_frames(). This is intended to be
1110 called with the GIL held, as it will be when called via
1111 sys._current_frames(). It's possible it would work fine even without
1112 the GIL held, but haven't thought enough about that.
1113*/
1114PyObject *
1115_PyThread_CurrentFrames(void)
1116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 PyObject *result;
1118 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001119
Steve Dowerb82e17e2019-05-23 08:45:22 -07001120 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1121 return NULL;
1122 }
1123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 result = PyDict_New();
1125 if (result == NULL)
1126 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 /* for i in all interpreters:
1129 * for t in all of i's thread states:
1130 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001131 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 * need to grab head_mutex for the duration.
1133 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001134 _PyRuntimeState *runtime = &_PyRuntime;
1135 HEAD_LOCK(runtime);
1136 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 PyThreadState *t;
1138 for (t = i->tstate_head; t != NULL; t = t->next) {
1139 PyObject *id;
1140 int stat;
1141 struct _frame *frame = t->frame;
1142 if (frame == NULL)
1143 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001144 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 if (id == NULL)
1146 goto Fail;
1147 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1148 Py_DECREF(id);
1149 if (stat < 0)
1150 goto Fail;
1151 }
1152 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001153 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001155
1156 Fail:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001157 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001158 Py_DECREF(result);
1159 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001160}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001161
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001162/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001163
1164/* Keep this as a static, as it is not reliable! It can only
1165 ever be compared to the state for the *current* thread.
1166 * If not equal, then it doesn't matter that the actual
1167 value may change immediately after comparison, as it can't
1168 possibly change to the current thread's state.
1169 * If equal, then the current thread holds the lock, so the value can't
1170 change until we yield the lock.
1171*/
1172static int
1173PyThreadState_IsCurrent(PyThreadState *tstate)
1174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001176 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001177 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1178 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001179}
1180
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001181/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001182 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001183*/
Victor Stinner4e53abb2020-03-10 23:49:16 +01001184PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01001185_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001186{
Victor Stinner8bb32302019-04-24 16:47:40 +02001187 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001188 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001189 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001190
Victor Stinner01b1cc12019-11-20 02:27:56 +01001191 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001192
1193 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Victor Stinner4e53abb2020-03-10 23:49:16 +01001194 return _PyStatus_NO_MEMORY();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001195 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001196 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001197 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1198 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001199
Victor Stinner8bb32302019-04-24 16:47:40 +02001200 _PyGILState_NoteThreadState(gilstate, tstate);
Victor Stinner4e53abb2020-03-10 23:49:16 +01001201 return _PyStatus_OK();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001202}
1203
Victor Stinner861d9ab2016-03-16 22:45:24 +01001204PyInterpreterState *
1205_PyGILState_GetInterpreterStateUnsafe(void)
1206{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001207 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001208}
1209
Tim Peters19717fa2004-10-09 17:38:29 +00001210void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001211_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001212{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001213 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001214 PyThread_tss_delete(&gilstate->autoTSSkey);
1215 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001216}
1217
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001218/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001219 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001220 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001221 */
1222void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001223_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001224{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001225 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001226 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001227
1228 PyThread_tss_delete(&gilstate->autoTSSkey);
1229 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001230 Py_FatalError("Could not allocate TSS entry");
1231 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001232
Charles-François Natalia233df82011-11-22 19:49:51 +01001233 /* If the thread had an associated auto thread state, reassociate it with
1234 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001235 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001236 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001237 {
1238 Py_FatalError("Couldn't create autoTSSkey mapping");
1239 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001240}
1241
Michael W. Hudson188d4362005-06-20 16:52:57 +00001242/* When a thread state is created for a thread by some mechanism other than
1243 PyGILState_Ensure, it's important that the GILState machinery knows about
1244 it so it doesn't try to create another thread state for the thread (this is
1245 a better fix for SF bug #1010677 than the first one attempted).
1246*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001247static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001248_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001249{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001250 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001251 threadstate created in Py_Initialize(). Don't do anything for now
1252 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001253 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001255 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001256
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001257 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 The only situation where you can legitimately have more than one
1260 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001261 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001262
Victor Stinner590cebe2013-12-13 11:08:56 +01001263 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1264 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001265
Victor Stinner590cebe2013-12-13 11:08:56 +01001266 The first thread state created for that given OS level thread will
1267 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001269 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1270 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001271 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001272 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001273 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 /* PyGILState_Release must not try to delete this thread state. */
1276 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001277}
1278
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001279/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001280static PyThreadState *
1281_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1282{
1283 if (gilstate->autoInterpreterState == NULL)
1284 return NULL;
1285 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1286}
1287
Tim Peters19717fa2004-10-09 17:38:29 +00001288PyThreadState *
1289PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001290{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001291 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001292}
1293
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001294int
1295PyGILState_Check(void)
1296{
Victor Stinner8a1be612016-03-14 22:07:55 +01001297
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001298 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001299 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001300 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001301
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001302 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1303 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1304 return 1;
1305 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001306
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001307 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1308 if (tstate == NULL) {
1309 return 0;
1310 }
1311
1312 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001313}
1314
Tim Peters19717fa2004-10-09 17:38:29 +00001315PyGILState_STATE
1316PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001317{
Victor Stinner175a7042020-03-10 00:37:48 +01001318 _PyRuntimeState *runtime = &_PyRuntime;
1319 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 /* Note that we do not auto-init Python here - apart from
1322 potential races with 2 threads auto-initializing, pep-311
1323 spells out other issues. Embedders are expected to have
Victor Stinner175a7042020-03-10 00:37:48 +01001324 called Py_Initialize(). */
1325
1326 /* Ensure that _PyEval_InitThreads() and _PyGILState_Init() have been
1327 called by Py_Initialize() */
1328 assert(_PyEval_ThreadsInitialized(runtime));
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001329 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001330
Victor Stinner175a7042020-03-10 00:37:48 +01001331 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1332 int current;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 if (tcur == NULL) {
Victor Stinner175a7042020-03-10 00:37:48 +01001334 /* Create a new Python thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001335 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Victor Stinner175a7042020-03-10 00:37:48 +01001336 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 Py_FatalError("Couldn't create thread-state for new thread");
Victor Stinner175a7042020-03-10 00:37:48 +01001338 }
1339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 /* This is our thread state! We'll need to delete it in the
1341 matching call to PyGILState_Release(). */
1342 tcur->gilstate_counter = 0;
1343 current = 0; /* new thread state is never current */
1344 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001345 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001347 }
1348
1349 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001351 }
1352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 /* Update our counter in the thread-state - no need for locks:
1354 - tcur will remain valid as we hold the GIL.
1355 - the counter is safe as we are the only thread "allowed"
1356 to modify this value
1357 */
1358 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001361}
1362
Tim Peters19717fa2004-10-09 17:38:29 +00001363void
1364PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001365{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001366 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner23ef89d2020-03-18 02:26:04 +01001367 PyThreadState *tstate = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1368 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 Py_FatalError("auto-releasing thread-state, "
1370 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001371 }
1372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 /* We must hold the GIL and have our thread state current */
1374 /* XXX - remove the check - the assert should be fine,
1375 but while this is very new (April 2003), the extra check
1376 by release-only users can't hurt.
1377 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001378 if (!PyThreadState_IsCurrent(tstate)) {
Victor Stinner87d3b9d2020-03-25 19:27:36 +01001379 _Py_FatalErrorFormat(__func__,
1380 "thread state %p must be current when releasing",
1381 tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001382 }
Victor Stinner23ef89d2020-03-18 02:26:04 +01001383 assert(PyThreadState_IsCurrent(tstate));
1384 --tstate->gilstate_counter;
1385 assert(tstate->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 /* If we're going to destroy this thread-state, we must
1388 * clear it while the GIL is held, as destructors may run.
1389 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001390 if (tstate->gilstate_counter == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 /* can't have been locked when we created it */
1392 assert(oldstate == PyGILState_UNLOCKED);
Victor Stinner23ef89d2020-03-18 02:26:04 +01001393 PyThreadState_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 /* Delete the thread-state. Note this releases the GIL too!
1395 * It's vital that the GIL be held here, to avoid shutdown
1396 * races; see bugs 225673 and 1061968 (that nasty bug has a
1397 * habit of coming back).
1398 */
Victor Stinner23ef89d2020-03-18 02:26:04 +01001399 assert(_PyRuntimeGILState_GetThreadState(&runtime->gilstate) == tstate);
1400 _PyThreadState_DeleteCurrent(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 }
1402 /* Release the lock if necessary */
1403 else if (oldstate == PyGILState_UNLOCKED)
1404 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001405}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001406
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001407
Eric Snow7f8bfc92018-01-29 18:23:44 -07001408/**************************/
1409/* cross-interpreter data */
1410/**************************/
1411
1412/* cross-interpreter data */
1413
1414crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1415
1416/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1417 to keep the registry code separate. */
1418static crossinterpdatafunc
1419_lookup_getdata(PyObject *obj)
1420{
1421 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1422 if (getdata == NULL && PyErr_Occurred() == 0)
1423 PyErr_Format(PyExc_ValueError,
1424 "%S does not support cross-interpreter data", obj);
1425 return getdata;
1426}
1427
1428int
1429_PyObject_CheckCrossInterpreterData(PyObject *obj)
1430{
1431 crossinterpdatafunc getdata = _lookup_getdata(obj);
1432 if (getdata == NULL) {
1433 return -1;
1434 }
1435 return 0;
1436}
1437
1438static int
1439_check_xidata(_PyCrossInterpreterData *data)
1440{
1441 // data->data can be anything, including NULL, so we don't check it.
1442
1443 // data->obj may be NULL, so we don't check it.
1444
1445 if (data->interp < 0) {
1446 PyErr_SetString(PyExc_SystemError, "missing interp");
1447 return -1;
1448 }
1449
1450 if (data->new_object == NULL) {
1451 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1452 return -1;
1453 }
1454
1455 // data->free may be NULL, so we don't check it.
1456
1457 return 0;
1458}
1459
1460int
1461_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1462{
Victor Stinnerbe793732020-03-13 18:15:33 +01001463 // PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001464 // to check the result for NULL.
Victor Stinnerbe793732020-03-13 18:15:33 +01001465 PyInterpreterState *interp = PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001466
1467 // Reset data before re-populating.
1468 *data = (_PyCrossInterpreterData){0};
1469 data->free = PyMem_RawFree; // Set a default that may be overridden.
1470
1471 // Call the "getdata" func for the object.
1472 Py_INCREF(obj);
1473 crossinterpdatafunc getdata = _lookup_getdata(obj);
1474 if (getdata == NULL) {
1475 Py_DECREF(obj);
1476 return -1;
1477 }
1478 int res = getdata(obj, data);
1479 Py_DECREF(obj);
1480 if (res != 0) {
1481 return -1;
1482 }
1483
1484 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001485 data->interp = interp->id;
1486 if (_check_xidata(data) != 0) {
1487 _PyCrossInterpreterData_Release(data);
1488 return -1;
1489 }
1490
1491 return 0;
1492}
1493
Victor Stinnere225beb2019-06-03 18:14:24 +02001494static void
Eric Snow63799132018-06-01 18:45:20 -06001495_release_xidata(void *arg)
1496{
1497 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1498 if (data->free != NULL) {
1499 data->free(data->data);
1500 }
1501 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001502}
1503
1504static void
1505_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1506 PyInterpreterState *interp,
1507 void (*func)(void *), void *arg)
1508{
1509 /* We would use Py_AddPendingCall() if it weren't specific to the
1510 * main interpreter (see bpo-33608). In the meantime we take a
1511 * naive approach.
1512 */
1513 PyThreadState *save_tstate = NULL;
1514 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1515 // XXX Using the "head" thread isn't strictly correct.
1516 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1517 // XXX Possible GILState issues?
1518 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1519 }
1520
1521 func(arg);
1522
1523 // Switch back.
1524 if (save_tstate != NULL) {
1525 _PyThreadState_Swap(gilstate, save_tstate);
1526 }
Eric Snow63799132018-06-01 18:45:20 -06001527}
1528
Eric Snow7f8bfc92018-01-29 18:23:44 -07001529void
1530_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1531{
1532 if (data->data == NULL && data->obj == NULL) {
1533 // Nothing to release!
1534 return;
1535 }
1536
Victor Stinnere225beb2019-06-03 18:14:24 +02001537 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001538 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1539 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001540 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001541 if (data->free != NULL) {
1542 // XXX Someone leaked some memory...
1543 }
1544 return;
1545 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001546
Eric Snow7f8bfc92018-01-29 18:23:44 -07001547 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001548 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1549 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001550}
1551
1552PyObject *
1553_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1554{
1555 return data->new_object(data);
1556}
1557
1558/* registry of {type -> crossinterpdatafunc} */
1559
1560/* For now we use a global registry of shareable classes. An
1561 alternative would be to add a tp_* slot for a class's
1562 crossinterpdatafunc. It would be simpler and more efficient. */
1563
1564static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001565_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1566 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001567{
1568 // Note that we effectively replace already registered classes
1569 // rather than failing.
1570 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1571 if (newhead == NULL)
1572 return -1;
1573 newhead->cls = cls;
1574 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001575 newhead->next = xidregistry->head;
1576 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001577 return 0;
1578}
1579
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001580static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001581
1582int
Eric Snowc11183c2019-03-15 16:35:46 -06001583_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001584 crossinterpdatafunc getdata)
1585{
1586 if (!PyType_Check(cls)) {
1587 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1588 return -1;
1589 }
1590 if (getdata == NULL) {
1591 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1592 return -1;
1593 }
1594
1595 // Make sure the class isn't ever deallocated.
1596 Py_INCREF((PyObject *)cls);
1597
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001598 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1599 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1600 if (xidregistry->head == NULL) {
1601 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001602 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001603 int res = _register_xidata(xidregistry, cls, getdata);
1604 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001605 return res;
1606}
1607
Eric Snow6d2cd902018-05-16 15:04:57 -04001608/* Cross-interpreter objects are looked up by exact match on the class.
1609 We can reassess this policy when we move from a global registry to a
1610 tp_* slot. */
1611
Eric Snow7f8bfc92018-01-29 18:23:44 -07001612crossinterpdatafunc
1613_PyCrossInterpreterData_Lookup(PyObject *obj)
1614{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001615 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001616 PyObject *cls = PyObject_Type(obj);
1617 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001618 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1619 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001620 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001621 _register_builtins_for_crossinterpreter_data(xidregistry);
1622 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001623 }
1624 for(; cur != NULL; cur = cur->next) {
1625 if (cur->cls == (PyTypeObject *)cls) {
1626 getdata = cur->getdata;
1627 break;
1628 }
1629 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001630 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001631 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001632 return getdata;
1633}
1634
1635/* cross-interpreter data for builtin types */
1636
Eric Snow6d2cd902018-05-16 15:04:57 -04001637struct _shared_bytes_data {
1638 char *bytes;
1639 Py_ssize_t len;
1640};
1641
Eric Snow7f8bfc92018-01-29 18:23:44 -07001642static PyObject *
1643_new_bytes_object(_PyCrossInterpreterData *data)
1644{
Eric Snow6d2cd902018-05-16 15:04:57 -04001645 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1646 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001647}
1648
1649static int
1650_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1651{
Eric Snow6d2cd902018-05-16 15:04:57 -04001652 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1653 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1654 return -1;
1655 }
1656 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001657 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001658 data->obj = obj; // Will be "released" (decref'ed) when data released.
1659 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001660 data->free = PyMem_Free;
1661 return 0;
1662}
1663
1664struct _shared_str_data {
1665 int kind;
1666 const void *buffer;
1667 Py_ssize_t len;
1668};
1669
1670static PyObject *
1671_new_str_object(_PyCrossInterpreterData *data)
1672{
1673 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1674 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1675}
1676
1677static int
1678_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1679{
1680 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1681 shared->kind = PyUnicode_KIND(obj);
1682 shared->buffer = PyUnicode_DATA(obj);
1683 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1684 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001685 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001686 data->obj = obj; // Will be "released" (decref'ed) when data released.
1687 data->new_object = _new_str_object;
1688 data->free = PyMem_Free;
1689 return 0;
1690}
1691
1692static PyObject *
1693_new_long_object(_PyCrossInterpreterData *data)
1694{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001695 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001696}
1697
1698static int
1699_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1700{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001701 /* Note that this means the size of shareable ints is bounded by
1702 * sys.maxsize. Hence on 32-bit architectures that is half the
1703 * size of maximum shareable ints on 64-bit.
1704 */
1705 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001706 if (value == -1 && PyErr_Occurred()) {
1707 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1708 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1709 }
1710 return -1;
1711 }
1712 data->data = (void *)value;
1713 data->obj = NULL;
1714 data->new_object = _new_long_object;
1715 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001716 return 0;
1717}
1718
1719static PyObject *
1720_new_none_object(_PyCrossInterpreterData *data)
1721{
1722 // XXX Singleton refcounts are problematic across interpreters...
1723 Py_INCREF(Py_None);
1724 return Py_None;
1725}
1726
1727static int
1728_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1729{
1730 data->data = NULL;
1731 // data->obj remains NULL
1732 data->new_object = _new_none_object;
1733 data->free = NULL; // There is nothing to free.
1734 return 0;
1735}
1736
1737static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001738_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001739{
1740 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001741 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001742 Py_FatalError("could not register None for cross-interpreter sharing");
1743 }
1744
Eric Snow6d2cd902018-05-16 15:04:57 -04001745 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001746 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001747 Py_FatalError("could not register int for cross-interpreter sharing");
1748 }
1749
Eric Snow7f8bfc92018-01-29 18:23:44 -07001750 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001751 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001752 Py_FatalError("could not register bytes for cross-interpreter sharing");
1753 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001754
1755 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001756 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001757 Py_FatalError("could not register str for cross-interpreter sharing");
1758 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001759}
1760
1761
Victor Stinner0b72b232020-03-12 23:18:39 +01001762_PyFrameEvalFunction
1763_PyInterpreterState_GetEvalFrameFunc(PyInterpreterState *interp)
1764{
1765 return interp->eval_frame;
1766}
1767
1768
1769void
1770_PyInterpreterState_SetEvalFrameFunc(PyInterpreterState *interp,
1771 _PyFrameEvalFunction eval_frame)
1772{
1773 interp->eval_frame = eval_frame;
1774}
1775
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001776#ifdef __cplusplus
1777}
1778#endif