blob: 7dd8b7f866b5ea60fea36bc06324fa302aafe4c0 [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 Stinner331a6a52019-05-27 16:39:22 +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 Stinner8bb32302019-04-24 16:47:40 +0200162/* Forward declaration */
163static void _PyGILState_NoteThreadState(
164 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000165
Victor Stinner331a6a52019-05-27 16:39:22 +0200166PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600167_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700168{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200169 struct pyinterpreters *interpreters = &runtime->interpreters;
170 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100171
172 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
173 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200174 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100175 /* Force default allocator, since _PyRuntimeState_Fini() must
176 use the same allocator than this function. */
177 PyMemAllocatorEx old_alloc;
178 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
179
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200180 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100181
182 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
183
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200184 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200185 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800186 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600187 }
Victor Stinner5d926472018-03-06 14:31:37 +0100188
Victor Stinner331a6a52019-05-27 16:39:22 +0200189 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700190}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000191
192PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000193PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000194{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700195 if (PySys_Audit("cpython.PyInterpreterState_New", NULL) < 0) {
196 return NULL;
197 }
198
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200199 PyInterpreterState *interp = PyMem_RawMalloc(sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100200 if (interp == NULL) {
201 return NULL;
202 }
203
Eric Snow5be45a62019-03-08 22:47:07 -0700204 memset(interp, 0, sizeof(*interp));
Eric Snow4c6955e2018-02-16 18:53:40 -0700205 interp->id_refcount = -1;
Victor Stinner022be022019-05-22 23:58:50 +0200206
Victor Stinner331a6a52019-05-27 16:39:22 +0200207 PyStatus status = PyConfig_InitPythonConfig(&interp->config);
208 if (_PyStatus_EXCEPTION(status)) {
209 /* Don't report status to caller: PyConfig_InitPythonConfig()
210 can only fail with a memory allocation error. */
211 PyConfig_Clear(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200212 PyMem_RawFree(interp);
213 return NULL;
214 }
215
Victor Stinnerd4341102017-11-23 00:12:09 +0100216 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000217#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300218#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100219 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000220#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100221 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000222#endif
223#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000224
Victor Stinner0fd2c302019-06-04 03:15:09 +0200225 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200226 struct pyinterpreters *interpreters = &runtime->interpreters;
227
228 HEAD_LOCK(runtime);
229 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100230 /* overflow or Py_Initialize() not called! */
231 PyErr_SetString(PyExc_RuntimeError,
232 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100233 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100234 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100235 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200236 else {
237 interp->id = interpreters->next_id;
238 interpreters->next_id += 1;
239 interp->next = interpreters->head;
240 if (interpreters->main == NULL) {
241 interpreters->main = interp;
242 }
243 interpreters->head = interp;
244 }
245 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000246
Pablo Galindo95d630e2018-08-31 22:49:29 +0100247 if (interp == NULL) {
248 return NULL;
249 }
250
Yury Selivanovf23746a2018-01-22 19:11:18 -0500251 interp->tstate_next_unique_id = 0;
252
Steve Dowerb82e17e2019-05-23 08:45:22 -0700253 interp->audit_hooks = NULL;
254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000256}
257
258
Victor Stinner0fd2c302019-06-04 03:15:09 +0200259static void
260_PyInterpreterState_Clear(_PyRuntimeState *runtime, PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000261{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700262 if (PySys_Audit("cpython.PyInterpreterState_Clear", NULL) < 0) {
263 PyErr_Clear();
264 }
265
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200266 HEAD_LOCK(runtime);
267 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200269 }
270 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700271
272 Py_CLEAR(interp->audit_hooks);
273
Victor Stinner331a6a52019-05-27 16:39:22 +0200274 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 Py_CLEAR(interp->codec_search_path);
276 Py_CLEAR(interp->codec_search_cache);
277 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700278 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 Py_CLEAR(interp->sysdict);
281 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200282 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400283 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300284 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600285 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200286#ifdef HAVE_FORK
287 Py_CLEAR(interp->before_forkers);
288 Py_CLEAR(interp->after_forkers_parent);
289 Py_CLEAR(interp->after_forkers_child);
290#endif
Eric Snow86ea5812019-05-10 13:29:55 -0400291 if (runtime->finalizing == NULL) {
292 _PyWarnings_Fini(interp);
293 }
Eric Snow5be45a62019-03-08 22:47:07 -0700294 // XXX Once we have one allocator per interpreter (i.e.
295 // per-interpreter GC) we must ensure that all of the interpreter's
296 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000297}
298
Victor Stinner0fd2c302019-06-04 03:15:09 +0200299void
300PyInterpreterState_Clear(PyInterpreterState *interp)
301{
302 _PyInterpreterState_Clear(&_PyRuntime, interp);
303}
304
Guido van Rossum25ce5661997-08-02 03:10:38 +0000305
306static void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200307zapthreads(_PyRuntimeState *runtime, PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000308{
Victor Stinner0fd2c302019-06-04 03:15:09 +0200309 PyThreadState *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 /* No need to lock the mutex here because this should only happen
311 when the threads are all really dead (XXX famous last words). */
Victor Stinner0fd2c302019-06-04 03:15:09 +0200312 while ((p = interp->tstate_head) != NULL) {
313 _PyThreadState_Delete(runtime, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000315}
316
317
Victor Stinner0fd2c302019-06-04 03:15:09 +0200318static void
319_PyInterpreterState_Delete(_PyRuntimeState *runtime,
320 PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200321{
322 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner0fd2c302019-06-04 03:15:09 +0200323 zapthreads(runtime, interp);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200324 HEAD_LOCK(runtime);
325 PyInterpreterState **p;
326 for (p = &interpreters->head; ; p = &(*p)->next) {
327 if (*p == NULL) {
328 Py_FatalError("PyInterpreterState_Delete: invalid interp");
329 }
330 if (*p == interp) {
331 break;
332 }
333 }
334 if (interp->tstate_head != NULL) {
335 Py_FatalError("PyInterpreterState_Delete: remaining threads");
336 }
337 *p = interp->next;
338 if (interpreters->main == interp) {
339 interpreters->main = NULL;
340 if (interpreters->head != NULL) {
341 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
342 }
343 }
344 HEAD_UNLOCK(runtime);
345 if (interp->id_mutex != NULL) {
346 PyThread_free_lock(interp->id_mutex);
347 }
348 PyMem_RawFree(interp);
349}
350
351
Victor Stinner0fd2c302019-06-04 03:15:09 +0200352void
353PyInterpreterState_Delete(PyInterpreterState *interp)
354{
355 _PyInterpreterState_Delete(&_PyRuntime, interp);
356}
357
358
Eric Snow59032962018-09-14 14:17:20 -0700359/*
360 * Delete all interpreter states except the main interpreter. If there
361 * is a current interpreter state, it *must* be the main interpreter.
362 */
363void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200364_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700365{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200366 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200367 struct pyinterpreters *interpreters = &runtime->interpreters;
368
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200369 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200370 if (tstate != NULL && tstate->interp != interpreters->main) {
Eric Snow59032962018-09-14 14:17:20 -0700371 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
372 }
373
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200374 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200375 PyInterpreterState *interp = interpreters->head;
376 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100377 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200378 if (interp == interpreters->main) {
379 interpreters->main->next = NULL;
380 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100381 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700382 continue;
383 }
384
Victor Stinner0fd2c302019-06-04 03:15:09 +0200385 _PyInterpreterState_Clear(runtime, interp); // XXX must activate?
386 zapthreads(runtime, interp);
Eric Snow59032962018-09-14 14:17:20 -0700387 if (interp->id_mutex != NULL) {
388 PyThread_free_lock(interp->id_mutex);
389 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100390 PyInterpreterState *prev_interp = interp;
391 interp = interp->next;
392 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700393 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200394 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700395
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200396 if (interpreters->head == NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700397 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
398 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200399 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700400}
401
402
Victor Stinnercaba55b2018-08-03 15:33:52 +0200403PyInterpreterState *
404_PyInterpreterState_Get(void)
405{
Victor Stinner50b48572018-11-01 01:51:40 +0100406 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200407 if (tstate == NULL) {
408 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
409 }
410 PyInterpreterState *interp = tstate->interp;
411 if (interp == NULL) {
412 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
413 }
414 return interp;
415}
416
417
Eric Snowe3774162017-05-22 19:46:40 -0700418int64_t
419PyInterpreterState_GetID(PyInterpreterState *interp)
420{
421 if (interp == NULL) {
422 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
423 return -1;
424 }
425 return interp->id;
426}
427
428
Eric Snow5be45a62019-03-08 22:47:07 -0700429static PyInterpreterState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200430interp_look_up_id(_PyRuntimeState *runtime, PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700431{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200432 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100433 while (interp != NULL) {
434 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700435 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100436 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700437 }
438 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100439 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700440 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100441 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700442 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100443 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700444}
445
Eric Snow5be45a62019-03-08 22:47:07 -0700446PyInterpreterState *
447_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
448{
449 PyInterpreterState *interp = NULL;
450 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200451 _PyRuntimeState *runtime = &_PyRuntime;
452 HEAD_LOCK(runtime);
453 interp = interp_look_up_id(runtime, requested_id);
454 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700455 }
456 if (interp == NULL && !PyErr_Occurred()) {
457 PyErr_Format(PyExc_RuntimeError,
458 "unrecognized interpreter ID %lld", requested_id);
459 }
460 return interp;
461}
462
Eric Snow4c6955e2018-02-16 18:53:40 -0700463
464int
465_PyInterpreterState_IDInitref(PyInterpreterState *interp)
466{
467 if (interp->id_mutex != NULL) {
468 return 0;
469 }
470 interp->id_mutex = PyThread_allocate_lock();
471 if (interp->id_mutex == NULL) {
472 PyErr_SetString(PyExc_RuntimeError,
473 "failed to create init interpreter ID mutex");
474 return -1;
475 }
476 interp->id_refcount = 0;
477 return 0;
478}
479
480
481void
482_PyInterpreterState_IDIncref(PyInterpreterState *interp)
483{
484 if (interp->id_mutex == NULL) {
485 return;
486 }
487 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
488 interp->id_refcount += 1;
489 PyThread_release_lock(interp->id_mutex);
490}
491
492
493void
494_PyInterpreterState_IDDecref(PyInterpreterState *interp)
495{
496 if (interp->id_mutex == NULL) {
497 return;
498 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200499 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700500 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
501 assert(interp->id_refcount != 0);
502 interp->id_refcount -= 1;
503 int64_t refcount = interp->id_refcount;
504 PyThread_release_lock(interp->id_mutex);
505
Eric Snowc11183c2019-03-15 16:35:46 -0600506 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700507 // XXX Using the "head" thread isn't strictly correct.
508 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
509 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200510 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700511 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200512 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700513 }
514}
515
Eric Snowc11183c2019-03-15 16:35:46 -0600516int
517_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
518{
519 return interp->requires_idref;
520}
521
522void
523_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
524{
525 interp->requires_idref = required ? 1 : 0;
526}
527
Eric Snowc11183c2019-03-15 16:35:46 -0600528PyObject *
529_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
530{
531 if (interp->modules == NULL) {
532 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
533 return NULL;
534 }
535 return PyMapping_GetItemString(interp->modules, "__main__");
536}
537
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600538PyObject *
539PyInterpreterState_GetDict(PyInterpreterState *interp)
540{
541 if (interp->dict == NULL) {
542 interp->dict = PyDict_New();
543 if (interp->dict == NULL) {
544 PyErr_Clear();
545 }
546 }
547 /* Returning NULL means no per-interpreter dict is available. */
548 return interp->dict;
549}
550
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000551/* Default implementation for _PyThreadState_GetFrame */
552static struct _frame *
553threadstate_getframe(PyThreadState *self)
554{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000556}
557
Victor Stinner45b9be52010-03-03 23:28:07 +0000558static PyThreadState *
559new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000560{
Victor Stinner0fd2c302019-06-04 03:15:09 +0200561 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200562 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200563 if (tstate == NULL) {
564 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566
Victor Stinner8bb32302019-04-24 16:47:40 +0200567 if (_PyThreadState_GetFrame == NULL) {
568 _PyThreadState_GetFrame = threadstate_getframe;
569 }
570
571 tstate->interp = interp;
572
573 tstate->frame = NULL;
574 tstate->recursion_depth = 0;
575 tstate->overflowed = 0;
576 tstate->recursion_critical = 0;
577 tstate->stackcheck_counter = 0;
578 tstate->tracing = 0;
579 tstate->use_tracing = 0;
580 tstate->gilstate_counter = 0;
581 tstate->async_exc = NULL;
582 tstate->thread_id = PyThread_get_thread_ident();
583
584 tstate->dict = NULL;
585
586 tstate->curexc_type = NULL;
587 tstate->curexc_value = NULL;
588 tstate->curexc_traceback = NULL;
589
590 tstate->exc_state.exc_type = NULL;
591 tstate->exc_state.exc_value = NULL;
592 tstate->exc_state.exc_traceback = NULL;
593 tstate->exc_state.previous_item = NULL;
594 tstate->exc_info = &tstate->exc_state;
595
596 tstate->c_profilefunc = NULL;
597 tstate->c_tracefunc = NULL;
598 tstate->c_profileobj = NULL;
599 tstate->c_traceobj = NULL;
600
601 tstate->trash_delete_nesting = 0;
602 tstate->trash_delete_later = NULL;
603 tstate->on_delete = NULL;
604 tstate->on_delete_data = NULL;
605
606 tstate->coroutine_origin_tracking_depth = 0;
607
Victor Stinner8bb32302019-04-24 16:47:40 +0200608 tstate->async_gen_firstiter = NULL;
609 tstate->async_gen_finalizer = NULL;
610
611 tstate->context = NULL;
612 tstate->context_ver = 1;
613
614 tstate->id = ++interp->tstate_next_unique_id;
615
616 if (init) {
Victor Stinner0fd2c302019-06-04 03:15:09 +0200617 _PyThreadState_Init(runtime, tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200618 }
619
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200620 HEAD_LOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200621 tstate->prev = NULL;
622 tstate->next = interp->tstate_head;
623 if (tstate->next)
624 tstate->next->prev = tstate;
625 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200626 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000629}
630
Victor Stinner45b9be52010-03-03 23:28:07 +0000631PyThreadState *
632PyThreadState_New(PyInterpreterState *interp)
633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000635}
636
637PyThreadState *
638_PyThreadState_Prealloc(PyInterpreterState *interp)
639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000641}
642
643void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200644_PyThreadState_Init(_PyRuntimeState *runtime, PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000645{
Victor Stinner8bb32302019-04-24 16:47:40 +0200646 _PyGILState_NoteThreadState(&runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000647}
648
Martin v. Löwis1a214512008-06-11 05:26:20 +0000649PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200650PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000651{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200652 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100653 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000655 if (module->m_slots) {
656 return NULL;
657 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 if (index == 0)
659 return NULL;
660 if (state->modules_by_index == NULL)
661 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200662 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 return NULL;
664 res = PyList_GET_ITEM(state->modules_by_index, index);
665 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000666}
667
668int
669_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
670{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000671 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300672 if (!def) {
673 assert(PyErr_Occurred());
674 return -1;
675 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000676 if (def->m_slots) {
677 PyErr_SetString(PyExc_SystemError,
678 "PyState_AddModule called on module with slots");
679 return -1;
680 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100681 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 if (!state->modules_by_index) {
683 state->modules_by_index = PyList_New(0);
684 if (!state->modules_by_index)
685 return -1;
686 }
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100687 while (PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 if (PyList_Append(state->modules_by_index, Py_None) < 0)
689 return -1;
690 Py_INCREF(module);
691 return PyList_SetItem(state->modules_by_index,
692 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000693}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000694
Martin v. Löwis7800f752012-06-22 12:20:55 +0200695int
696PyState_AddModule(PyObject* module, struct PyModuleDef* def)
697{
698 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100699 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200700 if (!def) {
701 Py_FatalError("PyState_AddModule: Module Definition is NULL");
702 return -1;
703 }
704 index = def->m_base.m_index;
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100705 if (state->modules_by_index &&
706 index < PyList_GET_SIZE(state->modules_by_index) &&
707 module == PyList_GET_ITEM(state->modules_by_index, index)) {
708 Py_FatalError("PyState_AddModule: Module already added!");
709 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200710 }
711 return _PyState_AddModule(module, def);
712}
713
714int
715PyState_RemoveModule(struct PyModuleDef* def)
716{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000717 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200718 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000719 if (def->m_slots) {
720 PyErr_SetString(PyExc_SystemError,
721 "PyState_RemoveModule called on module with slots");
722 return -1;
723 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100724 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200725 if (index == 0) {
726 Py_FatalError("PyState_RemoveModule: Module index invalid.");
727 return -1;
728 }
729 if (state->modules_by_index == NULL) {
Min ho Kim39d87b52019-08-31 06:21:19 +1000730 Py_FatalError("PyState_RemoveModule: Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200731 return -1;
732 }
733 if (index > PyList_GET_SIZE(state->modules_by_index)) {
734 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
735 return -1;
736 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700737 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200738 return PyList_SetItem(state->modules_by_index, index, Py_None);
739}
740
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200741/* Used by PyImport_Cleanup() */
Antoine Pitrou40322e62013-08-11 00:30:09 +0200742void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200743_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200744{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200745 if (!interp->modules_by_index) {
746 return;
747 }
748
749 Py_ssize_t i;
750 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
751 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
752 if (PyModule_Check(m)) {
753 /* cleanup the saved copy of module dicts */
754 PyModuleDef *md = PyModule_GetDef(m);
755 if (md) {
756 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200757 }
758 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200759 }
760
761 /* Setting modules_by_index to NULL could be dangerous, so we
762 clear the list instead. */
763 if (PyList_SetSlice(interp->modules_by_index,
764 0, PyList_GET_SIZE(interp->modules_by_index),
765 NULL)) {
766 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200767 }
768}
769
Guido van Rossuma027efa1997-05-05 20:56:21 +0000770void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000771PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000772{
Victor Stinner331a6a52019-05-27 16:39:22 +0200773 int verbose = tstate->interp->config.verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200774
775 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 fprintf(stderr,
777 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 Py_CLEAR(tstate->dict);
782 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 Py_CLEAR(tstate->curexc_type);
785 Py_CLEAR(tstate->curexc_value);
786 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000787
Mark Shannonae3087c2017-10-22 22:41:51 +0100788 Py_CLEAR(tstate->exc_state.exc_type);
789 Py_CLEAR(tstate->exc_state.exc_value);
790 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300791
Mark Shannonae3087c2017-10-22 22:41:51 +0100792 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200793 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100794 fprintf(stderr,
795 "PyThreadState_Clear: warning: thread still has a generator\n");
796 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 tstate->c_profilefunc = NULL;
799 tstate->c_tracefunc = NULL;
800 Py_CLEAR(tstate->c_profileobj);
801 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400802
Yury Selivanoveb636452016-09-08 22:01:51 -0700803 Py_CLEAR(tstate->async_gen_firstiter);
804 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500805
806 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000807}
808
809
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300810/* Common code for PyThreadState_Delete() and _PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000811static void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200812tstate_delete_common(_PyRuntimeState *runtime, PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000813{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200814 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 Py_FatalError("PyThreadState_Delete: NULL tstate");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200816 }
817 PyInterpreterState *interp = tstate->interp;
818 if (interp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 Py_FatalError("PyThreadState_Delete: NULL interp");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200820 }
821 HEAD_LOCK(runtime);
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200822 if (tstate->prev)
823 tstate->prev->next = tstate->next;
824 else
825 interp->tstate_head = tstate->next;
826 if (tstate->next)
827 tstate->next->prev = tstate->prev;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200828 HEAD_UNLOCK(runtime);
Antoine Pitrou7b476992013-09-07 23:38:37 +0200829 if (tstate->on_delete != NULL) {
830 tstate->on_delete(tstate->on_delete_data);
831 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200832 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000833}
834
835
Victor Stinner0fd2c302019-06-04 03:15:09 +0200836static void
837_PyThreadState_Delete(_PyRuntimeState *runtime, PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000838{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200839 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
840 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600842 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200843 if (gilstate->autoInterpreterState &&
844 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
845 {
846 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
847 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200848 tstate_delete_common(runtime, tstate);
849}
850
851
852void
853PyThreadState_Delete(PyThreadState *tstate)
854{
855 _PyThreadState_Delete(&_PyRuntime, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200856}
857
858
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300859void
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200860_PyThreadState_DeleteCurrent(_PyRuntimeState *runtime)
861{
862 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
863 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (tstate == NULL)
865 Py_FatalError(
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300866 "_PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner0fd2c302019-06-04 03:15:09 +0200867 tstate_delete_common(runtime, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200868 if (gilstate->autoInterpreterState &&
869 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600870 {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200871 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600872 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200873 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000875}
Guido van Rossum29757862001-01-23 01:46:06 +0000876
877
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200878/*
879 * Delete all thread states except the one passed as argument.
880 * Note that, if there is a current thread state, it *must* be the one
881 * passed as argument. Also, this won't touch any other interpreters
882 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000883 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200884 */
885void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200886_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200887{
888 PyInterpreterState *interp = tstate->interp;
889 PyThreadState *p, *next, *garbage;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200890 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200891 /* Remove all thread states, except tstate, from the linked list of
892 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200893 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200894 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200895 if (garbage == tstate)
896 garbage = tstate->next;
897 if (tstate->prev)
898 tstate->prev->next = tstate->next;
899 if (tstate->next)
900 tstate->next->prev = tstate->prev;
901 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200902 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200903 HEAD_UNLOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200904 /* Clear and deallocate all stale thread states. Even if this
905 executes Python code, we should be safe since it executes
906 in the current thread, not one of the stale threads. */
907 for (p = garbage; p; p = next) {
908 next = p->next;
909 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200910 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200911 }
912}
913
914
Guido van Rossuma027efa1997-05-05 20:56:21 +0000915PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100916_PyThreadState_UncheckedGet(void)
917{
Victor Stinner50b48572018-11-01 01:51:40 +0100918 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100919}
920
921
922PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000923PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000924{
Victor Stinner50b48572018-11-01 01:51:40 +0100925 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 if (tstate == NULL)
927 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000930}
931
932
Victor Stinner09532fe2019-05-10 23:39:09 +0200933PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200934_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000935{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200936 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000937
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200938 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 /* It should not be possible for more than one thread state
940 to be used for a thread. Check this the best we can in debug
941 builds.
942 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200943#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 if (newts) {
945 /* This can be called from PyEval_RestoreThread(). Similar
946 to it, we need to ensure errno doesn't change.
947 */
948 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200949 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 if (check && check->interp == newts->interp && check != newts)
951 Py_FatalError("Invalid thread state for this thread");
952 errno = err;
953 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000954#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000956}
Guido van Rossumede04391998-04-10 20:18:25 +0000957
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200958PyThreadState *
959PyThreadState_Swap(PyThreadState *newts)
960{
961 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
962}
963
Guido van Rossumede04391998-04-10 20:18:25 +0000964/* An extension mechanism to store arbitrary additional per-thread state.
965 PyThreadState_GetDict() returns a dictionary that can be used to hold such
966 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000967 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
968 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000969
970PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000971PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000972{
Victor Stinner50b48572018-11-01 01:51:40 +0100973 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (tstate == NULL)
975 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 if (tstate->dict == NULL) {
978 PyObject *d;
979 tstate->dict = d = PyDict_New();
980 if (d == NULL)
981 PyErr_Clear();
982 }
983 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000984}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000985
986
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000987/* Asynchronously raise an exception in a thread.
988 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000989 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000990 to call this, or use ctypes. Must be called with the GIL held.
991 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
992 match any known thread id). Can be called with exc=NULL to clear an
993 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000994
995int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200996PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
997{
Victor Stinner09532fe2019-05-10 23:39:09 +0200998 _PyRuntimeState *runtime = &_PyRuntime;
999 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 /* Although the GIL is held, a few C API functions can be called
1002 * without the GIL held, and in particular some that create and
1003 * destroy thread and interpreter states. Those can mutate the
1004 * list of thread states we're traversing, so to prevent that we lock
1005 * head_mutex for the duration.
1006 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001007 HEAD_LOCK(runtime);
Victor Stinner09532fe2019-05-10 23:39:09 +02001008 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (p->thread_id == id) {
1010 /* Tricky: we need to decref the current value
1011 * (if any) in p->async_exc, but that can in turn
1012 * allow arbitrary Python code to run, including
1013 * perhaps calls to this function. To prevent
1014 * deadlock, we need to release head_mutex before
1015 * the decref.
1016 */
1017 PyObject *old_exc = p->async_exc;
1018 Py_XINCREF(exc);
1019 p->async_exc = exc;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001020 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 Py_XDECREF(old_exc);
Victor Stinnere225beb2019-06-03 18:14:24 +02001022 _PyEval_SignalAsyncExc(&runtime->ceval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 return 1;
1024 }
1025 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001026 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001028}
1029
1030
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001031/* Routines for advanced debuggers, requested by David Beazley.
1032 Don't use unless you know what you are doing! */
1033
1034PyInterpreterState *
1035PyInterpreterState_Head(void)
1036{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001037 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001038}
1039
1040PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001041PyInterpreterState_Main(void)
1042{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001043 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001044}
1045
1046PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001047PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001049}
1050
1051PyThreadState *
1052PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001054}
1055
1056PyThreadState *
1057PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001059}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001060
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001061/* The implementation of sys._current_frames(). This is intended to be
1062 called with the GIL held, as it will be when called via
1063 sys._current_frames(). It's possible it would work fine even without
1064 the GIL held, but haven't thought enough about that.
1065*/
1066PyObject *
1067_PyThread_CurrentFrames(void)
1068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyObject *result;
1070 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001071
Steve Dowerb82e17e2019-05-23 08:45:22 -07001072 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1073 return NULL;
1074 }
1075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 result = PyDict_New();
1077 if (result == NULL)
1078 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 /* for i in all interpreters:
1081 * for t in all of i's thread states:
1082 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001083 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 * need to grab head_mutex for the duration.
1085 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001086 _PyRuntimeState *runtime = &_PyRuntime;
1087 HEAD_LOCK(runtime);
1088 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 PyThreadState *t;
1090 for (t = i->tstate_head; t != NULL; t = t->next) {
1091 PyObject *id;
1092 int stat;
1093 struct _frame *frame = t->frame;
1094 if (frame == NULL)
1095 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001096 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 if (id == NULL)
1098 goto Fail;
1099 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1100 Py_DECREF(id);
1101 if (stat < 0)
1102 goto Fail;
1103 }
1104 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001105 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001107
1108 Fail:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001109 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 Py_DECREF(result);
1111 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001112}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001113
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001114/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001115
1116/* Keep this as a static, as it is not reliable! It can only
1117 ever be compared to the state for the *current* thread.
1118 * If not equal, then it doesn't matter that the actual
1119 value may change immediately after comparison, as it can't
1120 possibly change to the current thread's state.
1121 * If equal, then the current thread holds the lock, so the value can't
1122 change until we yield the lock.
1123*/
1124static int
1125PyThreadState_IsCurrent(PyThreadState *tstate)
1126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001128 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001129 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1130 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001131}
1132
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001133/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001134 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001135*/
Tim Peters19717fa2004-10-09 17:38:29 +00001136void
Victor Stinnerb45d2592019-06-20 00:05:23 +02001137_PyGILState_Init(_PyRuntimeState *runtime, PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001138{
Victor Stinner8bb32302019-04-24 16:47:40 +02001139 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001140 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001141 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001142
Victor Stinner8bb32302019-04-24 16:47:40 +02001143 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1144
1145 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001146 Py_FatalError("Could not allocate TSS entry");
1147 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001148 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001149 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1150 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001151
Victor Stinner8bb32302019-04-24 16:47:40 +02001152 _PyGILState_NoteThreadState(gilstate, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001153}
1154
Victor Stinner861d9ab2016-03-16 22:45:24 +01001155PyInterpreterState *
1156_PyGILState_GetInterpreterStateUnsafe(void)
1157{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001158 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001159}
1160
Tim Peters19717fa2004-10-09 17:38:29 +00001161void
Victor Stinner8e91c242019-04-24 17:24:01 +02001162_PyGILState_Fini(_PyRuntimeState *runtime)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001163{
Victor Stinner8e91c242019-04-24 17:24:01 +02001164 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1165 PyThread_tss_delete(&gilstate->autoTSSkey);
1166 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001167}
1168
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001169/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001170 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001171 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001172 */
1173void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001174_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001175{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001176 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001177 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001178
1179 PyThread_tss_delete(&gilstate->autoTSSkey);
1180 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001181 Py_FatalError("Could not allocate TSS entry");
1182 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001183
Charles-François Natalia233df82011-11-22 19:49:51 +01001184 /* If the thread had an associated auto thread state, reassociate it with
1185 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001186 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001187 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001188 {
1189 Py_FatalError("Couldn't create autoTSSkey mapping");
1190 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001191}
1192
Michael W. Hudson188d4362005-06-20 16:52:57 +00001193/* When a thread state is created for a thread by some mechanism other than
1194 PyGILState_Ensure, it's important that the GILState machinery knows about
1195 it so it doesn't try to create another thread state for the thread (this is
1196 a better fix for SF bug #1010677 than the first one attempted).
1197*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001198static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001199_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001200{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001201 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001202 threadstate created in Py_Initialize(). Don't do anything for now
1203 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001204 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001206 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001207
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001208 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 The only situation where you can legitimately have more than one
1211 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001212 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001213
Victor Stinner590cebe2013-12-13 11:08:56 +01001214 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1215 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001216
Victor Stinner590cebe2013-12-13 11:08:56 +01001217 The first thread state created for that given OS level thread will
1218 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001220 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1221 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001222 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001223 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001224 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 /* PyGILState_Release must not try to delete this thread state. */
1227 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001228}
1229
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001230/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001231static PyThreadState *
1232_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1233{
1234 if (gilstate->autoInterpreterState == NULL)
1235 return NULL;
1236 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1237}
1238
Tim Peters19717fa2004-10-09 17:38:29 +00001239PyThreadState *
1240PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001241{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001242 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001243}
1244
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001245int
1246PyGILState_Check(void)
1247{
Victor Stinner8a1be612016-03-14 22:07:55 +01001248
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001249 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001250 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001251 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001252
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001253 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1254 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1255 return 1;
1256 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001257
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001258 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1259 if (tstate == NULL) {
1260 return 0;
1261 }
1262
1263 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001264}
1265
Tim Peters19717fa2004-10-09 17:38:29 +00001266PyGILState_STATE
1267PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001268{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001269 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 int current;
1271 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001272 int need_init_threads = 0;
1273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001274 /* Note that we do not auto-init Python here - apart from
1275 potential races with 2 threads auto-initializing, pep-311
1276 spells out other issues. Embedders are expected to have
1277 called Py_Initialize() and usually PyEval_InitThreads().
1278 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001279 /* Py_Initialize() hasn't been called! */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001280 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001281
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001282 tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001284 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 /* Create a new thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001287 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (tcur == NULL)
1289 Py_FatalError("Couldn't create thread-state for new thread");
1290 /* This is our thread state! We'll need to delete it in the
1291 matching call to PyGILState_Release(). */
1292 tcur->gilstate_counter = 0;
1293 current = 0; /* new thread state is never current */
1294 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001295 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001297 }
1298
1299 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001301 }
1302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 /* Update our counter in the thread-state - no need for locks:
1304 - tcur will remain valid as we hold the GIL.
1305 - the counter is safe as we are the only thread "allowed"
1306 to modify this value
1307 */
1308 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001309
1310 if (need_init_threads) {
1311 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1312 called from a new thread for the first time, we need the create the
1313 GIL. */
1314 PyEval_InitThreads();
1315 }
1316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001318}
1319
Tim Peters19717fa2004-10-09 17:38:29 +00001320void
1321PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001322{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001323 _PyRuntimeState *runtime = &_PyRuntime;
1324 PyThreadState *tcur = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1325 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 Py_FatalError("auto-releasing thread-state, "
1327 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001328 }
1329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 /* We must hold the GIL and have our thread state current */
1331 /* XXX - remove the check - the assert should be fine,
1332 but while this is very new (April 2003), the extra check
1333 by release-only users can't hurt.
1334 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001335 if (!PyThreadState_IsCurrent(tcur)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 Py_FatalError("This thread state must be current when releasing");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001337 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001338 assert(PyThreadState_IsCurrent(tcur));
1339 --tcur->gilstate_counter;
1340 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 /* If we're going to destroy this thread-state, we must
1343 * clear it while the GIL is held, as destructors may run.
1344 */
1345 if (tcur->gilstate_counter == 0) {
1346 /* can't have been locked when we created it */
1347 assert(oldstate == PyGILState_UNLOCKED);
1348 PyThreadState_Clear(tcur);
1349 /* Delete the thread-state. Note this releases the GIL too!
1350 * It's vital that the GIL be held here, to avoid shutdown
1351 * races; see bugs 225673 and 1061968 (that nasty bug has a
1352 * habit of coming back).
1353 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001354 _PyThreadState_DeleteCurrent(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 }
1356 /* Release the lock if necessary */
1357 else if (oldstate == PyGILState_UNLOCKED)
1358 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001359}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001360
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001361
Eric Snow7f8bfc92018-01-29 18:23:44 -07001362/**************************/
1363/* cross-interpreter data */
1364/**************************/
1365
1366/* cross-interpreter data */
1367
1368crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1369
1370/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1371 to keep the registry code separate. */
1372static crossinterpdatafunc
1373_lookup_getdata(PyObject *obj)
1374{
1375 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1376 if (getdata == NULL && PyErr_Occurred() == 0)
1377 PyErr_Format(PyExc_ValueError,
1378 "%S does not support cross-interpreter data", obj);
1379 return getdata;
1380}
1381
1382int
1383_PyObject_CheckCrossInterpreterData(PyObject *obj)
1384{
1385 crossinterpdatafunc getdata = _lookup_getdata(obj);
1386 if (getdata == NULL) {
1387 return -1;
1388 }
1389 return 0;
1390}
1391
1392static int
1393_check_xidata(_PyCrossInterpreterData *data)
1394{
1395 // data->data can be anything, including NULL, so we don't check it.
1396
1397 // data->obj may be NULL, so we don't check it.
1398
1399 if (data->interp < 0) {
1400 PyErr_SetString(PyExc_SystemError, "missing interp");
1401 return -1;
1402 }
1403
1404 if (data->new_object == NULL) {
1405 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1406 return -1;
1407 }
1408
1409 // data->free may be NULL, so we don't check it.
1410
1411 return 0;
1412}
1413
1414int
1415_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1416{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001417 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001418 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001419 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001420
1421 // Reset data before re-populating.
1422 *data = (_PyCrossInterpreterData){0};
1423 data->free = PyMem_RawFree; // Set a default that may be overridden.
1424
1425 // Call the "getdata" func for the object.
1426 Py_INCREF(obj);
1427 crossinterpdatafunc getdata = _lookup_getdata(obj);
1428 if (getdata == NULL) {
1429 Py_DECREF(obj);
1430 return -1;
1431 }
1432 int res = getdata(obj, data);
1433 Py_DECREF(obj);
1434 if (res != 0) {
1435 return -1;
1436 }
1437
1438 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001439 data->interp = interp->id;
1440 if (_check_xidata(data) != 0) {
1441 _PyCrossInterpreterData_Release(data);
1442 return -1;
1443 }
1444
1445 return 0;
1446}
1447
Victor Stinnere225beb2019-06-03 18:14:24 +02001448static void
Eric Snow63799132018-06-01 18:45:20 -06001449_release_xidata(void *arg)
1450{
1451 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1452 if (data->free != NULL) {
1453 data->free(data->data);
1454 }
1455 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001456}
1457
1458static void
1459_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1460 PyInterpreterState *interp,
1461 void (*func)(void *), void *arg)
1462{
1463 /* We would use Py_AddPendingCall() if it weren't specific to the
1464 * main interpreter (see bpo-33608). In the meantime we take a
1465 * naive approach.
1466 */
1467 PyThreadState *save_tstate = NULL;
1468 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1469 // XXX Using the "head" thread isn't strictly correct.
1470 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1471 // XXX Possible GILState issues?
1472 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1473 }
1474
1475 func(arg);
1476
1477 // Switch back.
1478 if (save_tstate != NULL) {
1479 _PyThreadState_Swap(gilstate, save_tstate);
1480 }
Eric Snow63799132018-06-01 18:45:20 -06001481}
1482
Eric Snow7f8bfc92018-01-29 18:23:44 -07001483void
1484_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1485{
1486 if (data->data == NULL && data->obj == NULL) {
1487 // Nothing to release!
1488 return;
1489 }
1490
Victor Stinnere225beb2019-06-03 18:14:24 +02001491 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001492 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1493 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001494 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001495 if (data->free != NULL) {
1496 // XXX Someone leaked some memory...
1497 }
1498 return;
1499 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001500
Eric Snow7f8bfc92018-01-29 18:23:44 -07001501 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001502 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1503 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001504}
1505
1506PyObject *
1507_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1508{
1509 return data->new_object(data);
1510}
1511
1512/* registry of {type -> crossinterpdatafunc} */
1513
1514/* For now we use a global registry of shareable classes. An
1515 alternative would be to add a tp_* slot for a class's
1516 crossinterpdatafunc. It would be simpler and more efficient. */
1517
1518static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001519_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1520 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001521{
1522 // Note that we effectively replace already registered classes
1523 // rather than failing.
1524 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1525 if (newhead == NULL)
1526 return -1;
1527 newhead->cls = cls;
1528 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001529 newhead->next = xidregistry->head;
1530 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001531 return 0;
1532}
1533
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001534static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001535
1536int
Eric Snowc11183c2019-03-15 16:35:46 -06001537_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001538 crossinterpdatafunc getdata)
1539{
1540 if (!PyType_Check(cls)) {
1541 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1542 return -1;
1543 }
1544 if (getdata == NULL) {
1545 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1546 return -1;
1547 }
1548
1549 // Make sure the class isn't ever deallocated.
1550 Py_INCREF((PyObject *)cls);
1551
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001552 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1553 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1554 if (xidregistry->head == NULL) {
1555 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001556 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001557 int res = _register_xidata(xidregistry, cls, getdata);
1558 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001559 return res;
1560}
1561
Eric Snow6d2cd902018-05-16 15:04:57 -04001562/* Cross-interpreter objects are looked up by exact match on the class.
1563 We can reassess this policy when we move from a global registry to a
1564 tp_* slot. */
1565
Eric Snow7f8bfc92018-01-29 18:23:44 -07001566crossinterpdatafunc
1567_PyCrossInterpreterData_Lookup(PyObject *obj)
1568{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001569 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001570 PyObject *cls = PyObject_Type(obj);
1571 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001572 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1573 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001574 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001575 _register_builtins_for_crossinterpreter_data(xidregistry);
1576 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001577 }
1578 for(; cur != NULL; cur = cur->next) {
1579 if (cur->cls == (PyTypeObject *)cls) {
1580 getdata = cur->getdata;
1581 break;
1582 }
1583 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001584 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001585 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001586 return getdata;
1587}
1588
1589/* cross-interpreter data for builtin types */
1590
Eric Snow6d2cd902018-05-16 15:04:57 -04001591struct _shared_bytes_data {
1592 char *bytes;
1593 Py_ssize_t len;
1594};
1595
Eric Snow7f8bfc92018-01-29 18:23:44 -07001596static PyObject *
1597_new_bytes_object(_PyCrossInterpreterData *data)
1598{
Eric Snow6d2cd902018-05-16 15:04:57 -04001599 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1600 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001601}
1602
1603static int
1604_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1605{
Eric Snow6d2cd902018-05-16 15:04:57 -04001606 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1607 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1608 return -1;
1609 }
1610 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001611 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001612 data->obj = obj; // Will be "released" (decref'ed) when data released.
1613 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001614 data->free = PyMem_Free;
1615 return 0;
1616}
1617
1618struct _shared_str_data {
1619 int kind;
1620 const void *buffer;
1621 Py_ssize_t len;
1622};
1623
1624static PyObject *
1625_new_str_object(_PyCrossInterpreterData *data)
1626{
1627 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1628 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1629}
1630
1631static int
1632_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1633{
1634 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1635 shared->kind = PyUnicode_KIND(obj);
1636 shared->buffer = PyUnicode_DATA(obj);
1637 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1638 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001639 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001640 data->obj = obj; // Will be "released" (decref'ed) when data released.
1641 data->new_object = _new_str_object;
1642 data->free = PyMem_Free;
1643 return 0;
1644}
1645
1646static PyObject *
1647_new_long_object(_PyCrossInterpreterData *data)
1648{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001649 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001650}
1651
1652static int
1653_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1654{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001655 /* Note that this means the size of shareable ints is bounded by
1656 * sys.maxsize. Hence on 32-bit architectures that is half the
1657 * size of maximum shareable ints on 64-bit.
1658 */
1659 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001660 if (value == -1 && PyErr_Occurred()) {
1661 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1662 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1663 }
1664 return -1;
1665 }
1666 data->data = (void *)value;
1667 data->obj = NULL;
1668 data->new_object = _new_long_object;
1669 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001670 return 0;
1671}
1672
1673static PyObject *
1674_new_none_object(_PyCrossInterpreterData *data)
1675{
1676 // XXX Singleton refcounts are problematic across interpreters...
1677 Py_INCREF(Py_None);
1678 return Py_None;
1679}
1680
1681static int
1682_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1683{
1684 data->data = NULL;
1685 // data->obj remains NULL
1686 data->new_object = _new_none_object;
1687 data->free = NULL; // There is nothing to free.
1688 return 0;
1689}
1690
1691static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001692_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001693{
1694 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001695 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001696 Py_FatalError("could not register None for cross-interpreter sharing");
1697 }
1698
Eric Snow6d2cd902018-05-16 15:04:57 -04001699 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001700 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001701 Py_FatalError("could not register int for cross-interpreter sharing");
1702 }
1703
Eric Snow7f8bfc92018-01-29 18:23:44 -07001704 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001705 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001706 Py_FatalError("could not register bytes for cross-interpreter sharing");
1707 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001708
1709 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001710 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001711 Py_FatalError("could not register str for cross-interpreter sharing");
1712 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001713}
1714
1715
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001716#ifdef __cplusplus
1717}
1718#endif