blob: f3d89e7d2b256e5352f6054e60eefe36259036db [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
40/* Forward declarations */
41static PyThreadState *_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate);
Victor Stinner0fd2c302019-06-04 03:15:09 +020042static void _PyThreadState_Delete(_PyRuntimeState *runtime, PyThreadState *tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +020043
44
Victor Stinner331a6a52019-05-27 16:39:22 +020045static PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010046_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060047{
Steve Dowerb82e17e2019-05-23 08:45:22 -070048 /* We preserve the hook across init, because there is
49 currently no public API to set it between runtime
50 initialization and interpreter initialization. */
51 void *open_code_hook = runtime->open_code_hook;
52 void *open_code_userdata = runtime->open_code_userdata;
53 _Py_AuditHookEntry *audit_hook_head = runtime->audit_hook_head;
54
Eric Snow2ebc5ce2017-09-07 23:51:28 -060055 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010056
Steve Dowerb82e17e2019-05-23 08:45:22 -070057 runtime->open_code_hook = open_code_hook;
58 runtime->open_code_userdata = open_code_userdata;
59 runtime->audit_hook_head = audit_hook_head;
60
Eric Snow2ebc5ce2017-09-07 23:51:28 -060061 _PyGC_Initialize(&runtime->gc);
62 _PyEval_Initialize(&runtime->ceval);
Victor Stinner441b10c2019-09-28 04:28:35 +020063
Victor Stinner3c30a762019-10-01 10:56:37 +020064 PyPreConfig_InitPythonConfig(&runtime->preconfig);
Michael W. Hudson188d4362005-06-20 16:52:57 +000065
Eric Snow2ebc5ce2017-09-07 23:51:28 -060066 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080067
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090068 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
69 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080070 Py_tss_t initial = Py_tss_NEEDS_INIT;
71 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000072
Eric Snow2ebc5ce2017-09-07 23:51:28 -060073 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080074 if (runtime->interpreters.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020075 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080076 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060077 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070078
79 runtime->xidregistry.mutex = PyThread_allocate_lock();
80 if (runtime->xidregistry.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020081 return _PyStatus_ERR("Can't initialize threads for cross-interpreter data registry");
Eric Snow7f8bfc92018-01-29 18:23:44 -070082 }
83
Eric Snow8479a342019-03-08 23:44:33 -070084 // Set it to the ID of the main thread of the main interpreter.
85 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070086
Victor Stinner331a6a52019-05-27 16:39:22 +020087 return _PyStatus_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060088}
Eric Snow05351c12017-09-05 21:43:08 -070089
Victor Stinner331a6a52019-05-27 16:39:22 +020090PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010091_PyRuntimeState_Init(_PyRuntimeState *runtime)
92{
93 /* Force default allocator, since _PyRuntimeState_Fini() must
94 use the same allocator than this function. */
95 PyMemAllocatorEx old_alloc;
96 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
97
Victor Stinner331a6a52019-05-27 16:39:22 +020098 PyStatus status = _PyRuntimeState_Init_impl(runtime);
Victor Stinner5d39e042017-11-29 17:20:38 +010099
100 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinner331a6a52019-05-27 16:39:22 +0200101 return status;
Victor Stinner5d39e042017-11-29 17:20:38 +0100102}
103
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600104void
105_PyRuntimeState_Fini(_PyRuntimeState *runtime)
106{
Victor Stinner5d39e042017-11-29 17:20:38 +0100107 /* Force the allocator used by _PyRuntimeState_Init(). */
108 PyMemAllocatorEx old_alloc;
109 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -0800110
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600111 if (runtime->interpreters.mutex != NULL) {
112 PyThread_free_lock(runtime->interpreters.mutex);
113 runtime->interpreters.mutex = NULL;
114 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800115
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100116 if (runtime->xidregistry.mutex != NULL) {
117 PyThread_free_lock(runtime->xidregistry.mutex);
118 runtime->xidregistry.mutex = NULL;
119 }
120
Victor Stinnerccb04422017-11-16 03:20:31 -0800121 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600122}
123
Eric Snow8479a342019-03-08 23:44:33 -0700124/* This function is called from PyOS_AfterFork_Child to ensure that
125 * newly created child processes do not share locks with the parent.
126 */
127
128void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200129_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700130{
131 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200132 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700133
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200134 /* Force default allocator, since _PyRuntimeState_Fini() must
135 use the same allocator than this function. */
136 PyMemAllocatorEx old_alloc;
137 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
138
139 runtime->interpreters.mutex = PyThread_allocate_lock();
140 runtime->interpreters.main->id_mutex = PyThread_allocate_lock();
141 runtime->xidregistry.mutex = PyThread_allocate_lock();
142
143 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
144
145 if (runtime->interpreters.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700146 Py_FatalError("Can't initialize lock for runtime interpreters");
147 }
148
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200149 if (runtime->interpreters.main->id_mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700150 Py_FatalError("Can't initialize ID lock for main interpreter");
151 }
152
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200153 if (runtime->xidregistry.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700154 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
155 }
156}
157
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200158#define HEAD_LOCK(runtime) \
159 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
160#define HEAD_UNLOCK(runtime) \
161 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700162
Victor Stinner8bb32302019-04-24 16:47:40 +0200163/* Forward declaration */
164static void _PyGILState_NoteThreadState(
165 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000166
Victor Stinner331a6a52019-05-27 16:39:22 +0200167PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600168_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700169{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200170 struct pyinterpreters *interpreters = &runtime->interpreters;
171 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100172
173 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
174 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200175 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100176 /* Force default allocator, since _PyRuntimeState_Fini() must
177 use the same allocator than this function. */
178 PyMemAllocatorEx old_alloc;
179 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
180
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200181 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100182
183 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
184
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200185 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200186 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800187 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600188 }
Victor Stinner5d926472018-03-06 14:31:37 +0100189
Victor Stinner331a6a52019-05-27 16:39:22 +0200190 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700191}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000192
193PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000194PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000195{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700196 if (PySys_Audit("cpython.PyInterpreterState_New", NULL) < 0) {
197 return NULL;
198 }
199
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200200 PyInterpreterState *interp = PyMem_RawMalloc(sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100201 if (interp == NULL) {
202 return NULL;
203 }
204
Eric Snow5be45a62019-03-08 22:47:07 -0700205 memset(interp, 0, sizeof(*interp));
Eric Snow4c6955e2018-02-16 18:53:40 -0700206 interp->id_refcount = -1;
Victor Stinner022be022019-05-22 23:58:50 +0200207
Victor Stinner8462a492019-10-01 12:06:16 +0200208 PyConfig_InitPythonConfig(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200209
Victor Stinnerd4341102017-11-23 00:12:09 +0100210 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000211#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300212#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100213 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000214#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100215 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000216#endif
217#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000218
Victor Stinner0fd2c302019-06-04 03:15:09 +0200219 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200220 struct pyinterpreters *interpreters = &runtime->interpreters;
221
222 HEAD_LOCK(runtime);
223 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100224 /* overflow or Py_Initialize() not called! */
225 PyErr_SetString(PyExc_RuntimeError,
226 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100227 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100228 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100229 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200230 else {
231 interp->id = interpreters->next_id;
232 interpreters->next_id += 1;
233 interp->next = interpreters->head;
234 if (interpreters->main == NULL) {
235 interpreters->main = interp;
236 }
237 interpreters->head = interp;
238 }
239 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000240
Pablo Galindo95d630e2018-08-31 22:49:29 +0100241 if (interp == NULL) {
242 return NULL;
243 }
244
Yury Selivanovf23746a2018-01-22 19:11:18 -0500245 interp->tstate_next_unique_id = 0;
246
Steve Dowerb82e17e2019-05-23 08:45:22 -0700247 interp->audit_hooks = NULL;
248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000250}
251
252
Victor Stinner0fd2c302019-06-04 03:15:09 +0200253static void
254_PyInterpreterState_Clear(_PyRuntimeState *runtime, PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000255{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700256 if (PySys_Audit("cpython.PyInterpreterState_Clear", NULL) < 0) {
257 PyErr_Clear();
258 }
259
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200260 HEAD_LOCK(runtime);
261 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200263 }
264 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700265
266 Py_CLEAR(interp->audit_hooks);
267
Victor Stinner331a6a52019-05-27 16:39:22 +0200268 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 Py_CLEAR(interp->codec_search_path);
270 Py_CLEAR(interp->codec_search_cache);
271 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700272 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 Py_CLEAR(interp->sysdict);
275 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200276 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400277 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300278 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600279 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200280#ifdef HAVE_FORK
281 Py_CLEAR(interp->before_forkers);
282 Py_CLEAR(interp->after_forkers_parent);
283 Py_CLEAR(interp->after_forkers_child);
284#endif
Eric Snow86ea5812019-05-10 13:29:55 -0400285 if (runtime->finalizing == NULL) {
286 _PyWarnings_Fini(interp);
287 }
Eric Snow5be45a62019-03-08 22:47:07 -0700288 // XXX Once we have one allocator per interpreter (i.e.
289 // per-interpreter GC) we must ensure that all of the interpreter's
290 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000291}
292
Victor Stinner0fd2c302019-06-04 03:15:09 +0200293void
294PyInterpreterState_Clear(PyInterpreterState *interp)
295{
296 _PyInterpreterState_Clear(&_PyRuntime, interp);
297}
298
Guido van Rossum25ce5661997-08-02 03:10:38 +0000299
300static void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200301zapthreads(_PyRuntimeState *runtime, PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000302{
Victor Stinner0fd2c302019-06-04 03:15:09 +0200303 PyThreadState *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 /* No need to lock the mutex here because this should only happen
305 when the threads are all really dead (XXX famous last words). */
Victor Stinner0fd2c302019-06-04 03:15:09 +0200306 while ((p = interp->tstate_head) != NULL) {
307 _PyThreadState_Delete(runtime, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000309}
310
311
Victor Stinner0fd2c302019-06-04 03:15:09 +0200312static void
313_PyInterpreterState_Delete(_PyRuntimeState *runtime,
314 PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200315{
316 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner0fd2c302019-06-04 03:15:09 +0200317 zapthreads(runtime, interp);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200318 HEAD_LOCK(runtime);
319 PyInterpreterState **p;
320 for (p = &interpreters->head; ; p = &(*p)->next) {
321 if (*p == NULL) {
322 Py_FatalError("PyInterpreterState_Delete: invalid interp");
323 }
324 if (*p == interp) {
325 break;
326 }
327 }
328 if (interp->tstate_head != NULL) {
329 Py_FatalError("PyInterpreterState_Delete: remaining threads");
330 }
331 *p = interp->next;
332 if (interpreters->main == interp) {
333 interpreters->main = NULL;
334 if (interpreters->head != NULL) {
335 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
336 }
337 }
338 HEAD_UNLOCK(runtime);
339 if (interp->id_mutex != NULL) {
340 PyThread_free_lock(interp->id_mutex);
341 }
342 PyMem_RawFree(interp);
343}
344
345
Victor Stinner0fd2c302019-06-04 03:15:09 +0200346void
347PyInterpreterState_Delete(PyInterpreterState *interp)
348{
349 _PyInterpreterState_Delete(&_PyRuntime, interp);
350}
351
352
Eric Snow59032962018-09-14 14:17:20 -0700353/*
354 * Delete all interpreter states except the main interpreter. If there
355 * is a current interpreter state, it *must* be the main interpreter.
356 */
357void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200358_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700359{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200360 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200361 struct pyinterpreters *interpreters = &runtime->interpreters;
362
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200363 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200364 if (tstate != NULL && tstate->interp != interpreters->main) {
Eric Snow59032962018-09-14 14:17:20 -0700365 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
366 }
367
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200368 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200369 PyInterpreterState *interp = interpreters->head;
370 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100371 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200372 if (interp == interpreters->main) {
373 interpreters->main->next = NULL;
374 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100375 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700376 continue;
377 }
378
Victor Stinner0fd2c302019-06-04 03:15:09 +0200379 _PyInterpreterState_Clear(runtime, interp); // XXX must activate?
380 zapthreads(runtime, interp);
Eric Snow59032962018-09-14 14:17:20 -0700381 if (interp->id_mutex != NULL) {
382 PyThread_free_lock(interp->id_mutex);
383 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100384 PyInterpreterState *prev_interp = interp;
385 interp = interp->next;
386 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700387 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200388 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700389
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200390 if (interpreters->head == NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700391 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
392 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200393 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700394}
395
396
Victor Stinnercaba55b2018-08-03 15:33:52 +0200397PyInterpreterState *
398_PyInterpreterState_Get(void)
399{
Victor Stinner50b48572018-11-01 01:51:40 +0100400 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200401 if (tstate == NULL) {
402 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
403 }
404 PyInterpreterState *interp = tstate->interp;
405 if (interp == NULL) {
406 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
407 }
408 return interp;
409}
410
411
Eric Snowe3774162017-05-22 19:46:40 -0700412int64_t
413PyInterpreterState_GetID(PyInterpreterState *interp)
414{
415 if (interp == NULL) {
416 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
417 return -1;
418 }
419 return interp->id;
420}
421
422
Eric Snow5be45a62019-03-08 22:47:07 -0700423static PyInterpreterState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200424interp_look_up_id(_PyRuntimeState *runtime, PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700425{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200426 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100427 while (interp != NULL) {
428 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700429 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100430 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700431 }
432 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100433 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700434 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100435 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700436 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100437 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700438}
439
Eric Snow5be45a62019-03-08 22:47:07 -0700440PyInterpreterState *
441_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
442{
443 PyInterpreterState *interp = NULL;
444 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200445 _PyRuntimeState *runtime = &_PyRuntime;
446 HEAD_LOCK(runtime);
447 interp = interp_look_up_id(runtime, requested_id);
448 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700449 }
450 if (interp == NULL && !PyErr_Occurred()) {
451 PyErr_Format(PyExc_RuntimeError,
452 "unrecognized interpreter ID %lld", requested_id);
453 }
454 return interp;
455}
456
Eric Snow4c6955e2018-02-16 18:53:40 -0700457
458int
459_PyInterpreterState_IDInitref(PyInterpreterState *interp)
460{
461 if (interp->id_mutex != NULL) {
462 return 0;
463 }
464 interp->id_mutex = PyThread_allocate_lock();
465 if (interp->id_mutex == NULL) {
466 PyErr_SetString(PyExc_RuntimeError,
467 "failed to create init interpreter ID mutex");
468 return -1;
469 }
470 interp->id_refcount = 0;
471 return 0;
472}
473
474
475void
476_PyInterpreterState_IDIncref(PyInterpreterState *interp)
477{
478 if (interp->id_mutex == NULL) {
479 return;
480 }
481 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
482 interp->id_refcount += 1;
483 PyThread_release_lock(interp->id_mutex);
484}
485
486
487void
488_PyInterpreterState_IDDecref(PyInterpreterState *interp)
489{
490 if (interp->id_mutex == NULL) {
491 return;
492 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200493 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700494 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
495 assert(interp->id_refcount != 0);
496 interp->id_refcount -= 1;
497 int64_t refcount = interp->id_refcount;
498 PyThread_release_lock(interp->id_mutex);
499
Eric Snowc11183c2019-03-15 16:35:46 -0600500 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700501 // XXX Using the "head" thread isn't strictly correct.
502 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
503 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200504 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700505 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200506 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700507 }
508}
509
Eric Snowc11183c2019-03-15 16:35:46 -0600510int
511_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
512{
513 return interp->requires_idref;
514}
515
516void
517_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
518{
519 interp->requires_idref = required ? 1 : 0;
520}
521
Eric Snowc11183c2019-03-15 16:35:46 -0600522PyObject *
523_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
524{
525 if (interp->modules == NULL) {
526 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
527 return NULL;
528 }
529 return PyMapping_GetItemString(interp->modules, "__main__");
530}
531
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600532PyObject *
533PyInterpreterState_GetDict(PyInterpreterState *interp)
534{
535 if (interp->dict == NULL) {
536 interp->dict = PyDict_New();
537 if (interp->dict == NULL) {
538 PyErr_Clear();
539 }
540 }
541 /* Returning NULL means no per-interpreter dict is available. */
542 return interp->dict;
543}
544
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000545/* Default implementation for _PyThreadState_GetFrame */
546static struct _frame *
547threadstate_getframe(PyThreadState *self)
548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000550}
551
Victor Stinner45b9be52010-03-03 23:28:07 +0000552static PyThreadState *
553new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000554{
Victor Stinner0fd2c302019-06-04 03:15:09 +0200555 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200556 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200557 if (tstate == NULL) {
558 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000560
Victor Stinner8bb32302019-04-24 16:47:40 +0200561 if (_PyThreadState_GetFrame == NULL) {
562 _PyThreadState_GetFrame = threadstate_getframe;
563 }
564
565 tstate->interp = interp;
566
567 tstate->frame = NULL;
568 tstate->recursion_depth = 0;
569 tstate->overflowed = 0;
570 tstate->recursion_critical = 0;
571 tstate->stackcheck_counter = 0;
572 tstate->tracing = 0;
573 tstate->use_tracing = 0;
574 tstate->gilstate_counter = 0;
575 tstate->async_exc = NULL;
576 tstate->thread_id = PyThread_get_thread_ident();
577
578 tstate->dict = NULL;
579
580 tstate->curexc_type = NULL;
581 tstate->curexc_value = NULL;
582 tstate->curexc_traceback = NULL;
583
584 tstate->exc_state.exc_type = NULL;
585 tstate->exc_state.exc_value = NULL;
586 tstate->exc_state.exc_traceback = NULL;
587 tstate->exc_state.previous_item = NULL;
588 tstate->exc_info = &tstate->exc_state;
589
590 tstate->c_profilefunc = NULL;
591 tstate->c_tracefunc = NULL;
592 tstate->c_profileobj = NULL;
593 tstate->c_traceobj = NULL;
594
595 tstate->trash_delete_nesting = 0;
596 tstate->trash_delete_later = NULL;
597 tstate->on_delete = NULL;
598 tstate->on_delete_data = NULL;
599
600 tstate->coroutine_origin_tracking_depth = 0;
601
Victor Stinner8bb32302019-04-24 16:47:40 +0200602 tstate->async_gen_firstiter = NULL;
603 tstate->async_gen_finalizer = NULL;
604
605 tstate->context = NULL;
606 tstate->context_ver = 1;
607
608 tstate->id = ++interp->tstate_next_unique_id;
609
610 if (init) {
Victor Stinner0fd2c302019-06-04 03:15:09 +0200611 _PyThreadState_Init(runtime, tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200612 }
613
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200614 HEAD_LOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200615 tstate->prev = NULL;
616 tstate->next = interp->tstate_head;
617 if (tstate->next)
618 tstate->next->prev = tstate;
619 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200620 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000623}
624
Victor Stinner45b9be52010-03-03 23:28:07 +0000625PyThreadState *
626PyThreadState_New(PyInterpreterState *interp)
627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000629}
630
631PyThreadState *
632_PyThreadState_Prealloc(PyInterpreterState *interp)
633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000635}
636
637void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200638_PyThreadState_Init(_PyRuntimeState *runtime, PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000639{
Victor Stinner8bb32302019-04-24 16:47:40 +0200640 _PyGILState_NoteThreadState(&runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000641}
642
Martin v. Löwis1a214512008-06-11 05:26:20 +0000643PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200644PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000645{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200646 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100647 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000649 if (module->m_slots) {
650 return NULL;
651 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 if (index == 0)
653 return NULL;
654 if (state->modules_by_index == NULL)
655 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200656 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 return NULL;
658 res = PyList_GET_ITEM(state->modules_by_index, index);
659 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000660}
661
662int
663_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
664{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000665 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300666 if (!def) {
667 assert(PyErr_Occurred());
668 return -1;
669 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000670 if (def->m_slots) {
671 PyErr_SetString(PyExc_SystemError,
672 "PyState_AddModule called on module with slots");
673 return -1;
674 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100675 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 if (!state->modules_by_index) {
677 state->modules_by_index = PyList_New(0);
678 if (!state->modules_by_index)
679 return -1;
680 }
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100681 while (PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 if (PyList_Append(state->modules_by_index, Py_None) < 0)
683 return -1;
684 Py_INCREF(module);
685 return PyList_SetItem(state->modules_by_index,
686 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000687}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000688
Martin v. Löwis7800f752012-06-22 12:20:55 +0200689int
690PyState_AddModule(PyObject* module, struct PyModuleDef* def)
691{
692 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100693 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200694 if (!def) {
695 Py_FatalError("PyState_AddModule: Module Definition is NULL");
696 return -1;
697 }
698 index = def->m_base.m_index;
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100699 if (state->modules_by_index &&
700 index < PyList_GET_SIZE(state->modules_by_index) &&
701 module == PyList_GET_ITEM(state->modules_by_index, index)) {
702 Py_FatalError("PyState_AddModule: Module already added!");
703 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200704 }
705 return _PyState_AddModule(module, def);
706}
707
708int
709PyState_RemoveModule(struct PyModuleDef* def)
710{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000711 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200712 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000713 if (def->m_slots) {
714 PyErr_SetString(PyExc_SystemError,
715 "PyState_RemoveModule called on module with slots");
716 return -1;
717 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100718 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200719 if (index == 0) {
720 Py_FatalError("PyState_RemoveModule: Module index invalid.");
721 return -1;
722 }
723 if (state->modules_by_index == NULL) {
Min ho Kim39d87b52019-08-31 06:21:19 +1000724 Py_FatalError("PyState_RemoveModule: Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200725 return -1;
726 }
727 if (index > PyList_GET_SIZE(state->modules_by_index)) {
728 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
729 return -1;
730 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700731 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200732 return PyList_SetItem(state->modules_by_index, index, Py_None);
733}
734
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200735/* Used by PyImport_Cleanup() */
Antoine Pitrou40322e62013-08-11 00:30:09 +0200736void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200737_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200738{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200739 if (!interp->modules_by_index) {
740 return;
741 }
742
743 Py_ssize_t i;
744 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
745 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
746 if (PyModule_Check(m)) {
747 /* cleanup the saved copy of module dicts */
748 PyModuleDef *md = PyModule_GetDef(m);
749 if (md) {
750 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200751 }
752 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200753 }
754
755 /* Setting modules_by_index to NULL could be dangerous, so we
756 clear the list instead. */
757 if (PyList_SetSlice(interp->modules_by_index,
758 0, PyList_GET_SIZE(interp->modules_by_index),
759 NULL)) {
760 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200761 }
762}
763
Guido van Rossuma027efa1997-05-05 20:56:21 +0000764void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000765PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000766{
Victor Stinner331a6a52019-05-27 16:39:22 +0200767 int verbose = tstate->interp->config.verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200768
769 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 fprintf(stderr,
771 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 Py_CLEAR(tstate->dict);
776 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 Py_CLEAR(tstate->curexc_type);
779 Py_CLEAR(tstate->curexc_value);
780 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000781
Mark Shannonae3087c2017-10-22 22:41:51 +0100782 Py_CLEAR(tstate->exc_state.exc_type);
783 Py_CLEAR(tstate->exc_state.exc_value);
784 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300785
Mark Shannonae3087c2017-10-22 22:41:51 +0100786 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200787 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100788 fprintf(stderr,
789 "PyThreadState_Clear: warning: thread still has a generator\n");
790 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 tstate->c_profilefunc = NULL;
793 tstate->c_tracefunc = NULL;
794 Py_CLEAR(tstate->c_profileobj);
795 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400796
Yury Selivanoveb636452016-09-08 22:01:51 -0700797 Py_CLEAR(tstate->async_gen_firstiter);
798 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500799
800 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000801}
802
803
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300804/* Common code for PyThreadState_Delete() and _PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000805static void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200806tstate_delete_common(_PyRuntimeState *runtime, PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000807{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200808 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 Py_FatalError("PyThreadState_Delete: NULL tstate");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200810 }
811 PyInterpreterState *interp = tstate->interp;
812 if (interp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 Py_FatalError("PyThreadState_Delete: NULL interp");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200814 }
815 HEAD_LOCK(runtime);
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200816 if (tstate->prev)
817 tstate->prev->next = tstate->next;
818 else
819 interp->tstate_head = tstate->next;
820 if (tstate->next)
821 tstate->next->prev = tstate->prev;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200822 HEAD_UNLOCK(runtime);
Antoine Pitrou7b476992013-09-07 23:38:37 +0200823 if (tstate->on_delete != NULL) {
824 tstate->on_delete(tstate->on_delete_data);
825 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200826 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000827}
828
829
Victor Stinner0fd2c302019-06-04 03:15:09 +0200830static void
831_PyThreadState_Delete(_PyRuntimeState *runtime, PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000832{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200833 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
834 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600836 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200837 if (gilstate->autoInterpreterState &&
838 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
839 {
840 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
841 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200842 tstate_delete_common(runtime, tstate);
843}
844
845
846void
847PyThreadState_Delete(PyThreadState *tstate)
848{
849 _PyThreadState_Delete(&_PyRuntime, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200850}
851
852
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300853void
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200854_PyThreadState_DeleteCurrent(_PyRuntimeState *runtime)
855{
856 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
857 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 if (tstate == NULL)
859 Py_FatalError(
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300860 "_PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner0fd2c302019-06-04 03:15:09 +0200861 tstate_delete_common(runtime, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200862 if (gilstate->autoInterpreterState &&
863 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600864 {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200865 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600866 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200867 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000869}
Guido van Rossum29757862001-01-23 01:46:06 +0000870
871
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200872/*
873 * Delete all thread states except the one passed as argument.
874 * Note that, if there is a current thread state, it *must* be the one
875 * passed as argument. Also, this won't touch any other interpreters
876 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000877 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200878 */
879void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200880_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200881{
882 PyInterpreterState *interp = tstate->interp;
883 PyThreadState *p, *next, *garbage;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200884 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200885 /* Remove all thread states, except tstate, from the linked list of
886 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200887 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200888 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200889 if (garbage == tstate)
890 garbage = tstate->next;
891 if (tstate->prev)
892 tstate->prev->next = tstate->next;
893 if (tstate->next)
894 tstate->next->prev = tstate->prev;
895 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200896 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200897 HEAD_UNLOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200898 /* Clear and deallocate all stale thread states. Even if this
899 executes Python code, we should be safe since it executes
900 in the current thread, not one of the stale threads. */
901 for (p = garbage; p; p = next) {
902 next = p->next;
903 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200904 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200905 }
906}
907
908
Guido van Rossuma027efa1997-05-05 20:56:21 +0000909PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100910_PyThreadState_UncheckedGet(void)
911{
Victor Stinner50b48572018-11-01 01:51:40 +0100912 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100913}
914
915
916PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000917PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000918{
Victor Stinner50b48572018-11-01 01:51:40 +0100919 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 if (tstate == NULL)
921 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000924}
925
926
Victor Stinner09532fe2019-05-10 23:39:09 +0200927PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200928_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000929{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200930 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000931
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200932 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 /* It should not be possible for more than one thread state
934 to be used for a thread. Check this the best we can in debug
935 builds.
936 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200937#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 if (newts) {
939 /* This can be called from PyEval_RestoreThread(). Similar
940 to it, we need to ensure errno doesn't change.
941 */
942 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200943 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 if (check && check->interp == newts->interp && check != newts)
945 Py_FatalError("Invalid thread state for this thread");
946 errno = err;
947 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000948#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000950}
Guido van Rossumede04391998-04-10 20:18:25 +0000951
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200952PyThreadState *
953PyThreadState_Swap(PyThreadState *newts)
954{
955 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
956}
957
Guido van Rossumede04391998-04-10 20:18:25 +0000958/* An extension mechanism to store arbitrary additional per-thread state.
959 PyThreadState_GetDict() returns a dictionary that can be used to hold such
960 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000961 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
962 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000963
964PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000965PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000966{
Victor Stinner50b48572018-11-01 01:51:40 +0100967 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 if (tstate == NULL)
969 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (tstate->dict == NULL) {
972 PyObject *d;
973 tstate->dict = d = PyDict_New();
974 if (d == NULL)
975 PyErr_Clear();
976 }
977 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000978}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000979
980
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000981/* Asynchronously raise an exception in a thread.
982 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000983 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000984 to call this, or use ctypes. Must be called with the GIL held.
985 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
986 match any known thread id). Can be called with exc=NULL to clear an
987 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000988
989int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200990PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
991{
Victor Stinner09532fe2019-05-10 23:39:09 +0200992 _PyRuntimeState *runtime = &_PyRuntime;
993 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 /* Although the GIL is held, a few C API functions can be called
996 * without the GIL held, and in particular some that create and
997 * destroy thread and interpreter states. Those can mutate the
998 * list of thread states we're traversing, so to prevent that we lock
999 * head_mutex for the duration.
1000 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001001 HEAD_LOCK(runtime);
Victor Stinner09532fe2019-05-10 23:39:09 +02001002 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 if (p->thread_id == id) {
1004 /* Tricky: we need to decref the current value
1005 * (if any) in p->async_exc, but that can in turn
1006 * allow arbitrary Python code to run, including
1007 * perhaps calls to this function. To prevent
1008 * deadlock, we need to release head_mutex before
1009 * the decref.
1010 */
1011 PyObject *old_exc = p->async_exc;
1012 Py_XINCREF(exc);
1013 p->async_exc = exc;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001014 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 Py_XDECREF(old_exc);
Victor Stinnere225beb2019-06-03 18:14:24 +02001016 _PyEval_SignalAsyncExc(&runtime->ceval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 return 1;
1018 }
1019 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001020 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001022}
1023
1024
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001025/* Routines for advanced debuggers, requested by David Beazley.
1026 Don't use unless you know what you are doing! */
1027
1028PyInterpreterState *
1029PyInterpreterState_Head(void)
1030{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001031 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001032}
1033
1034PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001035PyInterpreterState_Main(void)
1036{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001037 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001038}
1039
1040PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001041PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001043}
1044
1045PyThreadState *
1046PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001048}
1049
1050PyThreadState *
1051PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001053}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001054
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001055/* The implementation of sys._current_frames(). This is intended to be
1056 called with the GIL held, as it will be when called via
1057 sys._current_frames(). It's possible it would work fine even without
1058 the GIL held, but haven't thought enough about that.
1059*/
1060PyObject *
1061_PyThread_CurrentFrames(void)
1062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 PyObject *result;
1064 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001065
Steve Dowerb82e17e2019-05-23 08:45:22 -07001066 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1067 return NULL;
1068 }
1069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 result = PyDict_New();
1071 if (result == NULL)
1072 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 /* for i in all interpreters:
1075 * for t in all of i's thread states:
1076 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001077 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 * need to grab head_mutex for the duration.
1079 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001080 _PyRuntimeState *runtime = &_PyRuntime;
1081 HEAD_LOCK(runtime);
1082 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 PyThreadState *t;
1084 for (t = i->tstate_head; t != NULL; t = t->next) {
1085 PyObject *id;
1086 int stat;
1087 struct _frame *frame = t->frame;
1088 if (frame == NULL)
1089 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001090 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 if (id == NULL)
1092 goto Fail;
1093 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1094 Py_DECREF(id);
1095 if (stat < 0)
1096 goto Fail;
1097 }
1098 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001099 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001101
1102 Fail:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001103 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 Py_DECREF(result);
1105 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001106}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001107
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001108/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001109
1110/* Keep this as a static, as it is not reliable! It can only
1111 ever be compared to the state for the *current* thread.
1112 * If not equal, then it doesn't matter that the actual
1113 value may change immediately after comparison, as it can't
1114 possibly change to the current thread's state.
1115 * If equal, then the current thread holds the lock, so the value can't
1116 change until we yield the lock.
1117*/
1118static int
1119PyThreadState_IsCurrent(PyThreadState *tstate)
1120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001122 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001123 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1124 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001125}
1126
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001127/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001128 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001129*/
Tim Peters19717fa2004-10-09 17:38:29 +00001130void
Victor Stinnerb45d2592019-06-20 00:05:23 +02001131_PyGILState_Init(_PyRuntimeState *runtime, PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001132{
Victor Stinner8bb32302019-04-24 16:47:40 +02001133 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001134 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001135 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001136
Victor Stinner8bb32302019-04-24 16:47:40 +02001137 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1138
1139 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001140 Py_FatalError("Could not allocate TSS entry");
1141 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001142 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001143 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1144 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001145
Victor Stinner8bb32302019-04-24 16:47:40 +02001146 _PyGILState_NoteThreadState(gilstate, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001147}
1148
Victor Stinner861d9ab2016-03-16 22:45:24 +01001149PyInterpreterState *
1150_PyGILState_GetInterpreterStateUnsafe(void)
1151{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001152 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001153}
1154
Tim Peters19717fa2004-10-09 17:38:29 +00001155void
Victor Stinner8e91c242019-04-24 17:24:01 +02001156_PyGILState_Fini(_PyRuntimeState *runtime)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001157{
Victor Stinner8e91c242019-04-24 17:24:01 +02001158 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1159 PyThread_tss_delete(&gilstate->autoTSSkey);
1160 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001161}
1162
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001163/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001164 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001165 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001166 */
1167void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001168_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001169{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001170 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001171 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001172
1173 PyThread_tss_delete(&gilstate->autoTSSkey);
1174 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001175 Py_FatalError("Could not allocate TSS entry");
1176 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001177
Charles-François Natalia233df82011-11-22 19:49:51 +01001178 /* If the thread had an associated auto thread state, reassociate it with
1179 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001180 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001181 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001182 {
1183 Py_FatalError("Couldn't create autoTSSkey mapping");
1184 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001185}
1186
Michael W. Hudson188d4362005-06-20 16:52:57 +00001187/* When a thread state is created for a thread by some mechanism other than
1188 PyGILState_Ensure, it's important that the GILState machinery knows about
1189 it so it doesn't try to create another thread state for the thread (this is
1190 a better fix for SF bug #1010677 than the first one attempted).
1191*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001192static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001193_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001194{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001195 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001196 threadstate created in Py_Initialize(). Don't do anything for now
1197 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001198 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001200 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001201
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001202 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 The only situation where you can legitimately have more than one
1205 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001206 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001207
Victor Stinner590cebe2013-12-13 11:08:56 +01001208 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1209 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001210
Victor Stinner590cebe2013-12-13 11:08:56 +01001211 The first thread state created for that given OS level thread will
1212 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001214 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1215 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001216 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001217 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001218 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 /* PyGILState_Release must not try to delete this thread state. */
1221 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001222}
1223
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001224/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001225static PyThreadState *
1226_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1227{
1228 if (gilstate->autoInterpreterState == NULL)
1229 return NULL;
1230 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1231}
1232
Tim Peters19717fa2004-10-09 17:38:29 +00001233PyThreadState *
1234PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001235{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001236 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001237}
1238
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001239int
1240PyGILState_Check(void)
1241{
Victor Stinner8a1be612016-03-14 22:07:55 +01001242
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001243 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001244 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001245 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001246
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001247 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1248 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1249 return 1;
1250 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001251
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001252 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1253 if (tstate == NULL) {
1254 return 0;
1255 }
1256
1257 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001258}
1259
Tim Peters19717fa2004-10-09 17:38:29 +00001260PyGILState_STATE
1261PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001262{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001263 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 int current;
1265 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001266 int need_init_threads = 0;
1267
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 /* Note that we do not auto-init Python here - apart from
1269 potential races with 2 threads auto-initializing, pep-311
1270 spells out other issues. Embedders are expected to have
1271 called Py_Initialize() and usually PyEval_InitThreads().
1272 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001273 /* Py_Initialize() hasn't been called! */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001274 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001275
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001276 tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001278 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 /* Create a new thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001281 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (tcur == NULL)
1283 Py_FatalError("Couldn't create thread-state for new thread");
1284 /* This is our thread state! We'll need to delete it in the
1285 matching call to PyGILState_Release(). */
1286 tcur->gilstate_counter = 0;
1287 current = 0; /* new thread state is never current */
1288 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001289 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001291 }
1292
1293 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001295 }
1296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 /* Update our counter in the thread-state - no need for locks:
1298 - tcur will remain valid as we hold the GIL.
1299 - the counter is safe as we are the only thread "allowed"
1300 to modify this value
1301 */
1302 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001303
1304 if (need_init_threads) {
1305 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1306 called from a new thread for the first time, we need the create the
1307 GIL. */
1308 PyEval_InitThreads();
1309 }
1310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001311 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001312}
1313
Tim Peters19717fa2004-10-09 17:38:29 +00001314void
1315PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001316{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001317 _PyRuntimeState *runtime = &_PyRuntime;
1318 PyThreadState *tcur = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1319 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 Py_FatalError("auto-releasing thread-state, "
1321 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001322 }
1323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 /* We must hold the GIL and have our thread state current */
1325 /* XXX - remove the check - the assert should be fine,
1326 but while this is very new (April 2003), the extra check
1327 by release-only users can't hurt.
1328 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001329 if (!PyThreadState_IsCurrent(tcur)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 Py_FatalError("This thread state must be current when releasing");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001331 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 assert(PyThreadState_IsCurrent(tcur));
1333 --tcur->gilstate_counter;
1334 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 /* If we're going to destroy this thread-state, we must
1337 * clear it while the GIL is held, as destructors may run.
1338 */
1339 if (tcur->gilstate_counter == 0) {
1340 /* can't have been locked when we created it */
1341 assert(oldstate == PyGILState_UNLOCKED);
1342 PyThreadState_Clear(tcur);
1343 /* Delete the thread-state. Note this releases the GIL too!
1344 * It's vital that the GIL be held here, to avoid shutdown
1345 * races; see bugs 225673 and 1061968 (that nasty bug has a
1346 * habit of coming back).
1347 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001348 _PyThreadState_DeleteCurrent(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 }
1350 /* Release the lock if necessary */
1351 else if (oldstate == PyGILState_UNLOCKED)
1352 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001353}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001354
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001355
Eric Snow7f8bfc92018-01-29 18:23:44 -07001356/**************************/
1357/* cross-interpreter data */
1358/**************************/
1359
1360/* cross-interpreter data */
1361
1362crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1363
1364/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1365 to keep the registry code separate. */
1366static crossinterpdatafunc
1367_lookup_getdata(PyObject *obj)
1368{
1369 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1370 if (getdata == NULL && PyErr_Occurred() == 0)
1371 PyErr_Format(PyExc_ValueError,
1372 "%S does not support cross-interpreter data", obj);
1373 return getdata;
1374}
1375
1376int
1377_PyObject_CheckCrossInterpreterData(PyObject *obj)
1378{
1379 crossinterpdatafunc getdata = _lookup_getdata(obj);
1380 if (getdata == NULL) {
1381 return -1;
1382 }
1383 return 0;
1384}
1385
1386static int
1387_check_xidata(_PyCrossInterpreterData *data)
1388{
1389 // data->data can be anything, including NULL, so we don't check it.
1390
1391 // data->obj may be NULL, so we don't check it.
1392
1393 if (data->interp < 0) {
1394 PyErr_SetString(PyExc_SystemError, "missing interp");
1395 return -1;
1396 }
1397
1398 if (data->new_object == NULL) {
1399 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1400 return -1;
1401 }
1402
1403 // data->free may be NULL, so we don't check it.
1404
1405 return 0;
1406}
1407
1408int
1409_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1410{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001411 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001412 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001413 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001414
1415 // Reset data before re-populating.
1416 *data = (_PyCrossInterpreterData){0};
1417 data->free = PyMem_RawFree; // Set a default that may be overridden.
1418
1419 // Call the "getdata" func for the object.
1420 Py_INCREF(obj);
1421 crossinterpdatafunc getdata = _lookup_getdata(obj);
1422 if (getdata == NULL) {
1423 Py_DECREF(obj);
1424 return -1;
1425 }
1426 int res = getdata(obj, data);
1427 Py_DECREF(obj);
1428 if (res != 0) {
1429 return -1;
1430 }
1431
1432 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001433 data->interp = interp->id;
1434 if (_check_xidata(data) != 0) {
1435 _PyCrossInterpreterData_Release(data);
1436 return -1;
1437 }
1438
1439 return 0;
1440}
1441
Victor Stinnere225beb2019-06-03 18:14:24 +02001442static void
Eric Snow63799132018-06-01 18:45:20 -06001443_release_xidata(void *arg)
1444{
1445 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1446 if (data->free != NULL) {
1447 data->free(data->data);
1448 }
1449 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001450}
1451
1452static void
1453_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1454 PyInterpreterState *interp,
1455 void (*func)(void *), void *arg)
1456{
1457 /* We would use Py_AddPendingCall() if it weren't specific to the
1458 * main interpreter (see bpo-33608). In the meantime we take a
1459 * naive approach.
1460 */
1461 PyThreadState *save_tstate = NULL;
1462 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1463 // XXX Using the "head" thread isn't strictly correct.
1464 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1465 // XXX Possible GILState issues?
1466 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1467 }
1468
1469 func(arg);
1470
1471 // Switch back.
1472 if (save_tstate != NULL) {
1473 _PyThreadState_Swap(gilstate, save_tstate);
1474 }
Eric Snow63799132018-06-01 18:45:20 -06001475}
1476
Eric Snow7f8bfc92018-01-29 18:23:44 -07001477void
1478_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1479{
1480 if (data->data == NULL && data->obj == NULL) {
1481 // Nothing to release!
1482 return;
1483 }
1484
Victor Stinnere225beb2019-06-03 18:14:24 +02001485 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001486 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1487 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001488 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001489 if (data->free != NULL) {
1490 // XXX Someone leaked some memory...
1491 }
1492 return;
1493 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001494
Eric Snow7f8bfc92018-01-29 18:23:44 -07001495 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001496 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1497 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001498}
1499
1500PyObject *
1501_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1502{
1503 return data->new_object(data);
1504}
1505
1506/* registry of {type -> crossinterpdatafunc} */
1507
1508/* For now we use a global registry of shareable classes. An
1509 alternative would be to add a tp_* slot for a class's
1510 crossinterpdatafunc. It would be simpler and more efficient. */
1511
1512static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001513_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1514 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001515{
1516 // Note that we effectively replace already registered classes
1517 // rather than failing.
1518 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1519 if (newhead == NULL)
1520 return -1;
1521 newhead->cls = cls;
1522 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001523 newhead->next = xidregistry->head;
1524 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001525 return 0;
1526}
1527
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001528static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001529
1530int
Eric Snowc11183c2019-03-15 16:35:46 -06001531_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001532 crossinterpdatafunc getdata)
1533{
1534 if (!PyType_Check(cls)) {
1535 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1536 return -1;
1537 }
1538 if (getdata == NULL) {
1539 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1540 return -1;
1541 }
1542
1543 // Make sure the class isn't ever deallocated.
1544 Py_INCREF((PyObject *)cls);
1545
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001546 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1547 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1548 if (xidregistry->head == NULL) {
1549 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001550 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001551 int res = _register_xidata(xidregistry, cls, getdata);
1552 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001553 return res;
1554}
1555
Eric Snow6d2cd902018-05-16 15:04:57 -04001556/* Cross-interpreter objects are looked up by exact match on the class.
1557 We can reassess this policy when we move from a global registry to a
1558 tp_* slot. */
1559
Eric Snow7f8bfc92018-01-29 18:23:44 -07001560crossinterpdatafunc
1561_PyCrossInterpreterData_Lookup(PyObject *obj)
1562{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001563 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001564 PyObject *cls = PyObject_Type(obj);
1565 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001566 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1567 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001568 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001569 _register_builtins_for_crossinterpreter_data(xidregistry);
1570 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001571 }
1572 for(; cur != NULL; cur = cur->next) {
1573 if (cur->cls == (PyTypeObject *)cls) {
1574 getdata = cur->getdata;
1575 break;
1576 }
1577 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001578 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001579 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001580 return getdata;
1581}
1582
1583/* cross-interpreter data for builtin types */
1584
Eric Snow6d2cd902018-05-16 15:04:57 -04001585struct _shared_bytes_data {
1586 char *bytes;
1587 Py_ssize_t len;
1588};
1589
Eric Snow7f8bfc92018-01-29 18:23:44 -07001590static PyObject *
1591_new_bytes_object(_PyCrossInterpreterData *data)
1592{
Eric Snow6d2cd902018-05-16 15:04:57 -04001593 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1594 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001595}
1596
1597static int
1598_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1599{
Eric Snow6d2cd902018-05-16 15:04:57 -04001600 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1601 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1602 return -1;
1603 }
1604 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001605 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001606 data->obj = obj; // Will be "released" (decref'ed) when data released.
1607 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001608 data->free = PyMem_Free;
1609 return 0;
1610}
1611
1612struct _shared_str_data {
1613 int kind;
1614 const void *buffer;
1615 Py_ssize_t len;
1616};
1617
1618static PyObject *
1619_new_str_object(_PyCrossInterpreterData *data)
1620{
1621 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1622 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1623}
1624
1625static int
1626_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1627{
1628 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1629 shared->kind = PyUnicode_KIND(obj);
1630 shared->buffer = PyUnicode_DATA(obj);
1631 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1632 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001633 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001634 data->obj = obj; // Will be "released" (decref'ed) when data released.
1635 data->new_object = _new_str_object;
1636 data->free = PyMem_Free;
1637 return 0;
1638}
1639
1640static PyObject *
1641_new_long_object(_PyCrossInterpreterData *data)
1642{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001643 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001644}
1645
1646static int
1647_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1648{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001649 /* Note that this means the size of shareable ints is bounded by
1650 * sys.maxsize. Hence on 32-bit architectures that is half the
1651 * size of maximum shareable ints on 64-bit.
1652 */
1653 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001654 if (value == -1 && PyErr_Occurred()) {
1655 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1656 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1657 }
1658 return -1;
1659 }
1660 data->data = (void *)value;
1661 data->obj = NULL;
1662 data->new_object = _new_long_object;
1663 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001664 return 0;
1665}
1666
1667static PyObject *
1668_new_none_object(_PyCrossInterpreterData *data)
1669{
1670 // XXX Singleton refcounts are problematic across interpreters...
1671 Py_INCREF(Py_None);
1672 return Py_None;
1673}
1674
1675static int
1676_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1677{
1678 data->data = NULL;
1679 // data->obj remains NULL
1680 data->new_object = _new_none_object;
1681 data->free = NULL; // There is nothing to free.
1682 return 0;
1683}
1684
1685static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001686_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001687{
1688 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001689 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001690 Py_FatalError("could not register None for cross-interpreter sharing");
1691 }
1692
Eric Snow6d2cd902018-05-16 15:04:57 -04001693 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001694 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001695 Py_FatalError("could not register int for cross-interpreter sharing");
1696 }
1697
Eric Snow7f8bfc92018-01-29 18:23:44 -07001698 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001699 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001700 Py_FatalError("could not register bytes for cross-interpreter sharing");
1701 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001702
1703 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001704 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001705 Py_FatalError("could not register str for cross-interpreter sharing");
1706 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001707}
1708
1709
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001710#ifdef __cplusplus
1711}
1712#endif