blob: 2fc563bf5836d93fa18a56a660efec38e3f550ad [file] [log] [blame]
Guido van Rossuma027efa1997-05-05 20:56:21 +00001
2/* Thread and interpreter state structures and their interfaces */
3
4#include "Python.h"
Victor Stinner09532fe2019-05-10 23:39:09 +02005#include "pycore_ceval.h"
Victor Stinner331a6a52019-05-27 16:39:22 +02006#include "pycore_initconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01007#include "pycore_pymem.h"
8#include "pycore_pystate.h"
Eric Snow86ea5812019-05-10 13:29:55 -04009#include "pycore_pylifecycle.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +000010
Tim Peters84705582004-10-10 02:47:33 +000011/* --------------------------------------------------------------------------
12CAUTION
13
Victor Stinner1a7425f2013-07-07 16:25:15 +020014Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
15number of these functions are advertised as safe to call when the GIL isn't
16held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
17debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
18to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000019-------------------------------------------------------------------------- */
20
Martin v. Löwisf0473d52001-07-18 16:17:16 +000021#ifdef HAVE_DLOPEN
22#ifdef HAVE_DLFCN_H
23#include <dlfcn.h>
24#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030025#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000026#define RTLD_LAZY 1
27#endif
28#endif
29
Benjamin Peterson43162b82012-04-13 11:58:27 -040030#ifdef __cplusplus
31extern "C" {
32#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000033
Victor Stinner10c8e6a2019-04-26 01:53:18 +020034#define _PyRuntimeGILState_GetThreadState(gilstate) \
35 ((PyThreadState*)_Py_atomic_load_relaxed(&(gilstate)->tstate_current))
36#define _PyRuntimeGILState_SetThreadState(gilstate, value) \
37 _Py_atomic_store_relaxed(&(gilstate)->tstate_current, \
38 (uintptr_t)(value))
39
40/* Forward declarations */
41static PyThreadState *_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate);
Victor Stinner9da74302019-11-20 11:17:17 +010042static void _PyThreadState_Delete(PyThreadState *tstate, int check_current);
Victor Stinner10c8e6a2019-04-26 01:53:18 +020043
44
Victor Stinner331a6a52019-05-27 16:39:22 +020045static PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010046_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060047{
Steve Dowerb82e17e2019-05-23 08:45:22 -070048 /* We preserve the hook across init, because there is
49 currently no public API to set it between runtime
50 initialization and interpreter initialization. */
51 void *open_code_hook = runtime->open_code_hook;
52 void *open_code_userdata = runtime->open_code_userdata;
53 _Py_AuditHookEntry *audit_hook_head = runtime->audit_hook_head;
54
Eric Snow2ebc5ce2017-09-07 23:51:28 -060055 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010056
Steve Dowerb82e17e2019-05-23 08:45:22 -070057 runtime->open_code_hook = open_code_hook;
58 runtime->open_code_userdata = open_code_userdata;
59 runtime->audit_hook_head = audit_hook_head;
60
Eric Snow2ebc5ce2017-09-07 23:51:28 -060061 _PyEval_Initialize(&runtime->ceval);
Victor Stinner441b10c2019-09-28 04:28:35 +020062
Victor Stinner3c30a762019-10-01 10:56:37 +020063 PyPreConfig_InitPythonConfig(&runtime->preconfig);
Michael W. Hudson188d4362005-06-20 16:52:57 +000064
Eric Snow2ebc5ce2017-09-07 23:51:28 -060065 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080066
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090067 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
68 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080069 Py_tss_t initial = Py_tss_NEEDS_INIT;
70 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000071
Eric Snow2ebc5ce2017-09-07 23:51:28 -060072 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080073 if (runtime->interpreters.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020074 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080075 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060076 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070077
78 runtime->xidregistry.mutex = PyThread_allocate_lock();
79 if (runtime->xidregistry.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020080 return _PyStatus_ERR("Can't initialize threads for cross-interpreter data registry");
Eric Snow7f8bfc92018-01-29 18:23:44 -070081 }
82
Eric Snow8479a342019-03-08 23:44:33 -070083 // Set it to the ID of the main thread of the main interpreter.
84 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070085
Victor Stinner331a6a52019-05-27 16:39:22 +020086 return _PyStatus_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060087}
Eric Snow05351c12017-09-05 21:43:08 -070088
Victor Stinner331a6a52019-05-27 16:39:22 +020089PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010090_PyRuntimeState_Init(_PyRuntimeState *runtime)
91{
92 /* Force default allocator, since _PyRuntimeState_Fini() must
93 use the same allocator than this function. */
94 PyMemAllocatorEx old_alloc;
95 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
96
Victor Stinner331a6a52019-05-27 16:39:22 +020097 PyStatus status = _PyRuntimeState_Init_impl(runtime);
Victor Stinner5d39e042017-11-29 17:20:38 +010098
99 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinner331a6a52019-05-27 16:39:22 +0200100 return status;
Victor Stinner5d39e042017-11-29 17:20:38 +0100101}
102
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600103void
104_PyRuntimeState_Fini(_PyRuntimeState *runtime)
105{
Victor Stinner5d39e042017-11-29 17:20:38 +0100106 /* Force the allocator used by _PyRuntimeState_Init(). */
107 PyMemAllocatorEx old_alloc;
108 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -0800109
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600110 if (runtime->interpreters.mutex != NULL) {
111 PyThread_free_lock(runtime->interpreters.mutex);
112 runtime->interpreters.mutex = NULL;
113 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800114
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100115 if (runtime->xidregistry.mutex != NULL) {
116 PyThread_free_lock(runtime->xidregistry.mutex);
117 runtime->xidregistry.mutex = NULL;
118 }
119
Victor Stinnerccb04422017-11-16 03:20:31 -0800120 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600121}
122
Eric Snow8479a342019-03-08 23:44:33 -0700123/* This function is called from PyOS_AfterFork_Child to ensure that
124 * newly created child processes do not share locks with the parent.
125 */
126
127void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200128_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700129{
130 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200131 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700132
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200133 /* Force default allocator, since _PyRuntimeState_Fini() must
134 use the same allocator than this function. */
135 PyMemAllocatorEx old_alloc;
136 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
137
138 runtime->interpreters.mutex = PyThread_allocate_lock();
139 runtime->interpreters.main->id_mutex = PyThread_allocate_lock();
140 runtime->xidregistry.mutex = PyThread_allocate_lock();
141
142 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
143
144 if (runtime->interpreters.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700145 Py_FatalError("Can't initialize lock for runtime interpreters");
146 }
147
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200148 if (runtime->interpreters.main->id_mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700149 Py_FatalError("Can't initialize ID lock for main interpreter");
150 }
151
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200152 if (runtime->xidregistry.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700153 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
154 }
155}
156
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200157#define HEAD_LOCK(runtime) \
158 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
159#define HEAD_UNLOCK(runtime) \
160 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700161
Victor 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 Stinner01b1cc12019-11-20 02:27:56 +0100207 _PyRuntimeState *runtime = &_PyRuntime;
208 interp->runtime = runtime;
209
Victor Stinner72474072019-11-20 12:25:50 +0100210 _PyGC_InitState(&interp->gc);
Victor Stinner8462a492019-10-01 12:06:16 +0200211 PyConfig_InitPythonConfig(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200212
Victor Stinnerd4341102017-11-23 00:12:09 +0100213 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000214#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300215#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100216 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000217#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100218 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000219#endif
220#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000221
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200222 struct pyinterpreters *interpreters = &runtime->interpreters;
223
224 HEAD_LOCK(runtime);
225 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100226 /* overflow or Py_Initialize() not called! */
227 PyErr_SetString(PyExc_RuntimeError,
228 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100229 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100230 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100231 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200232 else {
233 interp->id = interpreters->next_id;
234 interpreters->next_id += 1;
235 interp->next = interpreters->head;
236 if (interpreters->main == NULL) {
237 interpreters->main = interp;
238 }
239 interpreters->head = interp;
240 }
241 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000242
Pablo Galindo95d630e2018-08-31 22:49:29 +0100243 if (interp == NULL) {
244 return NULL;
245 }
246
Yury Selivanovf23746a2018-01-22 19:11:18 -0500247 interp->tstate_next_unique_id = 0;
248
Steve Dowerb82e17e2019-05-23 08:45:22 -0700249 interp->audit_hooks = NULL;
250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000252}
253
254
Victor Stinner01b1cc12019-11-20 02:27:56 +0100255void
256PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000257{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100258 _PyRuntimeState *runtime = interp->runtime;
259
Steve Dowerb82e17e2019-05-23 08:45:22 -0700260 if (PySys_Audit("cpython.PyInterpreterState_Clear", NULL) < 0) {
261 PyErr_Clear();
262 }
263
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200264 HEAD_LOCK(runtime);
265 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200267 }
268 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700269
270 Py_CLEAR(interp->audit_hooks);
271
Victor Stinner331a6a52019-05-27 16:39:22 +0200272 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 Py_CLEAR(interp->codec_search_path);
274 Py_CLEAR(interp->codec_search_cache);
275 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700276 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 Py_CLEAR(interp->sysdict);
279 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200280 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400281 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300282 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600283 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200284#ifdef HAVE_FORK
285 Py_CLEAR(interp->before_forkers);
286 Py_CLEAR(interp->after_forkers_parent);
287 Py_CLEAR(interp->after_forkers_child);
288#endif
Eric Snow86ea5812019-05-10 13:29:55 -0400289 if (runtime->finalizing == NULL) {
290 _PyWarnings_Fini(interp);
291 }
Eric Snow5be45a62019-03-08 22:47:07 -0700292 // XXX Once we have one allocator per interpreter (i.e.
293 // per-interpreter GC) we must ensure that all of the interpreter's
294 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000295}
296
297
298static void
Victor Stinner9da74302019-11-20 11:17:17 +0100299zapthreads(PyInterpreterState *interp, int check_current)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000300{
Victor Stinner9da74302019-11-20 11:17:17 +0100301 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 /* No need to lock the mutex here because this should only happen
303 when the threads are all really dead (XXX famous last words). */
Victor Stinner9da74302019-11-20 11:17:17 +0100304 while ((tstate = interp->tstate_head) != NULL) {
305 _PyThreadState_Delete(tstate, check_current);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000307}
308
309
Victor Stinner01b1cc12019-11-20 02:27:56 +0100310void
311PyInterpreterState_Delete(PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200312{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100313 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200314 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner9da74302019-11-20 11:17:17 +0100315 zapthreads(interp, 0);
316
317 /* Delete current thread. After this, many C API calls become crashy. */
318 _PyThreadState_Swap(&runtime->gilstate, NULL);
319
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200320 HEAD_LOCK(runtime);
321 PyInterpreterState **p;
322 for (p = &interpreters->head; ; p = &(*p)->next) {
323 if (*p == NULL) {
324 Py_FatalError("PyInterpreterState_Delete: invalid interp");
325 }
326 if (*p == interp) {
327 break;
328 }
329 }
330 if (interp->tstate_head != NULL) {
331 Py_FatalError("PyInterpreterState_Delete: remaining threads");
332 }
333 *p = interp->next;
334 if (interpreters->main == interp) {
335 interpreters->main = NULL;
336 if (interpreters->head != NULL) {
337 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
338 }
339 }
340 HEAD_UNLOCK(runtime);
341 if (interp->id_mutex != NULL) {
342 PyThread_free_lock(interp->id_mutex);
343 }
344 PyMem_RawFree(interp);
345}
346
347
Eric Snow59032962018-09-14 14:17:20 -0700348/*
349 * Delete all interpreter states except the main interpreter. If there
350 * is a current interpreter state, it *must* be the main interpreter.
351 */
352void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200353_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700354{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200355 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200356 struct pyinterpreters *interpreters = &runtime->interpreters;
357
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200358 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200359 if (tstate != NULL && tstate->interp != interpreters->main) {
Eric Snow59032962018-09-14 14:17:20 -0700360 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
361 }
362
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200363 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200364 PyInterpreterState *interp = interpreters->head;
365 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100366 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200367 if (interp == interpreters->main) {
368 interpreters->main->next = NULL;
369 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100370 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700371 continue;
372 }
373
Victor Stinner01b1cc12019-11-20 02:27:56 +0100374 PyInterpreterState_Clear(interp); // XXX must activate?
Victor Stinner9da74302019-11-20 11:17:17 +0100375 zapthreads(interp, 1);
Eric Snow59032962018-09-14 14:17:20 -0700376 if (interp->id_mutex != NULL) {
377 PyThread_free_lock(interp->id_mutex);
378 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100379 PyInterpreterState *prev_interp = interp;
380 interp = interp->next;
381 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700382 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200383 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700384
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200385 if (interpreters->head == NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700386 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
387 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200388 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700389}
390
391
Victor Stinnercaba55b2018-08-03 15:33:52 +0200392PyInterpreterState *
393_PyInterpreterState_Get(void)
394{
Victor Stinner50b48572018-11-01 01:51:40 +0100395 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200396 if (tstate == NULL) {
397 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
398 }
399 PyInterpreterState *interp = tstate->interp;
400 if (interp == NULL) {
401 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
402 }
403 return interp;
404}
405
406
Eric Snowe3774162017-05-22 19:46:40 -0700407int64_t
408PyInterpreterState_GetID(PyInterpreterState *interp)
409{
410 if (interp == NULL) {
411 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
412 return -1;
413 }
414 return interp->id;
415}
416
417
Eric Snow5be45a62019-03-08 22:47:07 -0700418static PyInterpreterState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200419interp_look_up_id(_PyRuntimeState *runtime, PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700420{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200421 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100422 while (interp != NULL) {
423 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700424 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100425 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700426 }
427 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100428 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700429 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100430 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700431 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100432 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700433}
434
Eric Snow5be45a62019-03-08 22:47:07 -0700435PyInterpreterState *
436_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
437{
438 PyInterpreterState *interp = NULL;
439 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200440 _PyRuntimeState *runtime = &_PyRuntime;
441 HEAD_LOCK(runtime);
442 interp = interp_look_up_id(runtime, requested_id);
443 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700444 }
445 if (interp == NULL && !PyErr_Occurred()) {
446 PyErr_Format(PyExc_RuntimeError,
447 "unrecognized interpreter ID %lld", requested_id);
448 }
449 return interp;
450}
451
Eric Snow4c6955e2018-02-16 18:53:40 -0700452
453int
454_PyInterpreterState_IDInitref(PyInterpreterState *interp)
455{
456 if (interp->id_mutex != NULL) {
457 return 0;
458 }
459 interp->id_mutex = PyThread_allocate_lock();
460 if (interp->id_mutex == NULL) {
461 PyErr_SetString(PyExc_RuntimeError,
462 "failed to create init interpreter ID mutex");
463 return -1;
464 }
465 interp->id_refcount = 0;
466 return 0;
467}
468
469
470void
471_PyInterpreterState_IDIncref(PyInterpreterState *interp)
472{
473 if (interp->id_mutex == NULL) {
474 return;
475 }
476 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
477 interp->id_refcount += 1;
478 PyThread_release_lock(interp->id_mutex);
479}
480
481
482void
483_PyInterpreterState_IDDecref(PyInterpreterState *interp)
484{
485 if (interp->id_mutex == NULL) {
486 return;
487 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200488 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700489 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
490 assert(interp->id_refcount != 0);
491 interp->id_refcount -= 1;
492 int64_t refcount = interp->id_refcount;
493 PyThread_release_lock(interp->id_mutex);
494
Eric Snowc11183c2019-03-15 16:35:46 -0600495 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700496 // XXX Using the "head" thread isn't strictly correct.
497 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
498 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200499 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700500 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200501 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700502 }
503}
504
Eric Snowc11183c2019-03-15 16:35:46 -0600505int
506_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
507{
508 return interp->requires_idref;
509}
510
511void
512_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
513{
514 interp->requires_idref = required ? 1 : 0;
515}
516
Eric Snowc11183c2019-03-15 16:35:46 -0600517PyObject *
518_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
519{
520 if (interp->modules == NULL) {
521 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
522 return NULL;
523 }
524 return PyMapping_GetItemString(interp->modules, "__main__");
525}
526
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600527PyObject *
528PyInterpreterState_GetDict(PyInterpreterState *interp)
529{
530 if (interp->dict == NULL) {
531 interp->dict = PyDict_New();
532 if (interp->dict == NULL) {
533 PyErr_Clear();
534 }
535 }
536 /* Returning NULL means no per-interpreter dict is available. */
537 return interp->dict;
538}
539
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000540/* Default implementation for _PyThreadState_GetFrame */
541static struct _frame *
542threadstate_getframe(PyThreadState *self)
543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000545}
546
Victor Stinner45b9be52010-03-03 23:28:07 +0000547static PyThreadState *
548new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000549{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100550 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200551 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200552 if (tstate == NULL) {
553 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000555
Victor Stinner8bb32302019-04-24 16:47:40 +0200556 if (_PyThreadState_GetFrame == NULL) {
557 _PyThreadState_GetFrame = threadstate_getframe;
558 }
559
560 tstate->interp = interp;
561
562 tstate->frame = NULL;
563 tstate->recursion_depth = 0;
564 tstate->overflowed = 0;
565 tstate->recursion_critical = 0;
566 tstate->stackcheck_counter = 0;
567 tstate->tracing = 0;
568 tstate->use_tracing = 0;
569 tstate->gilstate_counter = 0;
570 tstate->async_exc = NULL;
571 tstate->thread_id = PyThread_get_thread_ident();
572
573 tstate->dict = NULL;
574
575 tstate->curexc_type = NULL;
576 tstate->curexc_value = NULL;
577 tstate->curexc_traceback = NULL;
578
579 tstate->exc_state.exc_type = NULL;
580 tstate->exc_state.exc_value = NULL;
581 tstate->exc_state.exc_traceback = NULL;
582 tstate->exc_state.previous_item = NULL;
583 tstate->exc_info = &tstate->exc_state;
584
585 tstate->c_profilefunc = NULL;
586 tstate->c_tracefunc = NULL;
587 tstate->c_profileobj = NULL;
588 tstate->c_traceobj = NULL;
589
590 tstate->trash_delete_nesting = 0;
591 tstate->trash_delete_later = NULL;
592 tstate->on_delete = NULL;
593 tstate->on_delete_data = NULL;
594
595 tstate->coroutine_origin_tracking_depth = 0;
596
Victor Stinner8bb32302019-04-24 16:47:40 +0200597 tstate->async_gen_firstiter = NULL;
598 tstate->async_gen_finalizer = NULL;
599
600 tstate->context = NULL;
601 tstate->context_ver = 1;
602
603 tstate->id = ++interp->tstate_next_unique_id;
604
605 if (init) {
Victor Stinner01b1cc12019-11-20 02:27:56 +0100606 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200607 }
608
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200609 HEAD_LOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200610 tstate->prev = NULL;
611 tstate->next = interp->tstate_head;
612 if (tstate->next)
613 tstate->next->prev = tstate;
614 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200615 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000618}
619
Victor Stinner45b9be52010-03-03 23:28:07 +0000620PyThreadState *
621PyThreadState_New(PyInterpreterState *interp)
622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000624}
625
626PyThreadState *
627_PyThreadState_Prealloc(PyInterpreterState *interp)
628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000630}
631
632void
Victor Stinner01b1cc12019-11-20 02:27:56 +0100633_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000634{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100635 _PyGILState_NoteThreadState(&tstate->interp->runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000636}
637
Martin v. Löwis1a214512008-06-11 05:26:20 +0000638PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200639PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000640{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200641 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100642 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000644 if (module->m_slots) {
645 return NULL;
646 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 if (index == 0)
648 return NULL;
649 if (state->modules_by_index == NULL)
650 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200651 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 return NULL;
653 res = PyList_GET_ITEM(state->modules_by_index, index);
654 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000655}
656
657int
658_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
659{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000660 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300661 if (!def) {
662 assert(PyErr_Occurred());
663 return -1;
664 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000665 if (def->m_slots) {
666 PyErr_SetString(PyExc_SystemError,
667 "PyState_AddModule called on module with slots");
668 return -1;
669 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100670 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 if (!state->modules_by_index) {
672 state->modules_by_index = PyList_New(0);
673 if (!state->modules_by_index)
674 return -1;
675 }
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100676 while (PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 if (PyList_Append(state->modules_by_index, Py_None) < 0)
678 return -1;
679 Py_INCREF(module);
680 return PyList_SetItem(state->modules_by_index,
681 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000682}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000683
Martin v. Löwis7800f752012-06-22 12:20:55 +0200684int
685PyState_AddModule(PyObject* module, struct PyModuleDef* def)
686{
687 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100688 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200689 if (!def) {
690 Py_FatalError("PyState_AddModule: Module Definition is NULL");
691 return -1;
692 }
693 index = def->m_base.m_index;
Benjamin Peterson39de95b2019-09-12 00:43:22 +0100694 if (state->modules_by_index &&
695 index < PyList_GET_SIZE(state->modules_by_index) &&
696 module == PyList_GET_ITEM(state->modules_by_index, index)) {
697 Py_FatalError("PyState_AddModule: Module already added!");
698 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200699 }
700 return _PyState_AddModule(module, def);
701}
702
703int
704PyState_RemoveModule(struct PyModuleDef* def)
705{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000706 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200707 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000708 if (def->m_slots) {
709 PyErr_SetString(PyExc_SystemError,
710 "PyState_RemoveModule called on module with slots");
711 return -1;
712 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100713 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200714 if (index == 0) {
715 Py_FatalError("PyState_RemoveModule: Module index invalid.");
716 return -1;
717 }
718 if (state->modules_by_index == NULL) {
Min ho Kim39d87b52019-08-31 06:21:19 +1000719 Py_FatalError("PyState_RemoveModule: Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200720 return -1;
721 }
722 if (index > PyList_GET_SIZE(state->modules_by_index)) {
723 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
724 return -1;
725 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700726 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200727 return PyList_SetItem(state->modules_by_index, index, Py_None);
728}
729
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200730/* Used by PyImport_Cleanup() */
Antoine Pitrou40322e62013-08-11 00:30:09 +0200731void
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200732_PyInterpreterState_ClearModules(PyInterpreterState *interp)
Antoine Pitrou40322e62013-08-11 00:30:09 +0200733{
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200734 if (!interp->modules_by_index) {
735 return;
736 }
737
738 Py_ssize_t i;
739 for (i = 0; i < PyList_GET_SIZE(interp->modules_by_index); i++) {
740 PyObject *m = PyList_GET_ITEM(interp->modules_by_index, i);
741 if (PyModule_Check(m)) {
742 /* cleanup the saved copy of module dicts */
743 PyModuleDef *md = PyModule_GetDef(m);
744 if (md) {
745 Py_CLEAR(md->m_base.m_copy);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200746 }
747 }
Victor Stinner0a28f8d2019-06-19 02:54:39 +0200748 }
749
750 /* Setting modules_by_index to NULL could be dangerous, so we
751 clear the list instead. */
752 if (PyList_SetSlice(interp->modules_by_index,
753 0, PyList_GET_SIZE(interp->modules_by_index),
754 NULL)) {
755 PyErr_WriteUnraisable(interp->modules_by_index);
Antoine Pitrou40322e62013-08-11 00:30:09 +0200756 }
757}
758
Guido van Rossuma027efa1997-05-05 20:56:21 +0000759void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000760PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000761{
Victor Stinner331a6a52019-05-27 16:39:22 +0200762 int verbose = tstate->interp->config.verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200763
764 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 fprintf(stderr,
766 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 Py_CLEAR(tstate->dict);
771 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 Py_CLEAR(tstate->curexc_type);
774 Py_CLEAR(tstate->curexc_value);
775 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000776
Mark Shannonae3087c2017-10-22 22:41:51 +0100777 Py_CLEAR(tstate->exc_state.exc_type);
778 Py_CLEAR(tstate->exc_state.exc_value);
779 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300780
Mark Shannonae3087c2017-10-22 22:41:51 +0100781 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200782 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100783 fprintf(stderr,
784 "PyThreadState_Clear: warning: thread still has a generator\n");
785 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 tstate->c_profilefunc = NULL;
788 tstate->c_tracefunc = NULL;
789 Py_CLEAR(tstate->c_profileobj);
790 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400791
Yury Selivanoveb636452016-09-08 22:01:51 -0700792 Py_CLEAR(tstate->async_gen_firstiter);
793 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500794
795 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000796}
797
798
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300799/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
Guido van Rossum29757862001-01-23 01:46:06 +0000800static void
Victor Stinner9da74302019-11-20 11:17:17 +0100801tstate_delete_common(PyThreadState *tstate,
802 struct _gilstate_runtime_state *gilstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000803{
Victor Stinner01b1cc12019-11-20 02:27:56 +0100804 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200805 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 Py_FatalError("PyThreadState_Delete: NULL tstate");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200807 }
808 PyInterpreterState *interp = tstate->interp;
809 if (interp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 Py_FatalError("PyThreadState_Delete: NULL interp");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200811 }
812 HEAD_LOCK(runtime);
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200813 if (tstate->prev)
814 tstate->prev->next = tstate->next;
815 else
816 interp->tstate_head = tstate->next;
817 if (tstate->next)
818 tstate->next->prev = tstate->prev;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200819 HEAD_UNLOCK(runtime);
Antoine Pitrou7b476992013-09-07 23:38:37 +0200820 if (tstate->on_delete != NULL) {
821 tstate->on_delete(tstate->on_delete_data);
822 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200823 PyMem_RawFree(tstate);
Victor Stinner9da74302019-11-20 11:17:17 +0100824
825 if (gilstate->autoInterpreterState &&
826 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
827 {
828 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
829 }
830}
831
832
833static void
834_PyThreadState_Delete(PyThreadState *tstate, int check_current)
835{
836 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
837 if (check_current) {
838 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
839 Py_FatalError("PyThreadState_Delete: tstate is still current");
840 }
841 }
842 tstate_delete_common(tstate, gilstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000843}
844
845
Victor Stinner01b1cc12019-11-20 02:27:56 +0100846void
847PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000848{
Victor Stinner9da74302019-11-20 11:17:17 +0100849 _PyThreadState_Delete(tstate, 1);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200850}
851
852
Joannah Nanjekye2bc43cd2019-09-05 13:06:49 -0300853void
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200854_PyThreadState_DeleteCurrent(_PyRuntimeState *runtime)
855{
856 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
857 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 if (tstate == NULL)
859 Py_FatalError(
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300860 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner9da74302019-11-20 11:17:17 +0100861 tstate_delete_common(tstate, gilstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200862 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000864}
Guido van Rossum29757862001-01-23 01:46:06 +0000865
Joannah Nanjekye8855e472019-10-04 08:35:42 -0300866void
867PyThreadState_DeleteCurrent(void)
868{
869 _PyThreadState_DeleteCurrent(&_PyRuntime);
870}
871
Guido van Rossum29757862001-01-23 01:46:06 +0000872
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200873/*
874 * Delete all thread states except the one passed as argument.
875 * Note that, if there is a current thread state, it *must* be the one
876 * passed as argument. Also, this won't touch any other interpreters
877 * than the current one, since we don't know which thread state should
Min ho Kim39d87b52019-08-31 06:21:19 +1000878 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200879 */
880void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200881_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200882{
883 PyInterpreterState *interp = tstate->interp;
884 PyThreadState *p, *next, *garbage;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200885 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200886 /* Remove all thread states, except tstate, from the linked list of
887 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200888 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200889 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200890 if (garbage == tstate)
891 garbage = tstate->next;
892 if (tstate->prev)
893 tstate->prev->next = tstate->next;
894 if (tstate->next)
895 tstate->next->prev = tstate->prev;
896 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200897 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200898 HEAD_UNLOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200899 /* Clear and deallocate all stale thread states. Even if this
900 executes Python code, we should be safe since it executes
901 in the current thread, not one of the stale threads. */
902 for (p = garbage; p; p = next) {
903 next = p->next;
904 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200905 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200906 }
907}
908
909
Guido van Rossuma027efa1997-05-05 20:56:21 +0000910PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100911_PyThreadState_UncheckedGet(void)
912{
Victor Stinner50b48572018-11-01 01:51:40 +0100913 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100914}
915
916
917PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000918PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000919{
Victor Stinner50b48572018-11-01 01:51:40 +0100920 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 if (tstate == NULL)
922 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000925}
926
927
Victor Stinner09532fe2019-05-10 23:39:09 +0200928PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200929_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000930{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200931 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000932
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200933 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 /* It should not be possible for more than one thread state
935 to be used for a thread. Check this the best we can in debug
936 builds.
937 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200938#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 if (newts) {
940 /* This can be called from PyEval_RestoreThread(). Similar
941 to it, we need to ensure errno doesn't change.
942 */
943 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200944 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 if (check && check->interp == newts->interp && check != newts)
946 Py_FatalError("Invalid thread state for this thread");
947 errno = err;
948 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000949#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000951}
Guido van Rossumede04391998-04-10 20:18:25 +0000952
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200953PyThreadState *
954PyThreadState_Swap(PyThreadState *newts)
955{
956 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
957}
958
Guido van Rossumede04391998-04-10 20:18:25 +0000959/* An extension mechanism to store arbitrary additional per-thread state.
960 PyThreadState_GetDict() returns a dictionary that can be used to hold such
961 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000962 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
963 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000964
965PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000966PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000967{
Victor Stinner50b48572018-11-01 01:51:40 +0100968 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 if (tstate == NULL)
970 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 if (tstate->dict == NULL) {
973 PyObject *d;
974 tstate->dict = d = PyDict_New();
975 if (d == NULL)
976 PyErr_Clear();
977 }
978 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000979}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000980
981
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000982/* Asynchronously raise an exception in a thread.
983 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000984 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000985 to call this, or use ctypes. Must be called with the GIL held.
986 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
987 match any known thread id). Can be called with exc=NULL to clear an
988 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000989
990int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200991PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
992{
Victor Stinner09532fe2019-05-10 23:39:09 +0200993 _PyRuntimeState *runtime = &_PyRuntime;
994 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 /* Although the GIL is held, a few C API functions can be called
997 * without the GIL held, and in particular some that create and
998 * destroy thread and interpreter states. Those can mutate the
999 * list of thread states we're traversing, so to prevent that we lock
1000 * head_mutex for the duration.
1001 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001002 HEAD_LOCK(runtime);
Victor Stinner09532fe2019-05-10 23:39:09 +02001003 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 if (p->thread_id == id) {
1005 /* Tricky: we need to decref the current value
1006 * (if any) in p->async_exc, but that can in turn
1007 * allow arbitrary Python code to run, including
1008 * perhaps calls to this function. To prevent
1009 * deadlock, we need to release head_mutex before
1010 * the decref.
1011 */
1012 PyObject *old_exc = p->async_exc;
1013 Py_XINCREF(exc);
1014 p->async_exc = exc;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001015 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 Py_XDECREF(old_exc);
Victor Stinnere225beb2019-06-03 18:14:24 +02001017 _PyEval_SignalAsyncExc(&runtime->ceval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 return 1;
1019 }
1020 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001021 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001023}
1024
1025
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001026/* Routines for advanced debuggers, requested by David Beazley.
1027 Don't use unless you know what you are doing! */
1028
1029PyInterpreterState *
1030PyInterpreterState_Head(void)
1031{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001032 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001033}
1034
1035PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001036PyInterpreterState_Main(void)
1037{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001038 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001039}
1040
1041PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001042PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001044}
1045
1046PyThreadState *
1047PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001049}
1050
1051PyThreadState *
1052PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001054}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001055
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001056/* The implementation of sys._current_frames(). This is intended to be
1057 called with the GIL held, as it will be when called via
1058 sys._current_frames(). It's possible it would work fine even without
1059 the GIL held, but haven't thought enough about that.
1060*/
1061PyObject *
1062_PyThread_CurrentFrames(void)
1063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 PyObject *result;
1065 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001066
Steve Dowerb82e17e2019-05-23 08:45:22 -07001067 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1068 return NULL;
1069 }
1070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 result = PyDict_New();
1072 if (result == NULL)
1073 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 /* for i in all interpreters:
1076 * for t in all of i's thread states:
1077 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001078 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 * need to grab head_mutex for the duration.
1080 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001081 _PyRuntimeState *runtime = &_PyRuntime;
1082 HEAD_LOCK(runtime);
1083 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 PyThreadState *t;
1085 for (t = i->tstate_head; t != NULL; t = t->next) {
1086 PyObject *id;
1087 int stat;
1088 struct _frame *frame = t->frame;
1089 if (frame == NULL)
1090 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001091 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 if (id == NULL)
1093 goto Fail;
1094 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1095 Py_DECREF(id);
1096 if (stat < 0)
1097 goto Fail;
1098 }
1099 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001100 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001102
1103 Fail:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001104 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 Py_DECREF(result);
1106 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001107}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001108
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001109/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001110
1111/* Keep this as a static, as it is not reliable! It can only
1112 ever be compared to the state for the *current* thread.
1113 * If not equal, then it doesn't matter that the actual
1114 value may change immediately after comparison, as it can't
1115 possibly change to the current thread's state.
1116 * If equal, then the current thread holds the lock, so the value can't
1117 change until we yield the lock.
1118*/
1119static int
1120PyThreadState_IsCurrent(PyThreadState *tstate)
1121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001123 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001124 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1125 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001126}
1127
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001128/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001129 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001130*/
Tim Peters19717fa2004-10-09 17:38:29 +00001131void
Victor Stinner01b1cc12019-11-20 02:27:56 +01001132_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001133{
Victor Stinner8bb32302019-04-24 16:47:40 +02001134 /* must init with valid states */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001135 assert(tstate != NULL);
Victor Stinnerb45d2592019-06-20 00:05:23 +02001136 assert(tstate->interp != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001137
Victor Stinner01b1cc12019-11-20 02:27:56 +01001138 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8bb32302019-04-24 16:47:40 +02001139
1140 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001141 Py_FatalError("Could not allocate TSS entry");
1142 }
Victor Stinnerb45d2592019-06-20 00:05:23 +02001143 gilstate->autoInterpreterState = tstate->interp;
Victor Stinner8bb32302019-04-24 16:47:40 +02001144 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1145 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001146
Victor Stinner8bb32302019-04-24 16:47:40 +02001147 _PyGILState_NoteThreadState(gilstate, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001148}
1149
Victor Stinner861d9ab2016-03-16 22:45:24 +01001150PyInterpreterState *
1151_PyGILState_GetInterpreterStateUnsafe(void)
1152{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001153 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001154}
1155
Tim Peters19717fa2004-10-09 17:38:29 +00001156void
Victor Stinner7eee5be2019-11-20 10:38:34 +01001157_PyGILState_Fini(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001158{
Victor Stinner7eee5be2019-11-20 10:38:34 +01001159 struct _gilstate_runtime_state *gilstate = &tstate->interp->runtime->gilstate;
Victor Stinner8e91c242019-04-24 17:24:01 +02001160 PyThread_tss_delete(&gilstate->autoTSSkey);
1161 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001162}
1163
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001164/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001165 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001166 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001167 */
1168void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001169_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001170{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001171 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001172 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001173
1174 PyThread_tss_delete(&gilstate->autoTSSkey);
1175 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001176 Py_FatalError("Could not allocate TSS entry");
1177 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001178
Charles-François Natalia233df82011-11-22 19:49:51 +01001179 /* If the thread had an associated auto thread state, reassociate it with
1180 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001181 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001182 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001183 {
1184 Py_FatalError("Couldn't create autoTSSkey mapping");
1185 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001186}
1187
Michael W. Hudson188d4362005-06-20 16:52:57 +00001188/* When a thread state is created for a thread by some mechanism other than
1189 PyGILState_Ensure, it's important that the GILState machinery knows about
1190 it so it doesn't try to create another thread state for the thread (this is
1191 a better fix for SF bug #1010677 than the first one attempted).
1192*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001193static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001194_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001195{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001196 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001197 threadstate created in Py_Initialize(). Don't do anything for now
1198 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001199 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001201 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001202
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001203 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 The only situation where you can legitimately have more than one
1206 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001207 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001208
Victor Stinner590cebe2013-12-13 11:08:56 +01001209 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1210 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001211
Victor Stinner590cebe2013-12-13 11:08:56 +01001212 The first thread state created for that given OS level thread will
1213 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001215 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1216 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001217 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001218 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001219 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 /* PyGILState_Release must not try to delete this thread state. */
1222 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001223}
1224
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001225/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001226static PyThreadState *
1227_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1228{
1229 if (gilstate->autoInterpreterState == NULL)
1230 return NULL;
1231 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1232}
1233
Tim Peters19717fa2004-10-09 17:38:29 +00001234PyThreadState *
1235PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001236{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001237 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001238}
1239
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001240int
1241PyGILState_Check(void)
1242{
Victor Stinner8a1be612016-03-14 22:07:55 +01001243
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001244 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001245 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001246 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001247
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001248 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1249 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1250 return 1;
1251 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001252
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001253 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1254 if (tstate == NULL) {
1255 return 0;
1256 }
1257
1258 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001259}
1260
Tim Peters19717fa2004-10-09 17:38:29 +00001261PyGILState_STATE
1262PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001263{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001264 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001265 int current;
1266 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001267 int need_init_threads = 0;
1268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 /* Note that we do not auto-init Python here - apart from
1270 potential races with 2 threads auto-initializing, pep-311
1271 spells out other issues. Embedders are expected to have
1272 called Py_Initialize() and usually PyEval_InitThreads().
1273 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001274 /* Py_Initialize() hasn't been called! */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001275 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001276
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001277 tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001279 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 /* Create a new thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001282 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 if (tcur == NULL)
1284 Py_FatalError("Couldn't create thread-state for new thread");
1285 /* This is our thread state! We'll need to delete it in the
1286 matching call to PyGILState_Release(). */
1287 tcur->gilstate_counter = 0;
1288 current = 0; /* new thread state is never current */
1289 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001290 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001292 }
1293
1294 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001296 }
1297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 /* Update our counter in the thread-state - no need for locks:
1299 - tcur will remain valid as we hold the GIL.
1300 - the counter is safe as we are the only thread "allowed"
1301 to modify this value
1302 */
1303 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001304
1305 if (need_init_threads) {
1306 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1307 called from a new thread for the first time, we need the create the
1308 GIL. */
1309 PyEval_InitThreads();
1310 }
1311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001313}
1314
Tim Peters19717fa2004-10-09 17:38:29 +00001315void
1316PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001317{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001318 _PyRuntimeState *runtime = &_PyRuntime;
1319 PyThreadState *tcur = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1320 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 Py_FatalError("auto-releasing thread-state, "
1322 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001323 }
1324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 /* We must hold the GIL and have our thread state current */
1326 /* XXX - remove the check - the assert should be fine,
1327 but while this is very new (April 2003), the extra check
1328 by release-only users can't hurt.
1329 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001330 if (!PyThreadState_IsCurrent(tcur)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 Py_FatalError("This thread state must be current when releasing");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001332 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 assert(PyThreadState_IsCurrent(tcur));
1334 --tcur->gilstate_counter;
1335 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 /* If we're going to destroy this thread-state, we must
1338 * clear it while the GIL is held, as destructors may run.
1339 */
1340 if (tcur->gilstate_counter == 0) {
1341 /* can't have been locked when we created it */
1342 assert(oldstate == PyGILState_UNLOCKED);
1343 PyThreadState_Clear(tcur);
1344 /* Delete the thread-state. Note this releases the GIL too!
1345 * It's vital that the GIL be held here, to avoid shutdown
1346 * races; see bugs 225673 and 1061968 (that nasty bug has a
1347 * habit of coming back).
1348 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001349 _PyThreadState_DeleteCurrent(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 }
1351 /* Release the lock if necessary */
1352 else if (oldstate == PyGILState_UNLOCKED)
1353 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001354}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001355
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001356
Eric Snow7f8bfc92018-01-29 18:23:44 -07001357/**************************/
1358/* cross-interpreter data */
1359/**************************/
1360
1361/* cross-interpreter data */
1362
1363crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1364
1365/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1366 to keep the registry code separate. */
1367static crossinterpdatafunc
1368_lookup_getdata(PyObject *obj)
1369{
1370 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1371 if (getdata == NULL && PyErr_Occurred() == 0)
1372 PyErr_Format(PyExc_ValueError,
1373 "%S does not support cross-interpreter data", obj);
1374 return getdata;
1375}
1376
1377int
1378_PyObject_CheckCrossInterpreterData(PyObject *obj)
1379{
1380 crossinterpdatafunc getdata = _lookup_getdata(obj);
1381 if (getdata == NULL) {
1382 return -1;
1383 }
1384 return 0;
1385}
1386
1387static int
1388_check_xidata(_PyCrossInterpreterData *data)
1389{
1390 // data->data can be anything, including NULL, so we don't check it.
1391
1392 // data->obj may be NULL, so we don't check it.
1393
1394 if (data->interp < 0) {
1395 PyErr_SetString(PyExc_SystemError, "missing interp");
1396 return -1;
1397 }
1398
1399 if (data->new_object == NULL) {
1400 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1401 return -1;
1402 }
1403
1404 // data->free may be NULL, so we don't check it.
1405
1406 return 0;
1407}
1408
1409int
1410_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1411{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001412 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001413 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001414 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001415
1416 // Reset data before re-populating.
1417 *data = (_PyCrossInterpreterData){0};
1418 data->free = PyMem_RawFree; // Set a default that may be overridden.
1419
1420 // Call the "getdata" func for the object.
1421 Py_INCREF(obj);
1422 crossinterpdatafunc getdata = _lookup_getdata(obj);
1423 if (getdata == NULL) {
1424 Py_DECREF(obj);
1425 return -1;
1426 }
1427 int res = getdata(obj, data);
1428 Py_DECREF(obj);
1429 if (res != 0) {
1430 return -1;
1431 }
1432
1433 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001434 data->interp = interp->id;
1435 if (_check_xidata(data) != 0) {
1436 _PyCrossInterpreterData_Release(data);
1437 return -1;
1438 }
1439
1440 return 0;
1441}
1442
Victor Stinnere225beb2019-06-03 18:14:24 +02001443static void
Eric Snow63799132018-06-01 18:45:20 -06001444_release_xidata(void *arg)
1445{
1446 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1447 if (data->free != NULL) {
1448 data->free(data->data);
1449 }
1450 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001451}
1452
1453static void
1454_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1455 PyInterpreterState *interp,
1456 void (*func)(void *), void *arg)
1457{
1458 /* We would use Py_AddPendingCall() if it weren't specific to the
1459 * main interpreter (see bpo-33608). In the meantime we take a
1460 * naive approach.
1461 */
1462 PyThreadState *save_tstate = NULL;
1463 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1464 // XXX Using the "head" thread isn't strictly correct.
1465 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1466 // XXX Possible GILState issues?
1467 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1468 }
1469
1470 func(arg);
1471
1472 // Switch back.
1473 if (save_tstate != NULL) {
1474 _PyThreadState_Swap(gilstate, save_tstate);
1475 }
Eric Snow63799132018-06-01 18:45:20 -06001476}
1477
Eric Snow7f8bfc92018-01-29 18:23:44 -07001478void
1479_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1480{
1481 if (data->data == NULL && data->obj == NULL) {
1482 // Nothing to release!
1483 return;
1484 }
1485
Victor Stinnere225beb2019-06-03 18:14:24 +02001486 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001487 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1488 if (interp == NULL) {
Min ho Kimc4cacc82019-07-31 08:16:13 +10001489 // The interpreter was already destroyed.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001490 if (data->free != NULL) {
1491 // XXX Someone leaked some memory...
1492 }
1493 return;
1494 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001495
Eric Snow7f8bfc92018-01-29 18:23:44 -07001496 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001497 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1498 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001499}
1500
1501PyObject *
1502_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1503{
1504 return data->new_object(data);
1505}
1506
1507/* registry of {type -> crossinterpdatafunc} */
1508
1509/* For now we use a global registry of shareable classes. An
1510 alternative would be to add a tp_* slot for a class's
1511 crossinterpdatafunc. It would be simpler and more efficient. */
1512
1513static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001514_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1515 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001516{
1517 // Note that we effectively replace already registered classes
1518 // rather than failing.
1519 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1520 if (newhead == NULL)
1521 return -1;
1522 newhead->cls = cls;
1523 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001524 newhead->next = xidregistry->head;
1525 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001526 return 0;
1527}
1528
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001529static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001530
1531int
Eric Snowc11183c2019-03-15 16:35:46 -06001532_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001533 crossinterpdatafunc getdata)
1534{
1535 if (!PyType_Check(cls)) {
1536 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1537 return -1;
1538 }
1539 if (getdata == NULL) {
1540 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1541 return -1;
1542 }
1543
1544 // Make sure the class isn't ever deallocated.
1545 Py_INCREF((PyObject *)cls);
1546
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001547 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1548 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1549 if (xidregistry->head == NULL) {
1550 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001551 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001552 int res = _register_xidata(xidregistry, cls, getdata);
1553 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001554 return res;
1555}
1556
Eric Snow6d2cd902018-05-16 15:04:57 -04001557/* Cross-interpreter objects are looked up by exact match on the class.
1558 We can reassess this policy when we move from a global registry to a
1559 tp_* slot. */
1560
Eric Snow7f8bfc92018-01-29 18:23:44 -07001561crossinterpdatafunc
1562_PyCrossInterpreterData_Lookup(PyObject *obj)
1563{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001564 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001565 PyObject *cls = PyObject_Type(obj);
1566 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001567 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1568 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001569 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001570 _register_builtins_for_crossinterpreter_data(xidregistry);
1571 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001572 }
1573 for(; cur != NULL; cur = cur->next) {
1574 if (cur->cls == (PyTypeObject *)cls) {
1575 getdata = cur->getdata;
1576 break;
1577 }
1578 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001579 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001580 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001581 return getdata;
1582}
1583
1584/* cross-interpreter data for builtin types */
1585
Eric Snow6d2cd902018-05-16 15:04:57 -04001586struct _shared_bytes_data {
1587 char *bytes;
1588 Py_ssize_t len;
1589};
1590
Eric Snow7f8bfc92018-01-29 18:23:44 -07001591static PyObject *
1592_new_bytes_object(_PyCrossInterpreterData *data)
1593{
Eric Snow6d2cd902018-05-16 15:04:57 -04001594 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1595 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001596}
1597
1598static int
1599_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1600{
Eric Snow6d2cd902018-05-16 15:04:57 -04001601 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1602 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1603 return -1;
1604 }
1605 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001606 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001607 data->obj = obj; // Will be "released" (decref'ed) when data released.
1608 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001609 data->free = PyMem_Free;
1610 return 0;
1611}
1612
1613struct _shared_str_data {
1614 int kind;
1615 const void *buffer;
1616 Py_ssize_t len;
1617};
1618
1619static PyObject *
1620_new_str_object(_PyCrossInterpreterData *data)
1621{
1622 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1623 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1624}
1625
1626static int
1627_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1628{
1629 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1630 shared->kind = PyUnicode_KIND(obj);
1631 shared->buffer = PyUnicode_DATA(obj);
1632 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1633 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001634 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001635 data->obj = obj; // Will be "released" (decref'ed) when data released.
1636 data->new_object = _new_str_object;
1637 data->free = PyMem_Free;
1638 return 0;
1639}
1640
1641static PyObject *
1642_new_long_object(_PyCrossInterpreterData *data)
1643{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001644 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001645}
1646
1647static int
1648_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1649{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001650 /* Note that this means the size of shareable ints is bounded by
1651 * sys.maxsize. Hence on 32-bit architectures that is half the
1652 * size of maximum shareable ints on 64-bit.
1653 */
1654 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001655 if (value == -1 && PyErr_Occurred()) {
1656 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1657 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1658 }
1659 return -1;
1660 }
1661 data->data = (void *)value;
1662 data->obj = NULL;
1663 data->new_object = _new_long_object;
1664 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001665 return 0;
1666}
1667
1668static PyObject *
1669_new_none_object(_PyCrossInterpreterData *data)
1670{
1671 // XXX Singleton refcounts are problematic across interpreters...
1672 Py_INCREF(Py_None);
1673 return Py_None;
1674}
1675
1676static int
1677_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1678{
1679 data->data = NULL;
1680 // data->obj remains NULL
1681 data->new_object = _new_none_object;
1682 data->free = NULL; // There is nothing to free.
1683 return 0;
1684}
1685
1686static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001687_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001688{
1689 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001690 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001691 Py_FatalError("could not register None for cross-interpreter sharing");
1692 }
1693
Eric Snow6d2cd902018-05-16 15:04:57 -04001694 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001695 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001696 Py_FatalError("could not register int for cross-interpreter sharing");
1697 }
1698
Eric Snow7f8bfc92018-01-29 18:23:44 -07001699 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001700 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001701 Py_FatalError("could not register bytes for cross-interpreter sharing");
1702 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001703
1704 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001705 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001706 Py_FatalError("could not register str for cross-interpreter sharing");
1707 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001708}
1709
1710
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001711#ifdef __cplusplus
1712}
1713#endif