blob: 0f0cb22995577869b37e3b82064ecc0f1daaf9b8 [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
64 runtime->preconfig.struct_size = sizeof(PyPreConfig);
65 PyStatus status = PyPreConfig_InitPythonConfig(&runtime->preconfig);
66 if (_PyStatus_EXCEPTION(status)) {
67 return status;
68 }
Michael W. Hudson188d4362005-06-20 16:52:57 +000069
Eric Snow2ebc5ce2017-09-07 23:51:28 -060070 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080071
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090072 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
73 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080074 Py_tss_t initial = Py_tss_NEEDS_INIT;
75 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000076
Eric Snow2ebc5ce2017-09-07 23:51:28 -060077 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080078 if (runtime->interpreters.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020079 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080080 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060081 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070082
83 runtime->xidregistry.mutex = PyThread_allocate_lock();
84 if (runtime->xidregistry.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020085 return _PyStatus_ERR("Can't initialize threads for cross-interpreter data registry");
Eric Snow7f8bfc92018-01-29 18:23:44 -070086 }
87
Eric Snow8479a342019-03-08 23:44:33 -070088 // Set it to the ID of the main thread of the main interpreter.
89 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070090
Victor Stinner331a6a52019-05-27 16:39:22 +020091 return _PyStatus_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060092}
Eric Snow05351c12017-09-05 21:43:08 -070093
Victor Stinner331a6a52019-05-27 16:39:22 +020094PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010095_PyRuntimeState_Init(_PyRuntimeState *runtime)
96{
97 /* Force default allocator, since _PyRuntimeState_Fini() must
98 use the same allocator than this function. */
99 PyMemAllocatorEx old_alloc;
100 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
101
Victor Stinner331a6a52019-05-27 16:39:22 +0200102 PyStatus status = _PyRuntimeState_Init_impl(runtime);
Victor Stinner5d39e042017-11-29 17:20:38 +0100103
104 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinner331a6a52019-05-27 16:39:22 +0200105 return status;
Victor Stinner5d39e042017-11-29 17:20:38 +0100106}
107
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600108void
109_PyRuntimeState_Fini(_PyRuntimeState *runtime)
110{
Victor Stinner5d39e042017-11-29 17:20:38 +0100111 /* Force the allocator used by _PyRuntimeState_Init(). */
112 PyMemAllocatorEx old_alloc;
113 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -0800114
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600115 if (runtime->interpreters.mutex != NULL) {
116 PyThread_free_lock(runtime->interpreters.mutex);
117 runtime->interpreters.mutex = NULL;
118 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800119
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100120 if (runtime->xidregistry.mutex != NULL) {
121 PyThread_free_lock(runtime->xidregistry.mutex);
122 runtime->xidregistry.mutex = NULL;
123 }
124
Victor Stinnerccb04422017-11-16 03:20:31 -0800125 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600126}
127
Eric Snow8479a342019-03-08 23:44:33 -0700128/* This function is called from PyOS_AfterFork_Child to ensure that
129 * newly created child processes do not share locks with the parent.
130 */
131
132void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200133_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700134{
135 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200136 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700137
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200138 /* Force default allocator, since _PyRuntimeState_Fini() must
139 use the same allocator than this function. */
140 PyMemAllocatorEx old_alloc;
141 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
142
143 runtime->interpreters.mutex = PyThread_allocate_lock();
144 runtime->interpreters.main->id_mutex = PyThread_allocate_lock();
145 runtime->xidregistry.mutex = PyThread_allocate_lock();
146
147 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
148
149 if (runtime->interpreters.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700150 Py_FatalError("Can't initialize lock for runtime interpreters");
151 }
152
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200153 if (runtime->interpreters.main->id_mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700154 Py_FatalError("Can't initialize ID lock for main interpreter");
155 }
156
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200157 if (runtime->xidregistry.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700158 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
159 }
160}
161
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200162#define HEAD_LOCK(runtime) \
163 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
164#define HEAD_UNLOCK(runtime) \
165 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700166
Victor Stinner8bb32302019-04-24 16:47:40 +0200167/* Forward declaration */
168static void _PyGILState_NoteThreadState(
169 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000170
Victor Stinner331a6a52019-05-27 16:39:22 +0200171PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600172_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700173{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200174 struct pyinterpreters *interpreters = &runtime->interpreters;
175 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100176
177 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
178 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200179 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100180 /* Force default allocator, since _PyRuntimeState_Fini() must
181 use the same allocator than this function. */
182 PyMemAllocatorEx old_alloc;
183 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
184
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200185 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100186
187 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
188
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200189 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200190 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800191 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600192 }
Victor Stinner5d926472018-03-06 14:31:37 +0100193
Victor Stinner331a6a52019-05-27 16:39:22 +0200194 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700195}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000196
197PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000198PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000199{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700200 if (PySys_Audit("cpython.PyInterpreterState_New", NULL) < 0) {
201 return NULL;
202 }
203
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200204 PyInterpreterState *interp = PyMem_RawMalloc(sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100205 if (interp == NULL) {
206 return NULL;
207 }
208
Eric Snow5be45a62019-03-08 22:47:07 -0700209 memset(interp, 0, sizeof(*interp));
Eric Snow4c6955e2018-02-16 18:53:40 -0700210 interp->id_refcount = -1;
Victor Stinner022be022019-05-22 23:58:50 +0200211
Victor Stinner441b10c2019-09-28 04:28:35 +0200212 interp->config.struct_size = sizeof(PyConfig);
Victor Stinner331a6a52019-05-27 16:39:22 +0200213 PyStatus status = PyConfig_InitPythonConfig(&interp->config);
214 if (_PyStatus_EXCEPTION(status)) {
215 /* Don't report status to caller: PyConfig_InitPythonConfig()
216 can only fail with a memory allocation error. */
217 PyConfig_Clear(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200218 PyMem_RawFree(interp);
219 return NULL;
220 }
221
Victor Stinnerd4341102017-11-23 00:12:09 +0100222 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000223#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300224#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100225 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000226#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100227 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000228#endif
229#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000230
Victor Stinner0fd2c302019-06-04 03:15:09 +0200231 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200232 struct pyinterpreters *interpreters = &runtime->interpreters;
233
234 HEAD_LOCK(runtime);
235 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100236 /* overflow or Py_Initialize() not called! */
237 PyErr_SetString(PyExc_RuntimeError,
238 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100239 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100240 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100241 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200242 else {
243 interp->id = interpreters->next_id;
244 interpreters->next_id += 1;
245 interp->next = interpreters->head;
246 if (interpreters->main == NULL) {
247 interpreters->main = interp;
248 }
249 interpreters->head = interp;
250 }
251 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000252
Pablo Galindo95d630e2018-08-31 22:49:29 +0100253 if (interp == NULL) {
254 return NULL;
255 }
256
Yury Selivanovf23746a2018-01-22 19:11:18 -0500257 interp->tstate_next_unique_id = 0;
258
Steve Dowerb82e17e2019-05-23 08:45:22 -0700259 interp->audit_hooks = NULL;
260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000262}
263
264
Victor Stinner0fd2c302019-06-04 03:15:09 +0200265static void
266_PyInterpreterState_Clear(_PyRuntimeState *runtime, PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000267{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700268 if (PySys_Audit("cpython.PyInterpreterState_Clear", NULL) < 0) {
269 PyErr_Clear();
270 }
271
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200272 HEAD_LOCK(runtime);
273 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200275 }
276 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700277
278 Py_CLEAR(interp->audit_hooks);
279
Victor Stinner331a6a52019-05-27 16:39:22 +0200280 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 Py_CLEAR(interp->codec_search_path);
282 Py_CLEAR(interp->codec_search_cache);
283 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700284 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 Py_CLEAR(interp->sysdict);
287 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200288 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400289 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300290 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600291 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200292#ifdef HAVE_FORK
293 Py_CLEAR(interp->before_forkers);
294 Py_CLEAR(interp->after_forkers_parent);
295 Py_CLEAR(interp->after_forkers_child);
296#endif
Eric Snow86ea5812019-05-10 13:29:55 -0400297 if (runtime->finalizing == NULL) {
298 _PyWarnings_Fini(interp);
299 }
Eric Snow5be45a62019-03-08 22:47:07 -0700300 // XXX Once we have one allocator per interpreter (i.e.
301 // per-interpreter GC) we must ensure that all of the interpreter's
302 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000303}
304
Victor Stinner0fd2c302019-06-04 03:15:09 +0200305void
306PyInterpreterState_Clear(PyInterpreterState *interp)
307{
308 _PyInterpreterState_Clear(&_PyRuntime, interp);
309}
310
Guido van Rossum25ce5661997-08-02 03:10:38 +0000311
312static void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200313zapthreads(_PyRuntimeState *runtime, PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000314{
Victor Stinner0fd2c302019-06-04 03:15:09 +0200315 PyThreadState *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 /* No need to lock the mutex here because this should only happen
317 when the threads are all really dead (XXX famous last words). */
Victor Stinner0fd2c302019-06-04 03:15:09 +0200318 while ((p = interp->tstate_head) != NULL) {
319 _PyThreadState_Delete(runtime, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000321}
322
323
Victor Stinner0fd2c302019-06-04 03:15:09 +0200324static void
325_PyInterpreterState_Delete(_PyRuntimeState *runtime,
326 PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200327{
328 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner0fd2c302019-06-04 03:15:09 +0200329 zapthreads(runtime, interp);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200330 HEAD_LOCK(runtime);
331 PyInterpreterState **p;
332 for (p = &interpreters->head; ; p = &(*p)->next) {
333 if (*p == NULL) {
334 Py_FatalError("PyInterpreterState_Delete: invalid interp");
335 }
336 if (*p == interp) {
337 break;
338 }
339 }
340 if (interp->tstate_head != NULL) {
341 Py_FatalError("PyInterpreterState_Delete: remaining threads");
342 }
343 *p = interp->next;
344 if (interpreters->main == interp) {
345 interpreters->main = NULL;
346 if (interpreters->head != NULL) {
347 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
348 }
349 }
350 HEAD_UNLOCK(runtime);
351 if (interp->id_mutex != NULL) {
352 PyThread_free_lock(interp->id_mutex);
353 }
354 PyMem_RawFree(interp);
355}
356
357
Victor Stinner0fd2c302019-06-04 03:15:09 +0200358void
359PyInterpreterState_Delete(PyInterpreterState *interp)
360{
361 _PyInterpreterState_Delete(&_PyRuntime, interp);
362}
363
364
Eric Snow59032962018-09-14 14:17:20 -0700365/*
366 * Delete all interpreter states except the main interpreter. If there
367 * is a current interpreter state, it *must* be the main interpreter.
368 */
369void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200370_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700371{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200372 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200373 struct pyinterpreters *interpreters = &runtime->interpreters;
374
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200375 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200376 if (tstate != NULL && tstate->interp != interpreters->main) {
Eric Snow59032962018-09-14 14:17:20 -0700377 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
378 }
379
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200380 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200381 PyInterpreterState *interp = interpreters->head;
382 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100383 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200384 if (interp == interpreters->main) {
385 interpreters->main->next = NULL;
386 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100387 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700388 continue;
389 }
390
Victor Stinner0fd2c302019-06-04 03:15:09 +0200391 _PyInterpreterState_Clear(runtime, interp); // XXX must activate?
392 zapthreads(runtime, interp);
Eric Snow59032962018-09-14 14:17:20 -0700393 if (interp->id_mutex != NULL) {
394 PyThread_free_lock(interp->id_mutex);
395 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100396 PyInterpreterState *prev_interp = interp;
397 interp = interp->next;
398 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700399 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200400 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700401
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200402 if (interpreters->head == NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700403 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
404 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200405 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700406}
407
408
Victor Stinnercaba55b2018-08-03 15:33:52 +0200409PyInterpreterState *
410_PyInterpreterState_Get(void)
411{
Victor Stinner50b48572018-11-01 01:51:40 +0100412 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200413 if (tstate == NULL) {
414 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
415 }
416 PyInterpreterState *interp = tstate->interp;
417 if (interp == NULL) {
418 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
419 }
420 return interp;
421}
422
423
Eric Snowe3774162017-05-22 19:46:40 -0700424int64_t
425PyInterpreterState_GetID(PyInterpreterState *interp)
426{
427 if (interp == NULL) {
428 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
429 return -1;
430 }
431 return interp->id;
432}
433
434
Eric Snow5be45a62019-03-08 22:47:07 -0700435static PyInterpreterState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200436interp_look_up_id(_PyRuntimeState *runtime, PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700437{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200438 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100439 while (interp != NULL) {
440 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700441 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100442 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700443 }
444 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100445 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700446 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100447 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700448 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100449 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700450}
451
Eric Snow5be45a62019-03-08 22:47:07 -0700452PyInterpreterState *
453_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
454{
455 PyInterpreterState *interp = NULL;
456 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200457 _PyRuntimeState *runtime = &_PyRuntime;
458 HEAD_LOCK(runtime);
459 interp = interp_look_up_id(runtime, requested_id);
460 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700461 }
462 if (interp == NULL && !PyErr_Occurred()) {
463 PyErr_Format(PyExc_RuntimeError,
464 "unrecognized interpreter ID %lld", requested_id);
465 }
466 return interp;
467}
468
Eric Snow4c6955e2018-02-16 18:53:40 -0700469
470int
471_PyInterpreterState_IDInitref(PyInterpreterState *interp)
472{
473 if (interp->id_mutex != NULL) {
474 return 0;
475 }
476 interp->id_mutex = PyThread_allocate_lock();
477 if (interp->id_mutex == NULL) {
478 PyErr_SetString(PyExc_RuntimeError,
479 "failed to create init interpreter ID mutex");
480 return -1;
481 }
482 interp->id_refcount = 0;
483 return 0;
484}
485
486
487void
488_PyInterpreterState_IDIncref(PyInterpreterState *interp)
489{
490 if (interp->id_mutex == NULL) {
491 return;
492 }
493 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
494 interp->id_refcount += 1;
495 PyThread_release_lock(interp->id_mutex);
496}
497
498
499void
500_PyInterpreterState_IDDecref(PyInterpreterState *interp)
501{
502 if (interp->id_mutex == NULL) {
503 return;
504 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200505 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700506 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
507 assert(interp->id_refcount != 0);
508 interp->id_refcount -= 1;
509 int64_t refcount = interp->id_refcount;
510 PyThread_release_lock(interp->id_mutex);
511
Eric Snowc11183c2019-03-15 16:35:46 -0600512 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700513 // XXX Using the "head" thread isn't strictly correct.
514 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
515 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200516 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700517 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200518 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700519 }
520}
521
Eric Snowc11183c2019-03-15 16:35:46 -0600522int
523_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
524{
525 return interp->requires_idref;
526}
527
528void
529_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
530{
531 interp->requires_idref = required ? 1 : 0;
532}
533
Eric Snowc11183c2019-03-15 16:35:46 -0600534PyObject *
535_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
536{
537 if (interp->modules == NULL) {
538 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
539 return NULL;
540 }
541 return PyMapping_GetItemString(interp->modules, "__main__");
542}
543
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600544PyObject *
545PyInterpreterState_GetDict(PyInterpreterState *interp)
546{
547 if (interp->dict == NULL) {
548 interp->dict = PyDict_New();
549 if (interp->dict == NULL) {
550 PyErr_Clear();
551 }
552 }
553 /* Returning NULL means no per-interpreter dict is available. */
554 return interp->dict;
555}
556
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000557/* Default implementation for _PyThreadState_GetFrame */
558static struct _frame *
559threadstate_getframe(PyThreadState *self)
560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000562}
563
Victor Stinner45b9be52010-03-03 23:28:07 +0000564static PyThreadState *
565new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000566{
Victor Stinner0fd2c302019-06-04 03:15:09 +0200567 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200568 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200569 if (tstate == NULL) {
570 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000572
Victor Stinner8bb32302019-04-24 16:47:40 +0200573 if (_PyThreadState_GetFrame == NULL) {
574 _PyThreadState_GetFrame = threadstate_getframe;
575 }
576
577 tstate->interp = interp;
578
579 tstate->frame = NULL;
580 tstate->recursion_depth = 0;
581 tstate->overflowed = 0;
582 tstate->recursion_critical = 0;
583 tstate->stackcheck_counter = 0;
584 tstate->tracing = 0;
585 tstate->use_tracing = 0;
586 tstate->gilstate_counter = 0;
587 tstate->async_exc = NULL;
588 tstate->thread_id = PyThread_get_thread_ident();
589
590 tstate->dict = NULL;
591
592 tstate->curexc_type = NULL;
593 tstate->curexc_value = NULL;
594 tstate->curexc_traceback = NULL;
595
596 tstate->exc_state.exc_type = NULL;
597 tstate->exc_state.exc_value = NULL;
598 tstate->exc_state.exc_traceback = NULL;
599 tstate->exc_state.previous_item = NULL;
600 tstate->exc_info = &tstate->exc_state;
601
602 tstate->c_profilefunc = NULL;
603 tstate->c_tracefunc = NULL;
604 tstate->c_profileobj = NULL;
605 tstate->c_traceobj = NULL;
606
607 tstate->trash_delete_nesting = 0;
608 tstate->trash_delete_later = NULL;
609 tstate->on_delete = NULL;
610 tstate->on_delete_data = NULL;
611
612 tstate->coroutine_origin_tracking_depth = 0;
613
Victor Stinner8bb32302019-04-24 16:47:40 +0200614 tstate->async_gen_firstiter = NULL;
615 tstate->async_gen_finalizer = NULL;
616
617 tstate->context = NULL;
618 tstate->context_ver = 1;
619
620 tstate->id = ++interp->tstate_next_unique_id;
621
622 if (init) {
Victor Stinner0fd2c302019-06-04 03:15:09 +0200623 _PyThreadState_Init(runtime, tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200624 }
625
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200626 HEAD_LOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200627 tstate->prev = NULL;
628 tstate->next = interp->tstate_head;
629 if (tstate->next)
630 tstate->next->prev = tstate;
631 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200632 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000635}
636
Victor Stinner45b9be52010-03-03 23:28:07 +0000637PyThreadState *
638PyThreadState_New(PyInterpreterState *interp)
639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000641}
642
643PyThreadState *
644_PyThreadState_Prealloc(PyInterpreterState *interp)
645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000647}
648
649void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200650_PyThreadState_Init(_PyRuntimeState *runtime, PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000651{
Victor Stinner8bb32302019-04-24 16:47:40 +0200652 _PyGILState_NoteThreadState(&runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000653}
654
Martin v. Löwis1a214512008-06-11 05:26:20 +0000655PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200656PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000657{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200658 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100659 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000661 if (module->m_slots) {
662 return NULL;
663 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 if (index == 0)
665 return NULL;
666 if (state->modules_by_index == NULL)
667 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200668 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 return NULL;
670 res = PyList_GET_ITEM(state->modules_by_index, index);
671 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000672}
673
674int
675_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
676{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000677 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300678 if (!def) {
679 assert(PyErr_Occurred());
680 return -1;
681 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000682 if (def->m_slots) {
683 PyErr_SetString(PyExc_SystemError,
684 "PyState_AddModule called on module with slots");
685 return -1;
686 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100687 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 if (!state->modules_by_index) {
689 state->modules_by_index = PyList_New(0);
690 if (!state->modules_by_index)
691 return -1;
692 }
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100693 while (PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 if (PyList_Append(state->modules_by_index, Py_None) < 0)
695 return -1;
696 Py_INCREF(module);
697 return PyList_SetItem(state->modules_by_index,
698 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000699}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000700
Martin v. Löwis7800f752012-06-22 12:20:55 +0200701int
702PyState_AddModule(PyObject* module, struct PyModuleDef* def)
703{
704 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100705 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200706 if (!def) {
707 Py_FatalError("PyState_AddModule: Module Definition is NULL");
708 return -1;
709 }
710 index = def->m_base.m_index;
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100711 if (state->modules_by_index &&
712 index < PyList_GET_SIZE(state->modules_by_index) &&
713 module == PyList_GET_ITEM(state->modules_by_index, index)) {
714 Py_FatalError("PyState_AddModule: Module already added!");
715 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200716 }
717 return _PyState_AddModule(module, def);
718}
719
720int
721PyState_RemoveModule(struct PyModuleDef* def)
722{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000723 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200724 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000725 if (def->m_slots) {
726 PyErr_SetString(PyExc_SystemError,
727 "PyState_RemoveModule called on module with slots");
728 return -1;
729 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100730 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200731 if (index == 0) {
732 Py_FatalError("PyState_RemoveModule: Module index invalid.");
733 return -1;
734 }
735 if (state->modules_by_index == NULL) {
Min ho Kim39d87b52019-08-31 06:21:19 +1000736 Py_FatalError("PyState_RemoveModule: Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200737 return -1;
738 }
739 if (index > PyList_GET_SIZE(state->modules_by_index)) {
740 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
741 return -1;
742 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700743 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200744 return PyList_SetItem(state->modules_by_index, index, Py_None);
745}
746
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200747/* Used by PyImport_Cleanup() */
Antoine Pitrou40322e62013-08-11 00:30:09 +0200748void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200749_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200750{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200751 if (!interp->modules_by_index) {
752 return;
753 }
754
755 Py_ssize_t i;
756 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
757 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
758 if (PyModule_Check(m)) {
759 /* cleanup the saved copy of module dicts */
760 PyModuleDef *md = PyModule_GetDef(m);
761 if (md) {
762 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200763 }
764 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200765 }
766
767 /* Setting modules_by_index to NULL could be dangerous, so we
768 clear the list instead. */
769 if (PyList_SetSlice(interp->modules_by_index,
770 0, PyList_GET_SIZE(interp->modules_by_index),
771 NULL)) {
772 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200773 }
774}
775
Guido van Rossuma027efa1997-05-05 20:56:21 +0000776void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000777PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000778{
Victor Stinner331a6a52019-05-27 16:39:22 +0200779 int verbose = tstate->interp->config.verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200780
781 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 fprintf(stderr,
783 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 Py_CLEAR(tstate->dict);
788 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 Py_CLEAR(tstate->curexc_type);
791 Py_CLEAR(tstate->curexc_value);
792 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000793
Mark Shannonae3087c2017-10-22 22:41:51 +0100794 Py_CLEAR(tstate->exc_state.exc_type);
795 Py_CLEAR(tstate->exc_state.exc_value);
796 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300797
Mark Shannonae3087c2017-10-22 22:41:51 +0100798 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200799 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100800 fprintf(stderr,
801 "PyThreadState_Clear: warning: thread still has a generator\n");
802 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 tstate->c_profilefunc = NULL;
805 tstate->c_tracefunc = NULL;
806 Py_CLEAR(tstate->c_profileobj);
807 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400808
Yury Selivanoveb636452016-09-08 22:01:51 -0700809 Py_CLEAR(tstate->async_gen_firstiter);
810 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500811
812 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000813}
814
815
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300816/* Common code for PyThreadState_Delete() and _PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000817static void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200818tstate_delete_common(_PyRuntimeState *runtime, PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000819{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200820 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 Py_FatalError("PyThreadState_Delete: NULL tstate");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200822 }
823 PyInterpreterState *interp = tstate->interp;
824 if (interp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 Py_FatalError("PyThreadState_Delete: NULL interp");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200826 }
827 HEAD_LOCK(runtime);
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200828 if (tstate->prev)
829 tstate->prev->next = tstate->next;
830 else
831 interp->tstate_head = tstate->next;
832 if (tstate->next)
833 tstate->next->prev = tstate->prev;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200834 HEAD_UNLOCK(runtime);
Antoine Pitrou7b476992013-09-07 23:38:37 +0200835 if (tstate->on_delete != NULL) {
836 tstate->on_delete(tstate->on_delete_data);
837 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200838 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000839}
840
841
Victor Stinner0fd2c302019-06-04 03:15:09 +0200842static void
843_PyThreadState_Delete(_PyRuntimeState *runtime, PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000844{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200845 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
846 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600848 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200849 if (gilstate->autoInterpreterState &&
850 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
851 {
852 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
853 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200854 tstate_delete_common(runtime, tstate);
855}
856
857
858void
859PyThreadState_Delete(PyThreadState *tstate)
860{
861 _PyThreadState_Delete(&_PyRuntime, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200862}
863
864
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300865void
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200866_PyThreadState_DeleteCurrent(_PyRuntimeState *runtime)
867{
868 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
869 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 if (tstate == NULL)
871 Py_FatalError(
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300872 "_PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner0fd2c302019-06-04 03:15:09 +0200873 tstate_delete_common(runtime, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200874 if (gilstate->autoInterpreterState &&
875 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600876 {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200877 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600878 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200879 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000881}
Guido van Rossum29757862001-01-23 01:46:06 +0000882
883
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200884/*
885 * Delete all thread states except the one passed as argument.
886 * Note that, if there is a current thread state, it *must* be the one
887 * passed as argument. Also, this won't touch any other interpreters
888 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000889 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200890 */
891void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200892_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200893{
894 PyInterpreterState *interp = tstate->interp;
895 PyThreadState *p, *next, *garbage;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200896 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200897 /* Remove all thread states, except tstate, from the linked list of
898 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200899 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200900 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200901 if (garbage == tstate)
902 garbage = tstate->next;
903 if (tstate->prev)
904 tstate->prev->next = tstate->next;
905 if (tstate->next)
906 tstate->next->prev = tstate->prev;
907 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200908 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200909 HEAD_UNLOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200910 /* Clear and deallocate all stale thread states. Even if this
911 executes Python code, we should be safe since it executes
912 in the current thread, not one of the stale threads. */
913 for (p = garbage; p; p = next) {
914 next = p->next;
915 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200916 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200917 }
918}
919
920
Guido van Rossuma027efa1997-05-05 20:56:21 +0000921PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100922_PyThreadState_UncheckedGet(void)
923{
Victor Stinner50b48572018-11-01 01:51:40 +0100924 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100925}
926
927
928PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000929PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000930{
Victor Stinner50b48572018-11-01 01:51:40 +0100931 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 if (tstate == NULL)
933 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000936}
937
938
Victor Stinner09532fe2019-05-10 23:39:09 +0200939PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200940_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000941{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200942 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000943
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200944 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 /* It should not be possible for more than one thread state
946 to be used for a thread. Check this the best we can in debug
947 builds.
948 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200949#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 if (newts) {
951 /* This can be called from PyEval_RestoreThread(). Similar
952 to it, we need to ensure errno doesn't change.
953 */
954 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200955 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 if (check && check->interp == newts->interp && check != newts)
957 Py_FatalError("Invalid thread state for this thread");
958 errno = err;
959 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000960#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000962}
Guido van Rossumede04391998-04-10 20:18:25 +0000963
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200964PyThreadState *
965PyThreadState_Swap(PyThreadState *newts)
966{
967 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
968}
969
Guido van Rossumede04391998-04-10 20:18:25 +0000970/* An extension mechanism to store arbitrary additional per-thread state.
971 PyThreadState_GetDict() returns a dictionary that can be used to hold such
972 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000973 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
974 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000975
976PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000977PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000978{
Victor Stinner50b48572018-11-01 01:51:40 +0100979 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 if (tstate == NULL)
981 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 if (tstate->dict == NULL) {
984 PyObject *d;
985 tstate->dict = d = PyDict_New();
986 if (d == NULL)
987 PyErr_Clear();
988 }
989 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000990}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000991
992
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000993/* Asynchronously raise an exception in a thread.
994 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000995 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000996 to call this, or use ctypes. Must be called with the GIL held.
997 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
998 match any known thread id). Can be called with exc=NULL to clear an
999 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001000
1001int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001002PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1003{
Victor Stinner09532fe2019-05-10 23:39:09 +02001004 _PyRuntimeState *runtime = &_PyRuntime;
1005 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 /* Although the GIL is held, a few C API functions can be called
1008 * without the GIL held, and in particular some that create and
1009 * destroy thread and interpreter states. Those can mutate the
1010 * list of thread states we're traversing, so to prevent that we lock
1011 * head_mutex for the duration.
1012 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001013 HEAD_LOCK(runtime);
Victor Stinner09532fe2019-05-10 23:39:09 +02001014 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 if (p->thread_id == id) {
1016 /* Tricky: we need to decref the current value
1017 * (if any) in p->async_exc, but that can in turn
1018 * allow arbitrary Python code to run, including
1019 * perhaps calls to this function. To prevent
1020 * deadlock, we need to release head_mutex before
1021 * the decref.
1022 */
1023 PyObject *old_exc = p->async_exc;
1024 Py_XINCREF(exc);
1025 p->async_exc = exc;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001026 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 Py_XDECREF(old_exc);
Victor Stinnere225beb2019-06-03 18:14:24 +02001028 _PyEval_SignalAsyncExc(&runtime->ceval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 return 1;
1030 }
1031 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001032 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001034}
1035
1036
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001037/* Routines for advanced debuggers, requested by David Beazley.
1038 Don't use unless you know what you are doing! */
1039
1040PyInterpreterState *
1041PyInterpreterState_Head(void)
1042{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001043 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001044}
1045
1046PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001047PyInterpreterState_Main(void)
1048{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001049 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001050}
1051
1052PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001053PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001055}
1056
1057PyThreadState *
1058PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001060}
1061
1062PyThreadState *
1063PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001065}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001066
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001067/* The implementation of sys._current_frames(). This is intended to be
1068 called with the GIL held, as it will be when called via
1069 sys._current_frames(). It's possible it would work fine even without
1070 the GIL held, but haven't thought enough about that.
1071*/
1072PyObject *
1073_PyThread_CurrentFrames(void)
1074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 PyObject *result;
1076 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001077
Steve Dowerb82e17e2019-05-23 08:45:22 -07001078 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1079 return NULL;
1080 }
1081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 result = PyDict_New();
1083 if (result == NULL)
1084 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 /* for i in all interpreters:
1087 * for t in all of i's thread states:
1088 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001089 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 * need to grab head_mutex for the duration.
1091 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001092 _PyRuntimeState *runtime = &_PyRuntime;
1093 HEAD_LOCK(runtime);
1094 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 PyThreadState *t;
1096 for (t = i->tstate_head; t != NULL; t = t->next) {
1097 PyObject *id;
1098 int stat;
1099 struct _frame *frame = t->frame;
1100 if (frame == NULL)
1101 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001102 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 if (id == NULL)
1104 goto Fail;
1105 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1106 Py_DECREF(id);
1107 if (stat < 0)
1108 goto Fail;
1109 }
1110 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001111 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001113
1114 Fail:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001115 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 Py_DECREF(result);
1117 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001118}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001119
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001120/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001121
1122/* Keep this as a static, as it is not reliable! It can only
1123 ever be compared to the state for the *current* thread.
1124 * If not equal, then it doesn't matter that the actual
1125 value may change immediately after comparison, as it can't
1126 possibly change to the current thread's state.
1127 * If equal, then the current thread holds the lock, so the value can't
1128 change until we yield the lock.
1129*/
1130static int
1131PyThreadState_IsCurrent(PyThreadState *tstate)
1132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001134 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001135 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1136 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001137}
1138
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001139/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001140 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001141*/
Tim Peters19717fa2004-10-09 17:38:29 +00001142void
Victor Stinnerb45d2592019-06-20 00:05:23 +02001143_PyGILState_Init(_PyRuntimeState *runtime, PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001144{
Victor Stinner8bb32302019-04-24 16:47:40 +02001145 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001146 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001147 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001148
Victor Stinner8bb32302019-04-24 16:47:40 +02001149 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1150
1151 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001152 Py_FatalError("Could not allocate TSS entry");
1153 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001154 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001155 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1156 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001157
Victor Stinner8bb32302019-04-24 16:47:40 +02001158 _PyGILState_NoteThreadState(gilstate, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001159}
1160
Victor Stinner861d9ab2016-03-16 22:45:24 +01001161PyInterpreterState *
1162_PyGILState_GetInterpreterStateUnsafe(void)
1163{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001164 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001165}
1166
Tim Peters19717fa2004-10-09 17:38:29 +00001167void
Victor Stinner8e91c242019-04-24 17:24:01 +02001168_PyGILState_Fini(_PyRuntimeState *runtime)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001169{
Victor Stinner8e91c242019-04-24 17:24:01 +02001170 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1171 PyThread_tss_delete(&gilstate->autoTSSkey);
1172 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001173}
1174
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001175/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001176 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001177 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001178 */
1179void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001180_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001181{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001182 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001183 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001184
1185 PyThread_tss_delete(&gilstate->autoTSSkey);
1186 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001187 Py_FatalError("Could not allocate TSS entry");
1188 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001189
Charles-François Natalia233df82011-11-22 19:49:51 +01001190 /* If the thread had an associated auto thread state, reassociate it with
1191 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001192 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001193 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001194 {
1195 Py_FatalError("Couldn't create autoTSSkey mapping");
1196 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001197}
1198
Michael W. Hudson188d4362005-06-20 16:52:57 +00001199/* When a thread state is created for a thread by some mechanism other than
1200 PyGILState_Ensure, it's important that the GILState machinery knows about
1201 it so it doesn't try to create another thread state for the thread (this is
1202 a better fix for SF bug #1010677 than the first one attempted).
1203*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001204static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001205_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001206{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001207 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001208 threadstate created in Py_Initialize(). Don't do anything for now
1209 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001210 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001212 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001213
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001214 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 The only situation where you can legitimately have more than one
1217 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001218 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001219
Victor Stinner590cebe2013-12-13 11:08:56 +01001220 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1221 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001222
Victor Stinner590cebe2013-12-13 11:08:56 +01001223 The first thread state created for that given OS level thread will
1224 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001226 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1227 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001228 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001229 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001230 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 /* PyGILState_Release must not try to delete this thread state. */
1233 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001234}
1235
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001236/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001237static PyThreadState *
1238_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1239{
1240 if (gilstate->autoInterpreterState == NULL)
1241 return NULL;
1242 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1243}
1244
Tim Peters19717fa2004-10-09 17:38:29 +00001245PyThreadState *
1246PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001247{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001248 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001249}
1250
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001251int
1252PyGILState_Check(void)
1253{
Victor Stinner8a1be612016-03-14 22:07:55 +01001254
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001255 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001256 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001257 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001258
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001259 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1260 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1261 return 1;
1262 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001263
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001264 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1265 if (tstate == NULL) {
1266 return 0;
1267 }
1268
1269 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001270}
1271
Tim Peters19717fa2004-10-09 17:38:29 +00001272PyGILState_STATE
1273PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001274{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001275 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 int current;
1277 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001278 int need_init_threads = 0;
1279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 /* Note that we do not auto-init Python here - apart from
1281 potential races with 2 threads auto-initializing, pep-311
1282 spells out other issues. Embedders are expected to have
1283 called Py_Initialize() and usually PyEval_InitThreads().
1284 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001285 /* Py_Initialize() hasn't been called! */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001286 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001287
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001288 tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001290 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 /* Create a new thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001293 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 if (tcur == NULL)
1295 Py_FatalError("Couldn't create thread-state for new thread");
1296 /* This is our thread state! We'll need to delete it in the
1297 matching call to PyGILState_Release(). */
1298 tcur->gilstate_counter = 0;
1299 current = 0; /* new thread state is never current */
1300 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001301 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001303 }
1304
1305 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001307 }
1308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 /* Update our counter in the thread-state - no need for locks:
1310 - tcur will remain valid as we hold the GIL.
1311 - the counter is safe as we are the only thread "allowed"
1312 to modify this value
1313 */
1314 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001315
1316 if (need_init_threads) {
1317 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1318 called from a new thread for the first time, we need the create the
1319 GIL. */
1320 PyEval_InitThreads();
1321 }
1322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001324}
1325
Tim Peters19717fa2004-10-09 17:38:29 +00001326void
1327PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001328{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001329 _PyRuntimeState *runtime = &_PyRuntime;
1330 PyThreadState *tcur = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1331 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 Py_FatalError("auto-releasing thread-state, "
1333 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001334 }
1335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 /* We must hold the GIL and have our thread state current */
1337 /* XXX - remove the check - the assert should be fine,
1338 but while this is very new (April 2003), the extra check
1339 by release-only users can't hurt.
1340 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001341 if (!PyThreadState_IsCurrent(tcur)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 Py_FatalError("This thread state must be current when releasing");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001343 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 assert(PyThreadState_IsCurrent(tcur));
1345 --tcur->gilstate_counter;
1346 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 /* If we're going to destroy this thread-state, we must
1349 * clear it while the GIL is held, as destructors may run.
1350 */
1351 if (tcur->gilstate_counter == 0) {
1352 /* can't have been locked when we created it */
1353 assert(oldstate == PyGILState_UNLOCKED);
1354 PyThreadState_Clear(tcur);
1355 /* Delete the thread-state. Note this releases the GIL too!
1356 * It's vital that the GIL be held here, to avoid shutdown
1357 * races; see bugs 225673 and 1061968 (that nasty bug has a
1358 * habit of coming back).
1359 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001360 _PyThreadState_DeleteCurrent(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 }
1362 /* Release the lock if necessary */
1363 else if (oldstate == PyGILState_UNLOCKED)
1364 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001365}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001366
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001367
Eric Snow7f8bfc92018-01-29 18:23:44 -07001368/**************************/
1369/* cross-interpreter data */
1370/**************************/
1371
1372/* cross-interpreter data */
1373
1374crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1375
1376/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1377 to keep the registry code separate. */
1378static crossinterpdatafunc
1379_lookup_getdata(PyObject *obj)
1380{
1381 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1382 if (getdata == NULL && PyErr_Occurred() == 0)
1383 PyErr_Format(PyExc_ValueError,
1384 "%S does not support cross-interpreter data", obj);
1385 return getdata;
1386}
1387
1388int
1389_PyObject_CheckCrossInterpreterData(PyObject *obj)
1390{
1391 crossinterpdatafunc getdata = _lookup_getdata(obj);
1392 if (getdata == NULL) {
1393 return -1;
1394 }
1395 return 0;
1396}
1397
1398static int
1399_check_xidata(_PyCrossInterpreterData *data)
1400{
1401 // data->data can be anything, including NULL, so we don't check it.
1402
1403 // data->obj may be NULL, so we don't check it.
1404
1405 if (data->interp < 0) {
1406 PyErr_SetString(PyExc_SystemError, "missing interp");
1407 return -1;
1408 }
1409
1410 if (data->new_object == NULL) {
1411 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1412 return -1;
1413 }
1414
1415 // data->free may be NULL, so we don't check it.
1416
1417 return 0;
1418}
1419
1420int
1421_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1422{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001423 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001424 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001425 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001426
1427 // Reset data before re-populating.
1428 *data = (_PyCrossInterpreterData){0};
1429 data->free = PyMem_RawFree; // Set a default that may be overridden.
1430
1431 // Call the "getdata" func for the object.
1432 Py_INCREF(obj);
1433 crossinterpdatafunc getdata = _lookup_getdata(obj);
1434 if (getdata == NULL) {
1435 Py_DECREF(obj);
1436 return -1;
1437 }
1438 int res = getdata(obj, data);
1439 Py_DECREF(obj);
1440 if (res != 0) {
1441 return -1;
1442 }
1443
1444 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001445 data->interp = interp->id;
1446 if (_check_xidata(data) != 0) {
1447 _PyCrossInterpreterData_Release(data);
1448 return -1;
1449 }
1450
1451 return 0;
1452}
1453
Victor Stinnere225beb2019-06-03 18:14:24 +02001454static void
Eric Snow63799132018-06-01 18:45:20 -06001455_release_xidata(void *arg)
1456{
1457 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1458 if (data->free != NULL) {
1459 data->free(data->data);
1460 }
1461 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001462}
1463
1464static void
1465_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1466 PyInterpreterState *interp,
1467 void (*func)(void *), void *arg)
1468{
1469 /* We would use Py_AddPendingCall() if it weren't specific to the
1470 * main interpreter (see bpo-33608). In the meantime we take a
1471 * naive approach.
1472 */
1473 PyThreadState *save_tstate = NULL;
1474 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1475 // XXX Using the "head" thread isn't strictly correct.
1476 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1477 // XXX Possible GILState issues?
1478 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1479 }
1480
1481 func(arg);
1482
1483 // Switch back.
1484 if (save_tstate != NULL) {
1485 _PyThreadState_Swap(gilstate, save_tstate);
1486 }
Eric Snow63799132018-06-01 18:45:20 -06001487}
1488
Eric Snow7f8bfc92018-01-29 18:23:44 -07001489void
1490_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1491{
1492 if (data->data == NULL && data->obj == NULL) {
1493 // Nothing to release!
1494 return;
1495 }
1496
Victor Stinnere225beb2019-06-03 18:14:24 +02001497 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001498 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1499 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001500 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001501 if (data->free != NULL) {
1502 // XXX Someone leaked some memory...
1503 }
1504 return;
1505 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001506
Eric Snow7f8bfc92018-01-29 18:23:44 -07001507 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001508 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1509 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001510}
1511
1512PyObject *
1513_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1514{
1515 return data->new_object(data);
1516}
1517
1518/* registry of {type -> crossinterpdatafunc} */
1519
1520/* For now we use a global registry of shareable classes. An
1521 alternative would be to add a tp_* slot for a class's
1522 crossinterpdatafunc. It would be simpler and more efficient. */
1523
1524static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001525_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1526 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001527{
1528 // Note that we effectively replace already registered classes
1529 // rather than failing.
1530 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1531 if (newhead == NULL)
1532 return -1;
1533 newhead->cls = cls;
1534 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001535 newhead->next = xidregistry->head;
1536 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001537 return 0;
1538}
1539
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001540static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001541
1542int
Eric Snowc11183c2019-03-15 16:35:46 -06001543_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001544 crossinterpdatafunc getdata)
1545{
1546 if (!PyType_Check(cls)) {
1547 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1548 return -1;
1549 }
1550 if (getdata == NULL) {
1551 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1552 return -1;
1553 }
1554
1555 // Make sure the class isn't ever deallocated.
1556 Py_INCREF((PyObject *)cls);
1557
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001558 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1559 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1560 if (xidregistry->head == NULL) {
1561 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001562 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001563 int res = _register_xidata(xidregistry, cls, getdata);
1564 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001565 return res;
1566}
1567
Eric Snow6d2cd902018-05-16 15:04:57 -04001568/* Cross-interpreter objects are looked up by exact match on the class.
1569 We can reassess this policy when we move from a global registry to a
1570 tp_* slot. */
1571
Eric Snow7f8bfc92018-01-29 18:23:44 -07001572crossinterpdatafunc
1573_PyCrossInterpreterData_Lookup(PyObject *obj)
1574{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001575 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001576 PyObject *cls = PyObject_Type(obj);
1577 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001578 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1579 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001580 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001581 _register_builtins_for_crossinterpreter_data(xidregistry);
1582 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001583 }
1584 for(; cur != NULL; cur = cur->next) {
1585 if (cur->cls == (PyTypeObject *)cls) {
1586 getdata = cur->getdata;
1587 break;
1588 }
1589 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001590 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001591 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001592 return getdata;
1593}
1594
1595/* cross-interpreter data for builtin types */
1596
Eric Snow6d2cd902018-05-16 15:04:57 -04001597struct _shared_bytes_data {
1598 char *bytes;
1599 Py_ssize_t len;
1600};
1601
Eric Snow7f8bfc92018-01-29 18:23:44 -07001602static PyObject *
1603_new_bytes_object(_PyCrossInterpreterData *data)
1604{
Eric Snow6d2cd902018-05-16 15:04:57 -04001605 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1606 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001607}
1608
1609static int
1610_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1611{
Eric Snow6d2cd902018-05-16 15:04:57 -04001612 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1613 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1614 return -1;
1615 }
1616 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001617 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001618 data->obj = obj; // Will be "released" (decref'ed) when data released.
1619 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001620 data->free = PyMem_Free;
1621 return 0;
1622}
1623
1624struct _shared_str_data {
1625 int kind;
1626 const void *buffer;
1627 Py_ssize_t len;
1628};
1629
1630static PyObject *
1631_new_str_object(_PyCrossInterpreterData *data)
1632{
1633 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1634 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1635}
1636
1637static int
1638_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1639{
1640 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1641 shared->kind = PyUnicode_KIND(obj);
1642 shared->buffer = PyUnicode_DATA(obj);
1643 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1644 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001645 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001646 data->obj = obj; // Will be "released" (decref'ed) when data released.
1647 data->new_object = _new_str_object;
1648 data->free = PyMem_Free;
1649 return 0;
1650}
1651
1652static PyObject *
1653_new_long_object(_PyCrossInterpreterData *data)
1654{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001655 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001656}
1657
1658static int
1659_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1660{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001661 /* Note that this means the size of shareable ints is bounded by
1662 * sys.maxsize. Hence on 32-bit architectures that is half the
1663 * size of maximum shareable ints on 64-bit.
1664 */
1665 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001666 if (value == -1 && PyErr_Occurred()) {
1667 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1668 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1669 }
1670 return -1;
1671 }
1672 data->data = (void *)value;
1673 data->obj = NULL;
1674 data->new_object = _new_long_object;
1675 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001676 return 0;
1677}
1678
1679static PyObject *
1680_new_none_object(_PyCrossInterpreterData *data)
1681{
1682 // XXX Singleton refcounts are problematic across interpreters...
1683 Py_INCREF(Py_None);
1684 return Py_None;
1685}
1686
1687static int
1688_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1689{
1690 data->data = NULL;
1691 // data->obj remains NULL
1692 data->new_object = _new_none_object;
1693 data->free = NULL; // There is nothing to free.
1694 return 0;
1695}
1696
1697static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001698_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001699{
1700 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001701 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001702 Py_FatalError("could not register None for cross-interpreter sharing");
1703 }
1704
Eric Snow6d2cd902018-05-16 15:04:57 -04001705 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001706 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001707 Py_FatalError("could not register int for cross-interpreter sharing");
1708 }
1709
Eric Snow7f8bfc92018-01-29 18:23:44 -07001710 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001711 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001712 Py_FatalError("could not register bytes for cross-interpreter sharing");
1713 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001714
1715 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001716 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001717 Py_FatalError("could not register str for cross-interpreter sharing");
1718 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001719}
1720
1721
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001722#ifdef __cplusplus
1723}
1724#endif