blob: 2b7db0e48debe9e1857160f35ba43a22ca2bd124 [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 Stinner10c8e6a2019-04-26 01:53:18 +020042
43
Victor Stinner331a6a52019-05-27 16:39:22 +020044static PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010045_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060046{
Steve Dowerb82e17e2019-05-23 08:45:22 -070047 /* We preserve the hook across init, because there is
48 currently no public API to set it between runtime
49 initialization and interpreter initialization. */
50 void *open_code_hook = runtime->open_code_hook;
51 void *open_code_userdata = runtime->open_code_userdata;
52 _Py_AuditHookEntry *audit_hook_head = runtime->audit_hook_head;
53
Eric Snow2ebc5ce2017-09-07 23:51:28 -060054 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010055
Steve Dowerb82e17e2019-05-23 08:45:22 -070056 runtime->open_code_hook = open_code_hook;
57 runtime->open_code_userdata = open_code_userdata;
58 runtime->audit_hook_head = audit_hook_head;
59
Eric Snow2ebc5ce2017-09-07 23:51:28 -060060 _PyGC_Initialize(&runtime->gc);
61 _PyEval_Initialize(&runtime->ceval);
Victor Stinner331a6a52019-05-27 16:39:22 +020062 PyPreConfig_InitPythonConfig(&runtime->preconfig);
Michael W. Hudson188d4362005-06-20 16:52:57 +000063
Eric Snow2ebc5ce2017-09-07 23:51:28 -060064 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080065
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090066 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
67 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080068 Py_tss_t initial = Py_tss_NEEDS_INIT;
69 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000070
Eric Snow2ebc5ce2017-09-07 23:51:28 -060071 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080072 if (runtime->interpreters.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020073 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080074 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060075 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070076
77 runtime->xidregistry.mutex = PyThread_allocate_lock();
78 if (runtime->xidregistry.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020079 return _PyStatus_ERR("Can't initialize threads for cross-interpreter data registry");
Eric Snow7f8bfc92018-01-29 18:23:44 -070080 }
81
Eric Snow8479a342019-03-08 23:44:33 -070082 // Set it to the ID of the main thread of the main interpreter.
83 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070084
Victor Stinner331a6a52019-05-27 16:39:22 +020085 return _PyStatus_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060086}
Eric Snow05351c12017-09-05 21:43:08 -070087
Victor Stinner331a6a52019-05-27 16:39:22 +020088PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010089_PyRuntimeState_Init(_PyRuntimeState *runtime)
90{
91 /* Force default allocator, since _PyRuntimeState_Fini() must
92 use the same allocator than this function. */
93 PyMemAllocatorEx old_alloc;
94 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
95
Victor Stinner331a6a52019-05-27 16:39:22 +020096 PyStatus status = _PyRuntimeState_Init_impl(runtime);
Victor Stinner5d39e042017-11-29 17:20:38 +010097
98 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinner331a6a52019-05-27 16:39:22 +020099 return status;
Victor Stinner5d39e042017-11-29 17:20:38 +0100100}
101
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600102void
103_PyRuntimeState_Fini(_PyRuntimeState *runtime)
104{
Victor Stinner5d39e042017-11-29 17:20:38 +0100105 /* Force the allocator used by _PyRuntimeState_Init(). */
106 PyMemAllocatorEx old_alloc;
107 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -0800108
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600109 if (runtime->interpreters.mutex != NULL) {
110 PyThread_free_lock(runtime->interpreters.mutex);
111 runtime->interpreters.mutex = NULL;
112 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800113
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100114 if (runtime->xidregistry.mutex != NULL) {
115 PyThread_free_lock(runtime->xidregistry.mutex);
116 runtime->xidregistry.mutex = NULL;
117 }
118
Victor Stinnerccb04422017-11-16 03:20:31 -0800119 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600120}
121
Eric Snow8479a342019-03-08 23:44:33 -0700122/* This function is called from PyOS_AfterFork_Child to ensure that
123 * newly created child processes do not share locks with the parent.
124 */
125
126void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200127_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700128{
129 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200130 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700131
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200132 /* Force default allocator, since _PyRuntimeState_Fini() must
133 use the same allocator than this function. */
134 PyMemAllocatorEx old_alloc;
135 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
136
137 runtime->interpreters.mutex = PyThread_allocate_lock();
138 runtime->interpreters.main->id_mutex = PyThread_allocate_lock();
139 runtime->xidregistry.mutex = PyThread_allocate_lock();
140
141 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
142
143 if (runtime->interpreters.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700144 Py_FatalError("Can't initialize lock for runtime interpreters");
145 }
146
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200147 if (runtime->interpreters.main->id_mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700148 Py_FatalError("Can't initialize ID lock for main interpreter");
149 }
150
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200151 if (runtime->xidregistry.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700152 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
153 }
154}
155
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200156#define HEAD_LOCK(runtime) \
157 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
158#define HEAD_UNLOCK(runtime) \
159 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700160
Victor Stinner8bb32302019-04-24 16:47:40 +0200161/* Forward declaration */
162static void _PyGILState_NoteThreadState(
163 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000164
Victor Stinner331a6a52019-05-27 16:39:22 +0200165PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600166_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700167{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200168 struct pyinterpreters *interpreters = &runtime->interpreters;
169 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100170
171 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
172 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200173 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100174 /* Force default allocator, since _PyRuntimeState_Fini() must
175 use the same allocator than this function. */
176 PyMemAllocatorEx old_alloc;
177 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
178
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200179 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100180
181 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
182
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200183 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200184 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800185 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600186 }
Victor Stinner5d926472018-03-06 14:31:37 +0100187
Victor Stinner331a6a52019-05-27 16:39:22 +0200188 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700189}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000190
191PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000192PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000193{
Eric Snow396e0a82019-05-31 21:16:47 -0600194 _PyRuntimeState *runtime = &_PyRuntime;
195
Steve Dowerb82e17e2019-05-23 08:45:22 -0700196 if (PySys_Audit("cpython.PyInterpreterState_New", NULL) < 0) {
197 return NULL;
198 }
199
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200200 PyInterpreterState *interp = PyMem_RawMalloc(sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100201 if (interp == NULL) {
202 return NULL;
203 }
204
Eric Snow5be45a62019-03-08 22:47:07 -0700205 memset(interp, 0, sizeof(*interp));
Eric Snow396e0a82019-05-31 21:16:47 -0600206
207 interp->runtime = runtime;
208
Eric Snow4c6955e2018-02-16 18:53:40 -0700209 interp->id_refcount = -1;
Victor Stinnerd4341102017-11-23 00:12:09 +0100210 interp->check_interval = 100;
Victor Stinner022be022019-05-22 23:58:50 +0200211
Victor Stinner331a6a52019-05-27 16:39:22 +0200212 PyStatus status = PyConfig_InitPythonConfig(&interp->config);
213 if (_PyStatus_EXCEPTION(status)) {
214 /* Don't report status to caller: PyConfig_InitPythonConfig()
215 can only fail with a memory allocation error. */
216 PyConfig_Clear(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200217 PyMem_RawFree(interp);
218 return NULL;
219 }
220
Victor Stinnerd4341102017-11-23 00:12:09 +0100221 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000222#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300223#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100224 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000225#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100226 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000227#endif
228#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000229
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200230 struct pyinterpreters *interpreters = &runtime->interpreters;
231
232 HEAD_LOCK(runtime);
233 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100234 /* overflow or Py_Initialize() not called! */
235 PyErr_SetString(PyExc_RuntimeError,
236 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100237 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100238 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100239 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200240 else {
241 interp->id = interpreters->next_id;
242 interpreters->next_id += 1;
243 interp->next = interpreters->head;
244 if (interpreters->main == NULL) {
245 interpreters->main = interp;
246 }
247 interpreters->head = interp;
248 }
249 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000250
Pablo Galindo95d630e2018-08-31 22:49:29 +0100251 if (interp == NULL) {
252 return NULL;
253 }
254
Yury Selivanovf23746a2018-01-22 19:11:18 -0500255 interp->tstate_next_unique_id = 0;
256
Steve Dowerb82e17e2019-05-23 08:45:22 -0700257 interp->audit_hooks = NULL;
258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000260}
261
262
Eric Snow396e0a82019-05-31 21:16:47 -0600263void
264PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000265{
Eric Snow396e0a82019-05-31 21:16:47 -0600266 _PyRuntimeState *runtime = interp->runtime;
267
Steve Dowerb82e17e2019-05-23 08:45:22 -0700268 if (PySys_Audit("cpython.PyInterpreterState_Clear", NULL) < 0) {
269 PyErr_Clear();
270 }
271
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200272 HEAD_LOCK(runtime);
273 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200275 }
276 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700277
278 Py_CLEAR(interp->audit_hooks);
279
Victor Stinner331a6a52019-05-27 16:39:22 +0200280 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 Py_CLEAR(interp->codec_search_path);
282 Py_CLEAR(interp->codec_search_cache);
283 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700284 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 Py_CLEAR(interp->sysdict);
287 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200288 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400289 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300290 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600291 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200292#ifdef HAVE_FORK
293 Py_CLEAR(interp->before_forkers);
294 Py_CLEAR(interp->after_forkers_parent);
295 Py_CLEAR(interp->after_forkers_child);
296#endif
Eric Snow86ea5812019-05-10 13:29:55 -0400297 if (runtime->finalizing == NULL) {
298 _PyWarnings_Fini(interp);
299 }
Eric Snow5be45a62019-03-08 22:47:07 -0700300 // XXX Once we have one allocator per interpreter (i.e.
301 // per-interpreter GC) we must ensure that all of the interpreter's
302 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000303}
304
305
306static void
Eric Snow396e0a82019-05-31 21:16:47 -0600307zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000308{
Eric Snow396e0a82019-05-31 21:16:47 -0600309 PyThreadState *ts;
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). */
Eric Snow396e0a82019-05-31 21:16:47 -0600312 while ((ts = interp->tstate_head) != NULL) {
313 PyThreadState_Delete(ts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000315}
316
317
Eric Snow396e0a82019-05-31 21:16:47 -0600318void
319PyInterpreterState_Delete(PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200320{
Eric Snow396e0a82019-05-31 21:16:47 -0600321 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200322 struct pyinterpreters *interpreters = &runtime->interpreters;
Eric Snow396e0a82019-05-31 21:16:47 -0600323 zapthreads(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
Eric Snow59032962018-09-14 14:17:20 -0700352/*
353 * Delete all interpreter states except the main interpreter. If there
354 * is a current interpreter state, it *must* be the main interpreter.
355 */
356void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200357_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700358{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200359 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200360 struct pyinterpreters *interpreters = &runtime->interpreters;
361
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200362 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200363 if (tstate != NULL && tstate->interp != interpreters->main) {
Eric Snow59032962018-09-14 14:17:20 -0700364 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
365 }
366
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200367 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200368 PyInterpreterState *interp = interpreters->head;
369 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100370 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200371 if (interp == interpreters->main) {
372 interpreters->main->next = NULL;
373 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100374 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700375 continue;
376 }
377
Eric Snow396e0a82019-05-31 21:16:47 -0600378 PyInterpreterState_Clear(interp); // XXX must activate?
379 zapthreads(interp);
Eric Snow59032962018-09-14 14:17:20 -0700380 if (interp->id_mutex != NULL) {
381 PyThread_free_lock(interp->id_mutex);
382 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100383 PyInterpreterState *prev_interp = interp;
384 interp = interp->next;
385 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700386 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200387 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700388
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200389 if (interpreters->head == NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700390 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
391 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200392 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700393}
394
395
Victor Stinnercaba55b2018-08-03 15:33:52 +0200396PyInterpreterState *
397_PyInterpreterState_Get(void)
398{
Victor Stinner50b48572018-11-01 01:51:40 +0100399 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200400 if (tstate == NULL) {
401 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
402 }
403 PyInterpreterState *interp = tstate->interp;
404 if (interp == NULL) {
405 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
406 }
407 return interp;
408}
409
410
Eric Snowe3774162017-05-22 19:46:40 -0700411int64_t
412PyInterpreterState_GetID(PyInterpreterState *interp)
413{
414 if (interp == NULL) {
415 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
416 return -1;
417 }
418 return interp->id;
419}
420
421
Eric Snow5be45a62019-03-08 22:47:07 -0700422static PyInterpreterState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200423interp_look_up_id(_PyRuntimeState *runtime, PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700424{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200425 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100426 while (interp != NULL) {
427 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700428 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100429 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700430 }
431 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100432 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700433 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100434 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700435 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100436 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700437}
438
Eric Snow5be45a62019-03-08 22:47:07 -0700439PyInterpreterState *
440_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
441{
442 PyInterpreterState *interp = NULL;
443 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200444 _PyRuntimeState *runtime = &_PyRuntime;
445 HEAD_LOCK(runtime);
446 interp = interp_look_up_id(runtime, requested_id);
447 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700448 }
449 if (interp == NULL && !PyErr_Occurred()) {
450 PyErr_Format(PyExc_RuntimeError,
451 "unrecognized interpreter ID %lld", requested_id);
452 }
453 return interp;
454}
455
Eric Snow4c6955e2018-02-16 18:53:40 -0700456
457int
458_PyInterpreterState_IDInitref(PyInterpreterState *interp)
459{
460 if (interp->id_mutex != NULL) {
461 return 0;
462 }
463 interp->id_mutex = PyThread_allocate_lock();
464 if (interp->id_mutex == NULL) {
465 PyErr_SetString(PyExc_RuntimeError,
466 "failed to create init interpreter ID mutex");
467 return -1;
468 }
469 interp->id_refcount = 0;
470 return 0;
471}
472
473
474void
475_PyInterpreterState_IDIncref(PyInterpreterState *interp)
476{
477 if (interp->id_mutex == NULL) {
478 return;
479 }
480 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
481 interp->id_refcount += 1;
482 PyThread_release_lock(interp->id_mutex);
483}
484
485
486void
487_PyInterpreterState_IDDecref(PyInterpreterState *interp)
488{
489 if (interp->id_mutex == NULL) {
490 return;
491 }
Eric Snow396e0a82019-05-31 21:16:47 -0600492 _PyRuntimeState *runtime = interp->runtime;
493 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700494 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
495 assert(interp->id_refcount != 0);
496 interp->id_refcount -= 1;
497 int64_t refcount = interp->id_refcount;
498 PyThread_release_lock(interp->id_mutex);
499
Eric Snowc11183c2019-03-15 16:35:46 -0600500 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700501 // XXX Using the "head" thread isn't strictly correct.
502 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
503 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200504 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700505 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200506 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700507 }
508}
509
Eric Snowc11183c2019-03-15 16:35:46 -0600510int
511_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
512{
513 return interp->requires_idref;
514}
515
516void
517_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
518{
519 interp->requires_idref = required ? 1 : 0;
520}
521
Eric Snowc11183c2019-03-15 16:35:46 -0600522PyObject *
523_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
524{
525 if (interp->modules == NULL) {
526 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
527 return NULL;
528 }
529 return PyMapping_GetItemString(interp->modules, "__main__");
530}
531
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600532PyObject *
533PyInterpreterState_GetDict(PyInterpreterState *interp)
534{
535 if (interp->dict == NULL) {
536 interp->dict = PyDict_New();
537 if (interp->dict == NULL) {
538 PyErr_Clear();
539 }
540 }
541 /* Returning NULL means no per-interpreter dict is available. */
542 return interp->dict;
543}
544
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000545/* Default implementation for _PyThreadState_GetFrame */
546static struct _frame *
547threadstate_getframe(PyThreadState *self)
548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000550}
551
Victor Stinner45b9be52010-03-03 23:28:07 +0000552static PyThreadState *
553new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000554{
Eric Snow396e0a82019-05-31 21:16:47 -0600555 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200556 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200557 if (tstate == NULL) {
558 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000560
Victor Stinner8bb32302019-04-24 16:47:40 +0200561 if (_PyThreadState_GetFrame == NULL) {
562 _PyThreadState_GetFrame = threadstate_getframe;
563 }
564
565 tstate->interp = interp;
566
567 tstate->frame = NULL;
568 tstate->recursion_depth = 0;
569 tstate->overflowed = 0;
570 tstate->recursion_critical = 0;
571 tstate->stackcheck_counter = 0;
572 tstate->tracing = 0;
573 tstate->use_tracing = 0;
574 tstate->gilstate_counter = 0;
575 tstate->async_exc = NULL;
576 tstate->thread_id = PyThread_get_thread_ident();
577
578 tstate->dict = NULL;
579
580 tstate->curexc_type = NULL;
581 tstate->curexc_value = NULL;
582 tstate->curexc_traceback = NULL;
583
584 tstate->exc_state.exc_type = NULL;
585 tstate->exc_state.exc_value = NULL;
586 tstate->exc_state.exc_traceback = NULL;
587 tstate->exc_state.previous_item = NULL;
588 tstate->exc_info = &tstate->exc_state;
589
590 tstate->c_profilefunc = NULL;
591 tstate->c_tracefunc = NULL;
592 tstate->c_profileobj = NULL;
593 tstate->c_traceobj = NULL;
594
595 tstate->trash_delete_nesting = 0;
596 tstate->trash_delete_later = NULL;
597 tstate->on_delete = NULL;
598 tstate->on_delete_data = NULL;
599
600 tstate->coroutine_origin_tracking_depth = 0;
601
Victor Stinner8bb32302019-04-24 16:47:40 +0200602 tstate->async_gen_firstiter = NULL;
603 tstate->async_gen_finalizer = NULL;
604
605 tstate->context = NULL;
606 tstate->context_ver = 1;
607
608 tstate->id = ++interp->tstate_next_unique_id;
609
610 if (init) {
Eric Snow396e0a82019-05-31 21:16:47 -0600611 _PyThreadState_Init(tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200612 }
613
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200614 HEAD_LOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200615 tstate->prev = NULL;
616 tstate->next = interp->tstate_head;
617 if (tstate->next)
618 tstate->next->prev = tstate;
619 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200620 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000623}
624
Victor Stinner45b9be52010-03-03 23:28:07 +0000625PyThreadState *
626PyThreadState_New(PyInterpreterState *interp)
627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000629}
630
631PyThreadState *
632_PyThreadState_Prealloc(PyInterpreterState *interp)
633{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000635}
636
637void
Eric Snow396e0a82019-05-31 21:16:47 -0600638_PyThreadState_Init(PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000639{
Eric Snow396e0a82019-05-31 21:16:47 -0600640 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner8bb32302019-04-24 16:47:40 +0200641 _PyGILState_NoteThreadState(&runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000642}
643
Martin v. Löwis1a214512008-06-11 05:26:20 +0000644PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200645PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000646{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200647 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100648 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000650 if (module->m_slots) {
651 return NULL;
652 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 if (index == 0)
654 return NULL;
655 if (state->modules_by_index == NULL)
656 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200657 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 return NULL;
659 res = PyList_GET_ITEM(state->modules_by_index, index);
660 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000661}
662
663int
664_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
665{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000666 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300667 if (!def) {
668 assert(PyErr_Occurred());
669 return -1;
670 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000671 if (def->m_slots) {
672 PyErr_SetString(PyExc_SystemError,
673 "PyState_AddModule called on module with slots");
674 return -1;
675 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100676 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 if (!state->modules_by_index) {
678 state->modules_by_index = PyList_New(0);
679 if (!state->modules_by_index)
680 return -1;
681 }
682 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
683 if (PyList_Append(state->modules_by_index, Py_None) < 0)
684 return -1;
685 Py_INCREF(module);
686 return PyList_SetItem(state->modules_by_index,
687 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000688}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000689
Martin v. Löwis7800f752012-06-22 12:20:55 +0200690int
691PyState_AddModule(PyObject* module, struct PyModuleDef* def)
692{
693 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100694 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200695 if (!def) {
696 Py_FatalError("PyState_AddModule: Module Definition is NULL");
697 return -1;
698 }
699 index = def->m_base.m_index;
700 if (state->modules_by_index) {
701 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
702 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
703 Py_FatalError("PyState_AddModule: Module already added!");
704 return -1;
705 }
706 }
707 }
708 return _PyState_AddModule(module, def);
709}
710
711int
712PyState_RemoveModule(struct PyModuleDef* def)
713{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000714 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200715 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000716 if (def->m_slots) {
717 PyErr_SetString(PyExc_SystemError,
718 "PyState_RemoveModule called on module with slots");
719 return -1;
720 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100721 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200722 if (index == 0) {
723 Py_FatalError("PyState_RemoveModule: Module index invalid.");
724 return -1;
725 }
726 if (state->modules_by_index == NULL) {
727 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
728 return -1;
729 }
730 if (index > PyList_GET_SIZE(state->modules_by_index)) {
731 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
732 return -1;
733 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700734 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200735 return PyList_SetItem(state->modules_by_index, index, Py_None);
736}
737
Antoine Pitrou40322e62013-08-11 00:30:09 +0200738/* used by import.c:PyImport_Cleanup */
739void
740_PyState_ClearModules(void)
741{
Victor Stinner9204fb82018-10-30 15:13:17 +0100742 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200743 if (state->modules_by_index) {
744 Py_ssize_t i;
745 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
746 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
747 if (PyModule_Check(m)) {
748 /* cleanup the saved copy of module dicts */
749 PyModuleDef *md = PyModule_GetDef(m);
750 if (md)
751 Py_CLEAR(md->m_base.m_copy);
752 }
753 }
754 /* Setting modules_by_index to NULL could be dangerous, so we
755 clear the list instead. */
756 if (PyList_SetSlice(state->modules_by_index,
757 0, PyList_GET_SIZE(state->modules_by_index),
758 NULL))
759 PyErr_WriteUnraisable(state->modules_by_index);
760 }
761}
762
Guido van Rossuma027efa1997-05-05 20:56:21 +0000763void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000764PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000765{
Victor Stinner331a6a52019-05-27 16:39:22 +0200766 int verbose = tstate->interp->config.verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200767
768 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 fprintf(stderr,
770 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 Py_CLEAR(tstate->dict);
775 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 Py_CLEAR(tstate->curexc_type);
778 Py_CLEAR(tstate->curexc_value);
779 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000780
Mark Shannonae3087c2017-10-22 22:41:51 +0100781 Py_CLEAR(tstate->exc_state.exc_type);
782 Py_CLEAR(tstate->exc_state.exc_value);
783 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300784
Mark Shannonae3087c2017-10-22 22:41:51 +0100785 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200786 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100787 fprintf(stderr,
788 "PyThreadState_Clear: warning: thread still has a generator\n");
789 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 tstate->c_profilefunc = NULL;
792 tstate->c_tracefunc = NULL;
793 Py_CLEAR(tstate->c_profileobj);
794 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400795
Yury Selivanoveb636452016-09-08 22:01:51 -0700796 Py_CLEAR(tstate->async_gen_firstiter);
797 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500798
799 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000800}
801
802
Guido van Rossum29757862001-01-23 01:46:06 +0000803/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
804static void
Eric Snow396e0a82019-05-31 21:16:47 -0600805tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000806{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200807 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 Py_FatalError("PyThreadState_Delete: NULL tstate");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200809 }
810 PyInterpreterState *interp = tstate->interp;
811 if (interp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 Py_FatalError("PyThreadState_Delete: NULL interp");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200813 }
Eric Snow396e0a82019-05-31 21:16:47 -0600814 _PyRuntimeState *runtime = interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200815 HEAD_LOCK(runtime);
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200816 if (tstate->prev)
817 tstate->prev->next = tstate->next;
818 else
819 interp->tstate_head = tstate->next;
820 if (tstate->next)
821 tstate->next->prev = tstate->prev;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200822 HEAD_UNLOCK(runtime);
Antoine Pitrou7b476992013-09-07 23:38:37 +0200823 if (tstate->on_delete != NULL) {
824 tstate->on_delete(tstate->on_delete_data);
825 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200826 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000827}
828
829
Eric Snow396e0a82019-05-31 21:16:47 -0600830void
831PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000832{
Eric Snow396e0a82019-05-31 21:16:47 -0600833 _PyRuntimeState *runtime = tstate->interp->runtime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200834 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
835 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600837 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200838 if (gilstate->autoInterpreterState &&
839 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
840 {
841 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
842 }
Eric Snow396e0a82019-05-31 21:16:47 -0600843 tstate_delete_common(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200844}
845
846
847static void
848_PyThreadState_DeleteCurrent(_PyRuntimeState *runtime)
849{
850 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
851 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 if (tstate == NULL)
853 Py_FatalError(
854 "PyThreadState_DeleteCurrent: no current tstate");
Eric Snow396e0a82019-05-31 21:16:47 -0600855 tstate_delete_common(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200856 if (gilstate->autoInterpreterState &&
857 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600858 {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200859 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600860 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200861 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000863}
Guido van Rossum29757862001-01-23 01:46:06 +0000864
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200865void
866PyThreadState_DeleteCurrent()
867{
868 _PyThreadState_DeleteCurrent(&_PyRuntime);
869}
870
Guido van Rossum29757862001-01-23 01:46:06 +0000871
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200872/*
873 * Delete all thread states except the one passed as argument.
874 * Note that, if there is a current thread state, it *must* be the one
875 * passed as argument. Also, this won't touch any other interpreters
876 * than the current one, since we don't know which thread state should
877 * be kept in those other interpreteres.
878 */
879void
Eric Snow396e0a82019-05-31 21:16:47 -0600880_PyThreadState_DeleteExcept(PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200881{
882 PyInterpreterState *interp = tstate->interp;
Eric Snow396e0a82019-05-31 21:16:47 -0600883 _PyRuntimeState *runtime = interp->runtime;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200884 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 Stinner09532fe2019-05-10 23:39:09 +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{
Eric Snow396e0a82019-05-31 21:16:47 -06001122 _PyRuntimeState *runtime = tstate->interp->runtime;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 /* Must be the tstate for this thread */
Eric Snow396e0a82019-05-31 21:16:47 -06001124 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001125 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1126 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001127}
1128
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001129/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001130 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001131*/
Tim Peters19717fa2004-10-09 17:38:29 +00001132void
Eric Snow396e0a82019-05-31 21:16:47 -06001133_PyGILState_Init(PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001134{
Victor Stinner8bb32302019-04-24 16:47:40 +02001135 /* must init with valid states */
Victor Stinner8bb32302019-04-24 16:47:40 +02001136 assert(tstate != NULL);
Eric Snow396e0a82019-05-31 21:16:47 -06001137 PyInterpreterState *interp = tstate->interp;
1138 assert(interp != NULL);
1139 _PyRuntimeState *runtime = interp->runtime;
1140 assert(runtime != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001141
Victor Stinner8bb32302019-04-24 16:47:40 +02001142 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1143
1144 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001145 Py_FatalError("Could not allocate TSS entry");
1146 }
Victor Stinner8bb32302019-04-24 16:47:40 +02001147 gilstate->autoInterpreterState = interp;
1148 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1149 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001150
Victor Stinner8bb32302019-04-24 16:47:40 +02001151 _PyGILState_NoteThreadState(gilstate, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001152}
1153
Victor Stinner861d9ab2016-03-16 22:45:24 +01001154PyInterpreterState *
1155_PyGILState_GetInterpreterStateUnsafe(void)
1156{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001157 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001158}
1159
Tim Peters19717fa2004-10-09 17:38:29 +00001160void
Victor Stinner8e91c242019-04-24 17:24:01 +02001161_PyGILState_Fini(_PyRuntimeState *runtime)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001162{
Victor Stinner8e91c242019-04-24 17:24:01 +02001163 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1164 PyThread_tss_delete(&gilstate->autoTSSkey);
1165 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001166}
1167
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001168/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001169 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001170 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001171 */
1172void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001173_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001174{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001175 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001176 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001177
1178 PyThread_tss_delete(&gilstate->autoTSSkey);
1179 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001180 Py_FatalError("Could not allocate TSS entry");
1181 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001182
Charles-François Natalia233df82011-11-22 19:49:51 +01001183 /* If the thread had an associated auto thread state, reassociate it with
1184 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001185 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001186 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001187 {
1188 Py_FatalError("Couldn't create autoTSSkey mapping");
1189 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001190}
1191
Michael W. Hudson188d4362005-06-20 16:52:57 +00001192/* When a thread state is created for a thread by some mechanism other than
1193 PyGILState_Ensure, it's important that the GILState machinery knows about
1194 it so it doesn't try to create another thread state for the thread (this is
1195 a better fix for SF bug #1010677 than the first one attempted).
1196*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001197static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001198_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001199{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001200 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001201 threadstate created in Py_Initialize(). Don't do anything for now
1202 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001203 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001205 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001206
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001207 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 The only situation where you can legitimately have more than one
1210 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001211 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001212
Victor Stinner590cebe2013-12-13 11:08:56 +01001213 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1214 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001215
Victor Stinner590cebe2013-12-13 11:08:56 +01001216 The first thread state created for that given OS level thread will
1217 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001219 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1220 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001221 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001222 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001223 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 /* PyGILState_Release must not try to delete this thread state. */
1226 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001227}
1228
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001229/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001230static PyThreadState *
1231_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1232{
1233 if (gilstate->autoInterpreterState == NULL)
1234 return NULL;
1235 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1236}
1237
Tim Peters19717fa2004-10-09 17:38:29 +00001238PyThreadState *
1239PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001240{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001241 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001242}
1243
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001244int
1245PyGILState_Check(void)
1246{
Victor Stinner8a1be612016-03-14 22:07:55 +01001247
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001248 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001249 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001250 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001251
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001252 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1253 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1254 return 1;
1255 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001256
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001257 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1258 if (tstate == NULL) {
1259 return 0;
1260 }
1261
1262 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001263}
1264
Tim Peters19717fa2004-10-09 17:38:29 +00001265PyGILState_STATE
1266PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001267{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001268 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 int current;
1270 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001271 int need_init_threads = 0;
1272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 /* Note that we do not auto-init Python here - apart from
1274 potential races with 2 threads auto-initializing, pep-311
1275 spells out other issues. Embedders are expected to have
1276 called Py_Initialize() and usually PyEval_InitThreads().
1277 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001278 /* Py_Initialize() hasn't been called! */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001279 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001280
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001281 tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001283 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 /* Create a new thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001286 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 if (tcur == NULL)
1288 Py_FatalError("Couldn't create thread-state for new thread");
1289 /* This is our thread state! We'll need to delete it in the
1290 matching call to PyGILState_Release(). */
1291 tcur->gilstate_counter = 0;
1292 current = 0; /* new thread state is never current */
1293 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001294 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001296 }
1297
1298 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001300 }
1301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 /* Update our counter in the thread-state - no need for locks:
1303 - tcur will remain valid as we hold the GIL.
1304 - the counter is safe as we are the only thread "allowed"
1305 to modify this value
1306 */
1307 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001308
1309 if (need_init_threads) {
1310 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1311 called from a new thread for the first time, we need the create the
1312 GIL. */
1313 PyEval_InitThreads();
1314 }
1315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001317}
1318
Tim Peters19717fa2004-10-09 17:38:29 +00001319void
1320PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001321{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001322 _PyRuntimeState *runtime = &_PyRuntime;
1323 PyThreadState *tcur = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1324 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 Py_FatalError("auto-releasing thread-state, "
1326 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001327 }
1328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 /* We must hold the GIL and have our thread state current */
1330 /* XXX - remove the check - the assert should be fine,
1331 but while this is very new (April 2003), the extra check
1332 by release-only users can't hurt.
1333 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001334 if (!PyThreadState_IsCurrent(tcur)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 Py_FatalError("This thread state must be current when releasing");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001336 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 assert(PyThreadState_IsCurrent(tcur));
1338 --tcur->gilstate_counter;
1339 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 /* If we're going to destroy this thread-state, we must
1342 * clear it while the GIL is held, as destructors may run.
1343 */
1344 if (tcur->gilstate_counter == 0) {
1345 /* can't have been locked when we created it */
1346 assert(oldstate == PyGILState_UNLOCKED);
1347 PyThreadState_Clear(tcur);
1348 /* Delete the thread-state. Note this releases the GIL too!
1349 * It's vital that the GIL be held here, to avoid shutdown
1350 * races; see bugs 225673 and 1061968 (that nasty bug has a
1351 * habit of coming back).
1352 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001353 _PyThreadState_DeleteCurrent(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 }
1355 /* Release the lock if necessary */
1356 else if (oldstate == PyGILState_UNLOCKED)
1357 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001358}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001359
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001360
Eric Snow7f8bfc92018-01-29 18:23:44 -07001361/**************************/
1362/* cross-interpreter data */
1363/**************************/
1364
1365/* cross-interpreter data */
1366
1367crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1368
1369/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1370 to keep the registry code separate. */
1371static crossinterpdatafunc
1372_lookup_getdata(PyObject *obj)
1373{
1374 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1375 if (getdata == NULL && PyErr_Occurred() == 0)
1376 PyErr_Format(PyExc_ValueError,
1377 "%S does not support cross-interpreter data", obj);
1378 return getdata;
1379}
1380
1381int
1382_PyObject_CheckCrossInterpreterData(PyObject *obj)
1383{
1384 crossinterpdatafunc getdata = _lookup_getdata(obj);
1385 if (getdata == NULL) {
1386 return -1;
1387 }
1388 return 0;
1389}
1390
1391static int
1392_check_xidata(_PyCrossInterpreterData *data)
1393{
1394 // data->data can be anything, including NULL, so we don't check it.
1395
1396 // data->obj may be NULL, so we don't check it.
1397
1398 if (data->interp < 0) {
1399 PyErr_SetString(PyExc_SystemError, "missing interp");
1400 return -1;
1401 }
1402
1403 if (data->new_object == NULL) {
1404 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1405 return -1;
1406 }
1407
1408 // data->free may be NULL, so we don't check it.
1409
1410 return 0;
1411}
1412
1413int
1414_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1415{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001416 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001417 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001418 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001419
1420 // Reset data before re-populating.
1421 *data = (_PyCrossInterpreterData){0};
1422 data->free = PyMem_RawFree; // Set a default that may be overridden.
1423
1424 // Call the "getdata" func for the object.
1425 Py_INCREF(obj);
1426 crossinterpdatafunc getdata = _lookup_getdata(obj);
1427 if (getdata == NULL) {
1428 Py_DECREF(obj);
1429 return -1;
1430 }
1431 int res = getdata(obj, data);
1432 Py_DECREF(obj);
1433 if (res != 0) {
1434 return -1;
1435 }
1436
1437 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001438 data->interp = interp->id;
1439 if (_check_xidata(data) != 0) {
1440 _PyCrossInterpreterData_Release(data);
1441 return -1;
1442 }
1443
1444 return 0;
1445}
1446
Eric Snowb75b1a352019-04-12 10:20:10 -06001447static void
Eric Snow63799132018-06-01 18:45:20 -06001448_release_xidata(void *arg)
1449{
1450 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1451 if (data->free != NULL) {
1452 data->free(data->data);
1453 }
1454 Py_XDECREF(data->obj);
Eric Snowb75b1a352019-04-12 10:20:10 -06001455}
1456
1457static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001458_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1459 PyInterpreterState *interp,
Eric Snowb75b1a352019-04-12 10:20:10 -06001460 void (*func)(void *), void *arg)
1461{
1462 /* We would use Py_AddPendingCall() if it weren't specific to the
1463 * main interpreter (see bpo-33608). In the meantime we take a
1464 * naive approach.
1465 */
1466 PyThreadState *save_tstate = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001467 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
Eric Snowb75b1a352019-04-12 10:20:10 -06001468 // XXX Using the "head" thread isn't strictly correct.
1469 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1470 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001471 save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snowb75b1a352019-04-12 10:20:10 -06001472 }
1473
1474 func(arg);
1475
1476 // Switch back.
1477 if (save_tstate != NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001478 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snowb75b1a352019-04-12 10:20:10 -06001479 }
Eric Snow63799132018-06-01 18:45:20 -06001480}
1481
Eric Snow7f8bfc92018-01-29 18:23:44 -07001482void
1483_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1484{
1485 if (data->data == NULL && data->obj == NULL) {
1486 // Nothing to release!
1487 return;
1488 }
1489
Eric Snowb75b1a352019-04-12 10:20:10 -06001490 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001491 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1492 if (interp == NULL) {
1493 // The intepreter was already destroyed.
1494 if (data->free != NULL) {
1495 // XXX Someone leaked some memory...
1496 }
1497 return;
1498 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001499
Eric Snow7f8bfc92018-01-29 18:23:44 -07001500 // "Release" the data and/or the object.
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001501 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1502 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001503}
1504
1505PyObject *
1506_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1507{
1508 return data->new_object(data);
1509}
1510
1511/* registry of {type -> crossinterpdatafunc} */
1512
1513/* For now we use a global registry of shareable classes. An
1514 alternative would be to add a tp_* slot for a class's
1515 crossinterpdatafunc. It would be simpler and more efficient. */
1516
1517static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001518_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1519 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001520{
1521 // Note that we effectively replace already registered classes
1522 // rather than failing.
1523 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1524 if (newhead == NULL)
1525 return -1;
1526 newhead->cls = cls;
1527 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001528 newhead->next = xidregistry->head;
1529 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001530 return 0;
1531}
1532
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001533static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001534
1535int
Eric Snowc11183c2019-03-15 16:35:46 -06001536_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001537 crossinterpdatafunc getdata)
1538{
1539 if (!PyType_Check(cls)) {
1540 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1541 return -1;
1542 }
1543 if (getdata == NULL) {
1544 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1545 return -1;
1546 }
1547
1548 // Make sure the class isn't ever deallocated.
1549 Py_INCREF((PyObject *)cls);
1550
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001551 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1552 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1553 if (xidregistry->head == NULL) {
1554 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001555 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001556 int res = _register_xidata(xidregistry, cls, getdata);
1557 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001558 return res;
1559}
1560
Eric Snow6d2cd902018-05-16 15:04:57 -04001561/* Cross-interpreter objects are looked up by exact match on the class.
1562 We can reassess this policy when we move from a global registry to a
1563 tp_* slot. */
1564
Eric Snow7f8bfc92018-01-29 18:23:44 -07001565crossinterpdatafunc
1566_PyCrossInterpreterData_Lookup(PyObject *obj)
1567{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001568 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001569 PyObject *cls = PyObject_Type(obj);
1570 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001571 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1572 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001573 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001574 _register_builtins_for_crossinterpreter_data(xidregistry);
1575 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001576 }
1577 for(; cur != NULL; cur = cur->next) {
1578 if (cur->cls == (PyTypeObject *)cls) {
1579 getdata = cur->getdata;
1580 break;
1581 }
1582 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001583 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001584 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001585 return getdata;
1586}
1587
1588/* cross-interpreter data for builtin types */
1589
Eric Snow6d2cd902018-05-16 15:04:57 -04001590struct _shared_bytes_data {
1591 char *bytes;
1592 Py_ssize_t len;
1593};
1594
Eric Snow7f8bfc92018-01-29 18:23:44 -07001595static PyObject *
1596_new_bytes_object(_PyCrossInterpreterData *data)
1597{
Eric Snow6d2cd902018-05-16 15:04:57 -04001598 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1599 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001600}
1601
1602static int
1603_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1604{
Eric Snow6d2cd902018-05-16 15:04:57 -04001605 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1606 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1607 return -1;
1608 }
1609 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001610 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001611 data->obj = obj; // Will be "released" (decref'ed) when data released.
1612 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001613 data->free = PyMem_Free;
1614 return 0;
1615}
1616
1617struct _shared_str_data {
1618 int kind;
1619 const void *buffer;
1620 Py_ssize_t len;
1621};
1622
1623static PyObject *
1624_new_str_object(_PyCrossInterpreterData *data)
1625{
1626 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1627 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1628}
1629
1630static int
1631_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1632{
1633 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1634 shared->kind = PyUnicode_KIND(obj);
1635 shared->buffer = PyUnicode_DATA(obj);
1636 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1637 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001638 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001639 data->obj = obj; // Will be "released" (decref'ed) when data released.
1640 data->new_object = _new_str_object;
1641 data->free = PyMem_Free;
1642 return 0;
1643}
1644
1645static PyObject *
1646_new_long_object(_PyCrossInterpreterData *data)
1647{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001648 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001649}
1650
1651static int
1652_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1653{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001654 /* Note that this means the size of shareable ints is bounded by
1655 * sys.maxsize. Hence on 32-bit architectures that is half the
1656 * size of maximum shareable ints on 64-bit.
1657 */
1658 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001659 if (value == -1 && PyErr_Occurred()) {
1660 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1661 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1662 }
1663 return -1;
1664 }
1665 data->data = (void *)value;
1666 data->obj = NULL;
1667 data->new_object = _new_long_object;
1668 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001669 return 0;
1670}
1671
1672static PyObject *
1673_new_none_object(_PyCrossInterpreterData *data)
1674{
1675 // XXX Singleton refcounts are problematic across interpreters...
1676 Py_INCREF(Py_None);
1677 return Py_None;
1678}
1679
1680static int
1681_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1682{
1683 data->data = NULL;
1684 // data->obj remains NULL
1685 data->new_object = _new_none_object;
1686 data->free = NULL; // There is nothing to free.
1687 return 0;
1688}
1689
1690static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001691_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001692{
1693 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001694 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001695 Py_FatalError("could not register None for cross-interpreter sharing");
1696 }
1697
Eric Snow6d2cd902018-05-16 15:04:57 -04001698 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001699 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001700 Py_FatalError("could not register int for cross-interpreter sharing");
1701 }
1702
Eric Snow7f8bfc92018-01-29 18:23:44 -07001703 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001704 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001705 Py_FatalError("could not register bytes for cross-interpreter sharing");
1706 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001707
1708 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001709 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001710 Py_FatalError("could not register str for cross-interpreter sharing");
1711 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001712}
1713
1714
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001715#ifdef __cplusplus
1716}
1717#endif