blob: 4001c63ff25ee9ea319410797b3de730c145727b [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 Stinner9da74302019-11-20 11:17:17 +010042static void _PyThreadState_Delete(PyThreadState *tstate, int check_current);
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 _PyEval_Initialize(&runtime->ceval);
Victor Stinner441b10c2019-09-28 04:28:35 +020062
Victor Stinner3c30a762019-10-01 10:56:37 +020063 PyPreConfig_InitPythonConfig(&runtime->preconfig);
Michael W. Hudson188d4362005-06-20 16:52:57 +000064
Eric Snow2ebc5ce2017-09-07 23:51:28 -060065 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080066
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090067 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
68 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080069 Py_tss_t initial = Py_tss_NEEDS_INIT;
70 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000071
Eric Snow2ebc5ce2017-09-07 23:51:28 -060072 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080073 if (runtime->interpreters.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020074 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080075 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060076 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070077
78 runtime->xidregistry.mutex = PyThread_allocate_lock();
79 if (runtime->xidregistry.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020080 return _PyStatus_ERR("Can't initialize threads for cross-interpreter data registry");
Eric Snow7f8bfc92018-01-29 18:23:44 -070081 }
82
Eric Snow8479a342019-03-08 23:44:33 -070083 // Set it to the ID of the main thread of the main interpreter.
84 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070085
Victor Stinner331a6a52019-05-27 16:39:22 +020086 return _PyStatus_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060087}
Eric Snow05351c12017-09-05 21:43:08 -070088
Victor Stinner331a6a52019-05-27 16:39:22 +020089PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010090_PyRuntimeState_Init(_PyRuntimeState *runtime)
91{
92 /* Force default allocator, since _PyRuntimeState_Fini() must
93 use the same allocator than this function. */
94 PyMemAllocatorEx old_alloc;
95 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
96
Victor Stinner331a6a52019-05-27 16:39:22 +020097 PyStatus status = _PyRuntimeState_Init_impl(runtime);
Victor Stinner5d39e042017-11-29 17:20:38 +010098
99 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinner331a6a52019-05-27 16:39:22 +0200100 return status;
Victor Stinner5d39e042017-11-29 17:20:38 +0100101}
102
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600103void
104_PyRuntimeState_Fini(_PyRuntimeState *runtime)
105{
Victor Stinner5d39e042017-11-29 17:20:38 +0100106 /* Force the allocator used by _PyRuntimeState_Init(). */
107 PyMemAllocatorEx old_alloc;
108 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -0800109
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600110 if (runtime->interpreters.mutex != NULL) {
111 PyThread_free_lock(runtime->interpreters.mutex);
112 runtime->interpreters.mutex = NULL;
113 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800114
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100115 if (runtime->xidregistry.mutex != NULL) {
116 PyThread_free_lock(runtime->xidregistry.mutex);
117 runtime->xidregistry.mutex = NULL;
118 }
119
Victor Stinnerccb04422017-11-16 03:20:31 -0800120 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600121}
122
Eric Snow8479a342019-03-08 23:44:33 -0700123/* This function is called from PyOS_AfterFork_Child to ensure that
124 * newly created child processes do not share locks with the parent.
125 */
126
127void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200128_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700129{
130 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200131 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700132
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200133 /* Force default allocator, since _PyRuntimeState_Fini() must
134 use the same allocator than this function. */
135 PyMemAllocatorEx old_alloc;
136 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
137
138 runtime->interpreters.mutex = PyThread_allocate_lock();
139 runtime->interpreters.main->id_mutex = PyThread_allocate_lock();
140 runtime->xidregistry.mutex = PyThread_allocate_lock();
141
142 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
143
144 if (runtime->interpreters.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700145 Py_FatalError("Can't initialize lock for runtime interpreters");
146 }
147
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200148 if (runtime->interpreters.main->id_mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700149 Py_FatalError("Can't initialize ID lock for main interpreter");
150 }
151
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200152 if (runtime->xidregistry.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700153 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
154 }
155}
156
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200157#define HEAD_LOCK(runtime) \
158 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
159#define HEAD_UNLOCK(runtime) \
160 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700161
Victor Stinnerfff7bbf2019-11-20 17:34:39 +0100162int
163_Py_IsMainInterpreter(PyThreadState* tstate)
164{
165 return (tstate->interp == tstate->interp->runtime->interpreters.main);
166}
167
Victor Stinner8bb32302019-04-24 16:47:40 +0200168/* Forward declaration */
169static void _PyGILState_NoteThreadState(
170 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000171
Victor Stinner331a6a52019-05-27 16:39:22 +0200172PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600173_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700174{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200175 struct pyinterpreters *interpreters = &runtime->interpreters;
176 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100177
178 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
179 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200180 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100181 /* Force default allocator, since _PyRuntimeState_Fini() must
182 use the same allocator than this function. */
183 PyMemAllocatorEx old_alloc;
184 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
185
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200186 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100187
188 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
189
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200190 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200191 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800192 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600193 }
Victor Stinner5d926472018-03-06 14:31:37 +0100194
Victor Stinner331a6a52019-05-27 16:39:22 +0200195 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700196}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000197
198PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000199PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000200{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700201 if (PySys_Audit("cpython.PyInterpreterState_New", NULL) < 0) {
202 return NULL;
203 }
204
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200205 PyInterpreterState *interp = PyMem_RawMalloc(sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100206 if (interp == NULL) {
207 return NULL;
208 }
209
Eric Snow5be45a62019-03-08 22:47:07 -0700210 memset(interp, 0, sizeof(*interp));
Eric Snow4c6955e2018-02-16 18:53:40 -0700211 interp->id_refcount = -1;
Victor Stinner022be022019-05-22 23:58:50 +0200212
Victor Stinner01b1cc12019-11-20 02:27:56 +0100213 _PyRuntimeState *runtime = &_PyRuntime;
214 interp->runtime = runtime;
215
Victor Stinner72474072019-11-20 12:25:50 +0100216 _PyGC_InitState(&interp->gc);
Victor Stinner8462a492019-10-01 12:06:16 +0200217 PyConfig_InitPythonConfig(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200218
Victor Stinnerd4341102017-11-23 00:12:09 +0100219 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000220#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300221#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100222 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000223#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100224 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000225#endif
226#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000227
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200228 struct pyinterpreters *interpreters = &runtime->interpreters;
229
230 HEAD_LOCK(runtime);
231 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100232 /* overflow or Py_Initialize() not called! */
233 PyErr_SetString(PyExc_RuntimeError,
234 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100235 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100236 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100237 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200238 else {
239 interp->id = interpreters->next_id;
240 interpreters->next_id += 1;
241 interp->next = interpreters->head;
242 if (interpreters->main == NULL) {
243 interpreters->main = interp;
244 }
245 interpreters->head = interp;
246 }
247 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000248
Pablo Galindo95d630e2018-08-31 22:49:29 +0100249 if (interp == NULL) {
250 return NULL;
251 }
252
Yury Selivanovf23746a2018-01-22 19:11:18 -0500253 interp->tstate_next_unique_id = 0;
254
Steve Dowerb82e17e2019-05-23 08:45:22 -0700255 interp->audit_hooks = NULL;
256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000258}
259
260
Victor Stinner01b1cc12019-11-20 02:27:56 +0100261void
262PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000263{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100264 _PyRuntimeState *runtime = interp->runtime;
265
Steve Dowerb82e17e2019-05-23 08:45:22 -0700266 if (PySys_Audit("cpython.PyInterpreterState_Clear", NULL) < 0) {
267 PyErr_Clear();
268 }
269
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200270 HEAD_LOCK(runtime);
271 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200273 }
274 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700275
276 Py_CLEAR(interp->audit_hooks);
277
Victor Stinner331a6a52019-05-27 16:39:22 +0200278 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 Py_CLEAR(interp->codec_search_path);
280 Py_CLEAR(interp->codec_search_cache);
281 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700282 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 Py_CLEAR(interp->sysdict);
285 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200286 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400287 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300288 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600289 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200290#ifdef HAVE_FORK
291 Py_CLEAR(interp->before_forkers);
292 Py_CLEAR(interp->after_forkers_parent);
293 Py_CLEAR(interp->after_forkers_child);
294#endif
Eric Snow86ea5812019-05-10 13:29:55 -0400295 if (runtime->finalizing == NULL) {
296 _PyWarnings_Fini(interp);
297 }
Eric Snow5be45a62019-03-08 22:47:07 -0700298 // XXX Once we have one allocator per interpreter (i.e.
299 // per-interpreter GC) we must ensure that all of the interpreter's
300 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000301}
302
303
304static void
Victor Stinner9da74302019-11-20 11:17:17 +0100305zapthreads(PyInterpreterState *interp, int check_current)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000306{
Victor Stinner9da74302019-11-20 11:17:17 +0100307 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 /* No need to lock the mutex here because this should only happen
309 when the threads are all really dead (XXX famous last words). */
Victor Stinner9da74302019-11-20 11:17:17 +0100310 while ((tstate = interp->tstate_head) != NULL) {
311 _PyThreadState_Delete(tstate, check_current);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000313}
314
315
Victor Stinner01b1cc12019-11-20 02:27:56 +0100316void
317PyInterpreterState_Delete(PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200318{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100319 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200320 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner9da74302019-11-20 11:17:17 +0100321 zapthreads(interp, 0);
322
323 /* Delete current thread. After this, many C API calls become crashy. */
324 _PyThreadState_Swap(&runtime->gilstate, NULL);
325
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200326 HEAD_LOCK(runtime);
327 PyInterpreterState **p;
328 for (p = &interpreters->head; ; p = &(*p)->next) {
329 if (*p == NULL) {
330 Py_FatalError("PyInterpreterState_Delete: invalid interp");
331 }
332 if (*p == interp) {
333 break;
334 }
335 }
336 if (interp->tstate_head != NULL) {
337 Py_FatalError("PyInterpreterState_Delete: remaining threads");
338 }
339 *p = interp->next;
340 if (interpreters->main == interp) {
341 interpreters->main = NULL;
342 if (interpreters->head != NULL) {
343 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
344 }
345 }
346 HEAD_UNLOCK(runtime);
347 if (interp->id_mutex != NULL) {
348 PyThread_free_lock(interp->id_mutex);
349 }
350 PyMem_RawFree(interp);
351}
352
353
Eric Snow59032962018-09-14 14:17:20 -0700354/*
355 * Delete all interpreter states except the main interpreter. If there
356 * is a current interpreter state, it *must* be the main interpreter.
357 */
358void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200359_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700360{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200361 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200362 struct pyinterpreters *interpreters = &runtime->interpreters;
363
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200364 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200365 if (tstate != NULL && tstate->interp != interpreters->main) {
Eric Snow59032962018-09-14 14:17:20 -0700366 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
367 }
368
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200369 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200370 PyInterpreterState *interp = interpreters->head;
371 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100372 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200373 if (interp == interpreters->main) {
374 interpreters->main->next = NULL;
375 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100376 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700377 continue;
378 }
379
Victor Stinner01b1cc12019-11-20 02:27:56 +0100380 PyInterpreterState_Clear(interp); // XXX must activate?
Victor Stinner9da74302019-11-20 11:17:17 +0100381 zapthreads(interp, 1);
Eric Snow59032962018-09-14 14:17:20 -0700382 if (interp->id_mutex != NULL) {
383 PyThread_free_lock(interp->id_mutex);
384 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100385 PyInterpreterState *prev_interp = interp;
386 interp = interp->next;
387 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700388 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200389 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700390
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200391 if (interpreters->head == NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700392 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
393 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200394 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700395}
396
397
Victor Stinnercaba55b2018-08-03 15:33:52 +0200398PyInterpreterState *
399_PyInterpreterState_Get(void)
400{
Victor Stinner50b48572018-11-01 01:51:40 +0100401 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200402 if (tstate == NULL) {
403 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
404 }
405 PyInterpreterState *interp = tstate->interp;
406 if (interp == NULL) {
407 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
408 }
409 return interp;
410}
411
412
Eric Snowe3774162017-05-22 19:46:40 -0700413int64_t
414PyInterpreterState_GetID(PyInterpreterState *interp)
415{
416 if (interp == NULL) {
417 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
418 return -1;
419 }
420 return interp->id;
421}
422
423
Eric Snow5be45a62019-03-08 22:47:07 -0700424static PyInterpreterState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200425interp_look_up_id(_PyRuntimeState *runtime, PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700426{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200427 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100428 while (interp != NULL) {
429 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700430 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100431 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700432 }
433 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100434 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700435 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100436 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700437 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100438 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700439}
440
Eric Snow5be45a62019-03-08 22:47:07 -0700441PyInterpreterState *
442_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
443{
444 PyInterpreterState *interp = NULL;
445 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200446 _PyRuntimeState *runtime = &_PyRuntime;
447 HEAD_LOCK(runtime);
448 interp = interp_look_up_id(runtime, requested_id);
449 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700450 }
451 if (interp == NULL && !PyErr_Occurred()) {
452 PyErr_Format(PyExc_RuntimeError,
453 "unrecognized interpreter ID %lld", requested_id);
454 }
455 return interp;
456}
457
Eric Snow4c6955e2018-02-16 18:53:40 -0700458
459int
460_PyInterpreterState_IDInitref(PyInterpreterState *interp)
461{
462 if (interp->id_mutex != NULL) {
463 return 0;
464 }
465 interp->id_mutex = PyThread_allocate_lock();
466 if (interp->id_mutex == NULL) {
467 PyErr_SetString(PyExc_RuntimeError,
468 "failed to create init interpreter ID mutex");
469 return -1;
470 }
471 interp->id_refcount = 0;
472 return 0;
473}
474
475
476void
477_PyInterpreterState_IDIncref(PyInterpreterState *interp)
478{
479 if (interp->id_mutex == NULL) {
480 return;
481 }
482 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
483 interp->id_refcount += 1;
484 PyThread_release_lock(interp->id_mutex);
485}
486
487
488void
489_PyInterpreterState_IDDecref(PyInterpreterState *interp)
490{
491 if (interp->id_mutex == NULL) {
492 return;
493 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200494 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700495 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
496 assert(interp->id_refcount != 0);
497 interp->id_refcount -= 1;
498 int64_t refcount = interp->id_refcount;
499 PyThread_release_lock(interp->id_mutex);
500
Eric Snowc11183c2019-03-15 16:35:46 -0600501 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700502 // XXX Using the "head" thread isn't strictly correct.
503 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
504 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200505 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700506 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200507 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700508 }
509}
510
Eric Snowc11183c2019-03-15 16:35:46 -0600511int
512_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
513{
514 return interp->requires_idref;
515}
516
517void
518_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
519{
520 interp->requires_idref = required ? 1 : 0;
521}
522
Eric Snowc11183c2019-03-15 16:35:46 -0600523PyObject *
524_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
525{
526 if (interp->modules == NULL) {
527 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
528 return NULL;
529 }
530 return PyMapping_GetItemString(interp->modules, "__main__");
531}
532
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600533PyObject *
534PyInterpreterState_GetDict(PyInterpreterState *interp)
535{
536 if (interp->dict == NULL) {
537 interp->dict = PyDict_New();
538 if (interp->dict == NULL) {
539 PyErr_Clear();
540 }
541 }
542 /* Returning NULL means no per-interpreter dict is available. */
543 return interp->dict;
544}
545
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000546/* Default implementation for _PyThreadState_GetFrame */
547static struct _frame *
548threadstate_getframe(PyThreadState *self)
549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000551}
552
Victor Stinner45b9be52010-03-03 23:28:07 +0000553static PyThreadState *
554new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000555{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100556 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200557 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200558 if (tstate == NULL) {
559 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561
Victor Stinner8bb32302019-04-24 16:47:40 +0200562 if (_PyThreadState_GetFrame == NULL) {
563 _PyThreadState_GetFrame = threadstate_getframe;
564 }
565
566 tstate->interp = interp;
567
568 tstate->frame = NULL;
569 tstate->recursion_depth = 0;
570 tstate->overflowed = 0;
571 tstate->recursion_critical = 0;
572 tstate->stackcheck_counter = 0;
573 tstate->tracing = 0;
574 tstate->use_tracing = 0;
575 tstate->gilstate_counter = 0;
576 tstate->async_exc = NULL;
577 tstate->thread_id = PyThread_get_thread_ident();
578
579 tstate->dict = NULL;
580
581 tstate->curexc_type = NULL;
582 tstate->curexc_value = NULL;
583 tstate->curexc_traceback = NULL;
584
585 tstate->exc_state.exc_type = NULL;
586 tstate->exc_state.exc_value = NULL;
587 tstate->exc_state.exc_traceback = NULL;
588 tstate->exc_state.previous_item = NULL;
589 tstate->exc_info = &tstate->exc_state;
590
591 tstate->c_profilefunc = NULL;
592 tstate->c_tracefunc = NULL;
593 tstate->c_profileobj = NULL;
594 tstate->c_traceobj = NULL;
595
596 tstate->trash_delete_nesting = 0;
597 tstate->trash_delete_later = NULL;
598 tstate->on_delete = NULL;
599 tstate->on_delete_data = NULL;
600
601 tstate->coroutine_origin_tracking_depth = 0;
602
Victor Stinner8bb32302019-04-24 16:47:40 +0200603 tstate->async_gen_firstiter = NULL;
604 tstate->async_gen_finalizer = NULL;
605
606 tstate->context = NULL;
607 tstate->context_ver = 1;
608
Victor Stinner8bb32302019-04-24 16:47:40 +0200609 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100610 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200611 }
612
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200613 HEAD_LOCK(runtime);
Stefan Krahb3b9ade2020-03-02 21:22:36 +0100614 tstate->id = ++interp->tstate_next_unique_id;
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 Stinner01b1cc12019-11-20 02:27:56 +0100638_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000639{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100640 _PyGILState_NoteThreadState(&tstate->interp->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
Victor Stinner82c83bd2019-11-22 18:52:27 +0100663_PyState_AddModule(PyThreadState *tstate, PyObject* module, struct PyModuleDef* def)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000664{
Berker Peksag4b7b5652016-08-22 18:05:56 +0300665 if (!def) {
666 assert(PyErr_Occurred());
667 return -1;
668 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000669 if (def->m_slots) {
670 PyErr_SetString(PyExc_SystemError,
671 "PyState_AddModule called on module with slots");
672 return -1;
673 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100674
675 PyInterpreterState *interp = tstate->interp;
676 if (!interp->modules_by_index) {
677 interp->modules_by_index = PyList_New(0);
678 if (!interp->modules_by_index) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100680 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100682
683 while (PyList_GET_SIZE(interp->modules_by_index) <= def->m_base.m_index) {
684 if (PyList_Append(interp->modules_by_index, Py_None) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 return -1;
Victor Stinner82c83bd2019-11-22 18:52:27 +0100686 }
687 }
688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 Py_INCREF(module);
Victor Stinner82c83bd2019-11-22 18:52:27 +0100690 return PyList_SetItem(interp->modules_by_index,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000692}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000693
Martin v. Löwis7800f752012-06-22 12:20:55 +0200694int
695PyState_AddModule(PyObject* module, struct PyModuleDef* def)
696{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200697 if (!def) {
698 Py_FatalError("PyState_AddModule: Module Definition is NULL");
699 return -1;
700 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100701
702 PyThreadState *tstate = _PyThreadState_GET();
703 PyInterpreterState *interp = tstate->interp;
704 Py_ssize_t index = def->m_base.m_index;
705 if (interp->modules_by_index &&
706 index < PyList_GET_SIZE(interp->modules_by_index) &&
707 module == PyList_GET_ITEM(interp->modules_by_index, index))
708 {
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100709 Py_FatalError("PyState_AddModule: Module already added!");
710 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200711 }
Victor Stinner82c83bd2019-11-22 18:52:27 +0100712 return _PyState_AddModule(tstate, module, def);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200713}
714
715int
716PyState_RemoveModule(struct PyModuleDef* def)
717{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000718 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200719 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000720 if (def->m_slots) {
721 PyErr_SetString(PyExc_SystemError,
722 "PyState_RemoveModule called on module with slots");
723 return -1;
724 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100725 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200726 if (index == 0) {
727 Py_FatalError("PyState_RemoveModule: Module index invalid.");
728 return -1;
729 }
730 if (state->modules_by_index == NULL) {
Min ho Kim39d87b52019-08-31 06:21:19 +1000731 Py_FatalError("PyState_RemoveModule: Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200732 return -1;
733 }
734 if (index > PyList_GET_SIZE(state->modules_by_index)) {
735 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
736 return -1;
737 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700738 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200739 return PyList_SetItem(state->modules_by_index, index, Py_None);
740}
741
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200742/* Used by PyImport_Cleanup() */
Antoine Pitrou40322e62013-08-11 00:30:09 +0200743void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200744_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200745{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200746 if (!interp->modules_by_index) {
747 return;
748 }
749
750 Py_ssize_t i;
751 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
752 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
753 if (PyModule_Check(m)) {
754 /* cleanup the saved copy of module dicts */
755 PyModuleDef *md = PyModule_GetDef(m);
756 if (md) {
757 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200758 }
759 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200760 }
761
762 /* Setting modules_by_index to NULL could be dangerous, so we
763 clear the list instead. */
764 if (PyList_SetSlice(interp->modules_by_index,
765 0, PyList_GET_SIZE(interp->modules_by_index),
766 NULL)) {
767 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200768 }
769}
770
Guido van Rossuma027efa1997-05-05 20:56:21 +0000771void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000772PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000773{
Victor Stinner331a6a52019-05-27 16:39:22 +0200774 int verbose = tstate->interp->config.verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200775
776 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 fprintf(stderr,
778 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 Py_CLEAR(tstate->dict);
783 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 Py_CLEAR(tstate->curexc_type);
786 Py_CLEAR(tstate->curexc_value);
787 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000788
Mark Shannonae3087c2017-10-22 22:41:51 +0100789 Py_CLEAR(tstate->exc_state.exc_type);
790 Py_CLEAR(tstate->exc_state.exc_value);
791 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300792
Mark Shannonae3087c2017-10-22 22:41:51 +0100793 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200794 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100795 fprintf(stderr,
796 "PyThreadState_Clear: warning: thread still has a generator\n");
797 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 tstate->c_profilefunc = NULL;
800 tstate->c_tracefunc = NULL;
801 Py_CLEAR(tstate->c_profileobj);
802 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400803
Yury Selivanoveb636452016-09-08 22:01:51 -0700804 Py_CLEAR(tstate->async_gen_firstiter);
805 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500806
807 Py_CLEAR(tstate->context);
Victor Stinner4d96b462020-02-01 02:30:25 +0100808
809 if (tstate->on_delete != NULL) {
810 tstate->on_delete(tstate->on_delete_data);
811 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000812}
813
814
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300815/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000816static void
Victor Stinner9da74302019-11-20 11:17:17 +0100817tstate_delete_common(PyThreadState *tstate,
818 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000819{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100820 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200821 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 Py_FatalError("PyThreadState_Delete: NULL tstate");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200823 }
824 PyInterpreterState *interp = tstate->interp;
825 if (interp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 Py_FatalError("PyThreadState_Delete: NULL interp");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200827 }
828 HEAD_LOCK(runtime);
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200829 if (tstate->prev)
830 tstate->prev->next = tstate->next;
831 else
832 interp->tstate_head = tstate->next;
833 if (tstate->next)
834 tstate->next->prev = tstate->prev;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200835 HEAD_UNLOCK(runtime);
Victor Stinner4d96b462020-02-01 02:30:25 +0100836
Victor Stinner1a7425f2013-07-07 16:25:15 +0200837 PyMem_RawFree(tstate);
Victor Stinner9da74302019-11-20 11:17:17 +0100838
839 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)) {
853 Py_FatalError("PyThreadState_Delete: tstate is still current");
854 }
855 }
856 tstate_delete_common(tstate, gilstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000857}
858
859
Victor Stinner01b1cc12019-11-20 02:27:56 +0100860void
861PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000862{
Victor Stinner9da74302019-11-20 11:17:17 +0100863 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200864}
865
866
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300867void
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200868_PyThreadState_DeleteCurrent(_PyRuntimeState *runtime)
869{
870 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
871 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 if (tstate == NULL)
873 Py_FatalError(
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300874 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner9da74302019-11-20 11:17:17 +0100875 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200876 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000878}
Guido van Rossum29757862001-01-23 01:46:06 +0000879
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300880void
881PyThreadState_DeleteCurrent(void)
882{
883 _PyThreadState_DeleteCurrent(&_PyRuntime);
884}
885
Guido van Rossum29757862001-01-23 01:46:06 +0000886
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200887/*
888 * Delete all thread states except the one passed as argument.
889 * Note that, if there is a current thread state, it *must* be the one
890 * passed as argument. Also, this won't touch any other interpreters
891 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000892 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200893 */
894void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200895_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200896{
897 PyInterpreterState *interp = tstate->interp;
898 PyThreadState *p, *next, *garbage;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200899 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200900 /* Remove all thread states, except tstate, from the linked list of
901 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200902 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200903 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200904 if (garbage == tstate)
905 garbage = tstate->next;
906 if (tstate->prev)
907 tstate->prev->next = tstate->next;
908 if (tstate->next)
909 tstate->next->prev = tstate->prev;
910 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200911 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200912 HEAD_UNLOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200913 /* Clear and deallocate all stale thread states. Even if this
914 executes Python code, we should be safe since it executes
915 in the current thread, not one of the stale threads. */
916 for (p = garbage; p; p = next) {
917 next = p->next;
918 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200919 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200920 }
921}
922
923
Guido van Rossuma027efa1997-05-05 20:56:21 +0000924PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100925_PyThreadState_UncheckedGet(void)
926{
Victor Stinner50b48572018-11-01 01:51:40 +0100927 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100928}
929
930
931PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000932PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000933{
Victor Stinner50b48572018-11-01 01:51:40 +0100934 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 if (tstate == NULL)
936 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000939}
940
941
Victor Stinner09532fe2019-05-10 23:39:09 +0200942PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200943_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000944{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200945 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000946
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200947 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* It should not be possible for more than one thread state
949 to be used for a thread. Check this the best we can in debug
950 builds.
951 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200952#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 if (newts) {
954 /* This can be called from PyEval_RestoreThread(). Similar
955 to it, we need to ensure errno doesn't change.
956 */
957 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200958 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 if (check && check->interp == newts->interp && check != newts)
960 Py_FatalError("Invalid thread state for this thread");
961 errno = err;
962 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000963#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000965}
Guido van Rossumede04391998-04-10 20:18:25 +0000966
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200967PyThreadState *
968PyThreadState_Swap(PyThreadState *newts)
969{
970 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
971}
972
Guido van Rossumede04391998-04-10 20:18:25 +0000973/* An extension mechanism to store arbitrary additional per-thread state.
974 PyThreadState_GetDict() returns a dictionary that can be used to hold such
975 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000976 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
977 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000978
979PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000980PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000981{
Victor Stinner50b48572018-11-01 01:51:40 +0100982 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 if (tstate == NULL)
984 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (tstate->dict == NULL) {
987 PyObject *d;
988 tstate->dict = d = PyDict_New();
989 if (d == NULL)
990 PyErr_Clear();
991 }
992 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000993}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000994
995
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000996/* Asynchronously raise an exception in a thread.
997 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000998 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000999 to call this, or use ctypes. Must be called with the GIL held.
1000 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1001 match any known thread id). Can be called with exc=NULL to clear an
1002 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001003
1004int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001005PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1006{
Victor Stinner09532fe2019-05-10 23:39:09 +02001007 _PyRuntimeState *runtime = &_PyRuntime;
1008 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 /* Although the GIL is held, a few C API functions can be called
1011 * without the GIL held, and in particular some that create and
1012 * destroy thread and interpreter states. Those can mutate the
1013 * list of thread states we're traversing, so to prevent that we lock
1014 * head_mutex for the duration.
1015 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001016 HEAD_LOCK(runtime);
Victor Stinner09532fe2019-05-10 23:39:09 +02001017 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 if (p->thread_id == id) {
1019 /* Tricky: we need to decref the current value
1020 * (if any) in p->async_exc, but that can in turn
1021 * allow arbitrary Python code to run, including
1022 * perhaps calls to this function. To prevent
1023 * deadlock, we need to release head_mutex before
1024 * the decref.
1025 */
1026 PyObject *old_exc = p->async_exc;
1027 Py_XINCREF(exc);
1028 p->async_exc = exc;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001029 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 Py_XDECREF(old_exc);
Victor Stinnere225beb2019-06-03 18:14:24 +02001031 _PyEval_SignalAsyncExc(&runtime->ceval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 return 1;
1033 }
1034 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001035 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001037}
1038
1039
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001040/* Routines for advanced debuggers, requested by David Beazley.
1041 Don't use unless you know what you are doing! */
1042
1043PyInterpreterState *
1044PyInterpreterState_Head(void)
1045{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001046 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001047}
1048
1049PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001050PyInterpreterState_Main(void)
1051{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001052 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001053}
1054
1055PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001056PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001058}
1059
1060PyThreadState *
1061PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001063}
1064
1065PyThreadState *
1066PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001068}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001069
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001070/* The implementation of sys._current_frames(). This is intended to be
1071 called with the GIL held, as it will be when called via
1072 sys._current_frames(). It's possible it would work fine even without
1073 the GIL held, but haven't thought enough about that.
1074*/
1075PyObject *
1076_PyThread_CurrentFrames(void)
1077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 PyObject *result;
1079 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001080
Steve Dowerb82e17e2019-05-23 08:45:22 -07001081 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1082 return NULL;
1083 }
1084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 result = PyDict_New();
1086 if (result == NULL)
1087 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 /* for i in all interpreters:
1090 * for t in all of i's thread states:
1091 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001092 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 * need to grab head_mutex for the duration.
1094 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001095 _PyRuntimeState *runtime = &_PyRuntime;
1096 HEAD_LOCK(runtime);
1097 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyThreadState *t;
1099 for (t = i->tstate_head; t != NULL; t = t->next) {
1100 PyObject *id;
1101 int stat;
1102 struct _frame *frame = t->frame;
1103 if (frame == NULL)
1104 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001105 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (id == NULL)
1107 goto Fail;
1108 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1109 Py_DECREF(id);
1110 if (stat < 0)
1111 goto Fail;
1112 }
1113 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001114 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001116
1117 Fail:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001118 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 Py_DECREF(result);
1120 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001121}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001122
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001123/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001124
1125/* Keep this as a static, as it is not reliable! It can only
1126 ever be compared to the state for the *current* thread.
1127 * If not equal, then it doesn't matter that the actual
1128 value may change immediately after comparison, as it can't
1129 possibly change to the current thread's state.
1130 * If equal, then the current thread holds the lock, so the value can't
1131 change until we yield the lock.
1132*/
1133static int
1134PyThreadState_IsCurrent(PyThreadState *tstate)
1135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001137 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001138 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1139 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001140}
1141
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001142/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001143 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001144*/
Tim Peters19717fa2004-10-09 17:38:29 +00001145void
Victor Stinner01b1cc12019-11-20 02:27:56 +01001146_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001147{
Victor Stinner8bb32302019-04-24 16:47:40 +02001148 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001149 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001150 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001151
Victor Stinner01b1cc12019-11-20 02:27:56 +01001152 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001153
1154 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001155 Py_FatalError("Could not allocate TSS entry");
1156 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001157 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001158 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1159 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001160
Victor Stinner8bb32302019-04-24 16:47:40 +02001161 _PyGILState_NoteThreadState(gilstate, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001162}
1163
Victor Stinner861d9ab2016-03-16 22:45:24 +01001164PyInterpreterState *
1165_PyGILState_GetInterpreterStateUnsafe(void)
1166{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001167 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001168}
1169
Tim Peters19717fa2004-10-09 17:38:29 +00001170void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001171_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001172{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001173 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001174 PyThread_tss_delete(&gilstate->autoTSSkey);
1175 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001176}
1177
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001178/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001179 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001180 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001181 */
1182void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001183_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001184{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001185 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001186 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001187
1188 PyThread_tss_delete(&gilstate->autoTSSkey);
1189 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001190 Py_FatalError("Could not allocate TSS entry");
1191 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001192
Charles-François Natalia233df82011-11-22 19:49:51 +01001193 /* If the thread had an associated auto thread state, reassociate it with
1194 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001195 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001196 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001197 {
1198 Py_FatalError("Couldn't create autoTSSkey mapping");
1199 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001200}
1201
Michael W. Hudson188d4362005-06-20 16:52:57 +00001202/* When a thread state is created for a thread by some mechanism other than
1203 PyGILState_Ensure, it's important that the GILState machinery knows about
1204 it so it doesn't try to create another thread state for the thread (this is
1205 a better fix for SF bug #1010677 than the first one attempted).
1206*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001207static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001208_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001209{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001210 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001211 threadstate created in Py_Initialize(). Don't do anything for now
1212 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001213 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001215 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001216
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001217 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 The only situation where you can legitimately have more than one
1220 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001221 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001222
Victor Stinner590cebe2013-12-13 11:08:56 +01001223 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1224 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001225
Victor Stinner590cebe2013-12-13 11:08:56 +01001226 The first thread state created for that given OS level thread will
1227 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001229 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1230 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001231 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001232 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001233 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 /* PyGILState_Release must not try to delete this thread state. */
1236 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001237}
1238
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001239/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001240static PyThreadState *
1241_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1242{
1243 if (gilstate->autoInterpreterState == NULL)
1244 return NULL;
1245 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1246}
1247
Tim Peters19717fa2004-10-09 17:38:29 +00001248PyThreadState *
1249PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001250{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001251 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001252}
1253
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001254int
1255PyGILState_Check(void)
1256{
Victor Stinner8a1be612016-03-14 22:07:55 +01001257
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001258 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001259 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001260 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001261
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001262 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1263 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1264 return 1;
1265 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001266
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001267 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1268 if (tstate == NULL) {
1269 return 0;
1270 }
1271
1272 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001273}
1274
Tim Peters19717fa2004-10-09 17:38:29 +00001275PyGILState_STATE
1276PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001277{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001278 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 int current;
1280 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001281 int need_init_threads = 0;
1282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 /* Note that we do not auto-init Python here - apart from
1284 potential races with 2 threads auto-initializing, pep-311
1285 spells out other issues. Embedders are expected to have
1286 called Py_Initialize() and usually PyEval_InitThreads().
1287 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001288 /* Py_Initialize() hasn't been called! */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001289 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001290
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001291 tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001293 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 /* Create a new thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001296 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 if (tcur == NULL)
1298 Py_FatalError("Couldn't create thread-state for new thread");
1299 /* This is our thread state! We'll need to delete it in the
1300 matching call to PyGILState_Release(). */
1301 tcur->gilstate_counter = 0;
1302 current = 0; /* new thread state is never current */
1303 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001304 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001306 }
1307
1308 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001310 }
1311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 /* Update our counter in the thread-state - no need for locks:
1313 - tcur will remain valid as we hold the GIL.
1314 - the counter is safe as we are the only thread "allowed"
1315 to modify this value
1316 */
1317 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001318
1319 if (need_init_threads) {
1320 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1321 called from a new thread for the first time, we need the create the
1322 GIL. */
1323 PyEval_InitThreads();
1324 }
1325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001327}
1328
Tim Peters19717fa2004-10-09 17:38:29 +00001329void
1330PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001331{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001332 _PyRuntimeState *runtime = &_PyRuntime;
1333 PyThreadState *tcur = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1334 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 Py_FatalError("auto-releasing thread-state, "
1336 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001337 }
1338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 /* We must hold the GIL and have our thread state current */
1340 /* XXX - remove the check - the assert should be fine,
1341 but while this is very new (April 2003), the extra check
1342 by release-only users can't hurt.
1343 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001344 if (!PyThreadState_IsCurrent(tcur)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 Py_FatalError("This thread state must be current when releasing");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001346 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 assert(PyThreadState_IsCurrent(tcur));
1348 --tcur->gilstate_counter;
1349 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 /* If we're going to destroy this thread-state, we must
1352 * clear it while the GIL is held, as destructors may run.
1353 */
1354 if (tcur->gilstate_counter == 0) {
1355 /* can't have been locked when we created it */
1356 assert(oldstate == PyGILState_UNLOCKED);
1357 PyThreadState_Clear(tcur);
1358 /* Delete the thread-state. Note this releases the GIL too!
1359 * It's vital that the GIL be held here, to avoid shutdown
1360 * races; see bugs 225673 and 1061968 (that nasty bug has a
1361 * habit of coming back).
1362 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001363 _PyThreadState_DeleteCurrent(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 }
1365 /* Release the lock if necessary */
1366 else if (oldstate == PyGILState_UNLOCKED)
1367 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001368}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001369
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001370
Eric Snow7f8bfc92018-01-29 18:23:44 -07001371/**************************/
1372/* cross-interpreter data */
1373/**************************/
1374
1375/* cross-interpreter data */
1376
1377crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1378
1379/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1380 to keep the registry code separate. */
1381static crossinterpdatafunc
1382_lookup_getdata(PyObject *obj)
1383{
1384 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1385 if (getdata == NULL && PyErr_Occurred() == 0)
1386 PyErr_Format(PyExc_ValueError,
1387 "%S does not support cross-interpreter data", obj);
1388 return getdata;
1389}
1390
1391int
1392_PyObject_CheckCrossInterpreterData(PyObject *obj)
1393{
1394 crossinterpdatafunc getdata = _lookup_getdata(obj);
1395 if (getdata == NULL) {
1396 return -1;
1397 }
1398 return 0;
1399}
1400
1401static int
1402_check_xidata(_PyCrossInterpreterData *data)
1403{
1404 // data->data can be anything, including NULL, so we don't check it.
1405
1406 // data->obj may be NULL, so we don't check it.
1407
1408 if (data->interp < 0) {
1409 PyErr_SetString(PyExc_SystemError, "missing interp");
1410 return -1;
1411 }
1412
1413 if (data->new_object == NULL) {
1414 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1415 return -1;
1416 }
1417
1418 // data->free may be NULL, so we don't check it.
1419
1420 return 0;
1421}
1422
1423int
1424_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1425{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001426 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001427 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001428 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001429
1430 // Reset data before re-populating.
1431 *data = (_PyCrossInterpreterData){0};
1432 data->free = PyMem_RawFree; // Set a default that may be overridden.
1433
1434 // Call the "getdata" func for the object.
1435 Py_INCREF(obj);
1436 crossinterpdatafunc getdata = _lookup_getdata(obj);
1437 if (getdata == NULL) {
1438 Py_DECREF(obj);
1439 return -1;
1440 }
1441 int res = getdata(obj, data);
1442 Py_DECREF(obj);
1443 if (res != 0) {
1444 return -1;
1445 }
1446
1447 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001448 data->interp = interp->id;
1449 if (_check_xidata(data) != 0) {
1450 _PyCrossInterpreterData_Release(data);
1451 return -1;
1452 }
1453
1454 return 0;
1455}
1456
Victor Stinnere225beb2019-06-03 18:14:24 +02001457static void
Eric Snow63799132018-06-01 18:45:20 -06001458_release_xidata(void *arg)
1459{
1460 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1461 if (data->free != NULL) {
1462 data->free(data->data);
1463 }
1464 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001465}
1466
1467static void
1468_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1469 PyInterpreterState *interp,
1470 void (*func)(void *), void *arg)
1471{
1472 /* We would use Py_AddPendingCall() if it weren't specific to the
1473 * main interpreter (see bpo-33608). In the meantime we take a
1474 * naive approach.
1475 */
1476 PyThreadState *save_tstate = NULL;
1477 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1478 // XXX Using the "head" thread isn't strictly correct.
1479 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1480 // XXX Possible GILState issues?
1481 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1482 }
1483
1484 func(arg);
1485
1486 // Switch back.
1487 if (save_tstate != NULL) {
1488 _PyThreadState_Swap(gilstate, save_tstate);
1489 }
Eric Snow63799132018-06-01 18:45:20 -06001490}
1491
Eric Snow7f8bfc92018-01-29 18:23:44 -07001492void
1493_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1494{
1495 if (data->data == NULL && data->obj == NULL) {
1496 // Nothing to release!
1497 return;
1498 }
1499
Victor Stinnere225beb2019-06-03 18:14:24 +02001500 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001501 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1502 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001503 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001504 if (data->free != NULL) {
1505 // XXX Someone leaked some memory...
1506 }
1507 return;
1508 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001509
Eric Snow7f8bfc92018-01-29 18:23:44 -07001510 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001511 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1512 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001513}
1514
1515PyObject *
1516_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1517{
1518 return data->new_object(data);
1519}
1520
1521/* registry of {type -> crossinterpdatafunc} */
1522
1523/* For now we use a global registry of shareable classes. An
1524 alternative would be to add a tp_* slot for a class's
1525 crossinterpdatafunc. It would be simpler and more efficient. */
1526
1527static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001528_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1529 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001530{
1531 // Note that we effectively replace already registered classes
1532 // rather than failing.
1533 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1534 if (newhead == NULL)
1535 return -1;
1536 newhead->cls = cls;
1537 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001538 newhead->next = xidregistry->head;
1539 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001540 return 0;
1541}
1542
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001543static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001544
1545int
Eric Snowc11183c2019-03-15 16:35:46 -06001546_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001547 crossinterpdatafunc getdata)
1548{
1549 if (!PyType_Check(cls)) {
1550 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1551 return -1;
1552 }
1553 if (getdata == NULL) {
1554 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1555 return -1;
1556 }
1557
1558 // Make sure the class isn't ever deallocated.
1559 Py_INCREF((PyObject *)cls);
1560
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001561 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1562 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1563 if (xidregistry->head == NULL) {
1564 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001565 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001566 int res = _register_xidata(xidregistry, cls, getdata);
1567 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001568 return res;
1569}
1570
Eric Snow6d2cd902018-05-16 15:04:57 -04001571/* Cross-interpreter objects are looked up by exact match on the class.
1572 We can reassess this policy when we move from a global registry to a
1573 tp_* slot. */
1574
Eric Snow7f8bfc92018-01-29 18:23:44 -07001575crossinterpdatafunc
1576_PyCrossInterpreterData_Lookup(PyObject *obj)
1577{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001578 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001579 PyObject *cls = PyObject_Type(obj);
1580 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001581 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1582 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001583 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001584 _register_builtins_for_crossinterpreter_data(xidregistry);
1585 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001586 }
1587 for(; cur != NULL; cur = cur->next) {
1588 if (cur->cls == (PyTypeObject *)cls) {
1589 getdata = cur->getdata;
1590 break;
1591 }
1592 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001593 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001594 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001595 return getdata;
1596}
1597
1598/* cross-interpreter data for builtin types */
1599
Eric Snow6d2cd902018-05-16 15:04:57 -04001600struct _shared_bytes_data {
1601 char *bytes;
1602 Py_ssize_t len;
1603};
1604
Eric Snow7f8bfc92018-01-29 18:23:44 -07001605static PyObject *
1606_new_bytes_object(_PyCrossInterpreterData *data)
1607{
Eric Snow6d2cd902018-05-16 15:04:57 -04001608 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1609 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001610}
1611
1612static int
1613_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1614{
Eric Snow6d2cd902018-05-16 15:04:57 -04001615 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1616 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1617 return -1;
1618 }
1619 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001620 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001621 data->obj = obj; // Will be "released" (decref'ed) when data released.
1622 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001623 data->free = PyMem_Free;
1624 return 0;
1625}
1626
1627struct _shared_str_data {
1628 int kind;
1629 const void *buffer;
1630 Py_ssize_t len;
1631};
1632
1633static PyObject *
1634_new_str_object(_PyCrossInterpreterData *data)
1635{
1636 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1637 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1638}
1639
1640static int
1641_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1642{
1643 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1644 shared->kind = PyUnicode_KIND(obj);
1645 shared->buffer = PyUnicode_DATA(obj);
1646 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1647 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001648 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001649 data->obj = obj; // Will be "released" (decref'ed) when data released.
1650 data->new_object = _new_str_object;
1651 data->free = PyMem_Free;
1652 return 0;
1653}
1654
1655static PyObject *
1656_new_long_object(_PyCrossInterpreterData *data)
1657{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001658 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001659}
1660
1661static int
1662_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1663{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001664 /* Note that this means the size of shareable ints is bounded by
1665 * sys.maxsize. Hence on 32-bit architectures that is half the
1666 * size of maximum shareable ints on 64-bit.
1667 */
1668 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001669 if (value == -1 && PyErr_Occurred()) {
1670 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1671 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1672 }
1673 return -1;
1674 }
1675 data->data = (void *)value;
1676 data->obj = NULL;
1677 data->new_object = _new_long_object;
1678 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001679 return 0;
1680}
1681
1682static PyObject *
1683_new_none_object(_PyCrossInterpreterData *data)
1684{
1685 // XXX Singleton refcounts are problematic across interpreters...
1686 Py_INCREF(Py_None);
1687 return Py_None;
1688}
1689
1690static int
1691_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1692{
1693 data->data = NULL;
1694 // data->obj remains NULL
1695 data->new_object = _new_none_object;
1696 data->free = NULL; // There is nothing to free.
1697 return 0;
1698}
1699
1700static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001701_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001702{
1703 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001704 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001705 Py_FatalError("could not register None for cross-interpreter sharing");
1706 }
1707
Eric Snow6d2cd902018-05-16 15:04:57 -04001708 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001709 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001710 Py_FatalError("could not register int for cross-interpreter sharing");
1711 }
1712
Eric Snow7f8bfc92018-01-29 18:23:44 -07001713 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001714 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001715 Py_FatalError("could not register bytes for cross-interpreter sharing");
1716 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001717
1718 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001719 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001720 Py_FatalError("could not register str for cross-interpreter sharing");
1721 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001722}
1723
1724
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001725#ifdef __cplusplus
1726}
1727#endif