blob: 098280d76dfc0100f05c0c1ecb1b8427375d7a9e [file] [log] [blame]
Guido van Rossuma027efa1997-05-05 20:56:21 +00001
2/* Thread and interpreter state structures and their interfaces */
3
4#include "Python.h"
Victor Stinner09532fe2019-05-10 23:39:09 +02005#include "pycore_ceval.h"
Victor Stinner331a6a52019-05-27 16:39:22 +02006#include "pycore_initconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01007#include "pycore_pymem.h"
8#include "pycore_pystate.h"
Eric Snow86ea5812019-05-10 13:29:55 -04009#include "pycore_pylifecycle.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +000010
Tim Peters84705582004-10-10 02:47:33 +000011/* --------------------------------------------------------------------------
12CAUTION
13
Victor Stinner1a7425f2013-07-07 16:25:15 +020014Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
15number of these functions are advertised as safe to call when the GIL isn't
16held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
17debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
18to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000019-------------------------------------------------------------------------- */
20
Martin v. Löwisf0473d52001-07-18 16:17:16 +000021#ifdef HAVE_DLOPEN
22#ifdef HAVE_DLFCN_H
23#include <dlfcn.h>
24#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030025#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000026#define RTLD_LAZY 1
27#endif
28#endif
29
Benjamin Peterson43162b82012-04-13 11:58:27 -040030#ifdef __cplusplus
31extern "C" {
32#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000033
Victor Stinner10c8e6a2019-04-26 01:53:18 +020034#define _PyRuntimeGILState_GetThreadState(gilstate) \
35 ((PyThreadState*)_Py_atomic_load_relaxed(&(gilstate)->tstate_current))
36#define _PyRuntimeGILState_SetThreadState(gilstate, value) \
37 _Py_atomic_store_relaxed(&(gilstate)->tstate_current, \
38 (uintptr_t)(value))
39
40/* Forward declarations */
41static PyThreadState *_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate);
Victor Stinner0fd2c302019-06-04 03:15:09 +020042static void _PyThreadState_Delete(_PyRuntimeState *runtime, PyThreadState *tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +020043
44
Victor Stinner331a6a52019-05-27 16:39:22 +020045static PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010046_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060047{
Steve Dowerb82e17e2019-05-23 08:45:22 -070048 /* We preserve the hook across init, because there is
49 currently no public API to set it between runtime
50 initialization and interpreter initialization. */
51 void *open_code_hook = runtime->open_code_hook;
52 void *open_code_userdata = runtime->open_code_userdata;
53 _Py_AuditHookEntry *audit_hook_head = runtime->audit_hook_head;
54
Eric Snow2ebc5ce2017-09-07 23:51:28 -060055 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010056
Steve Dowerb82e17e2019-05-23 08:45:22 -070057 runtime->open_code_hook = open_code_hook;
58 runtime->open_code_userdata = open_code_userdata;
59 runtime->audit_hook_head = audit_hook_head;
60
Eric Snow2ebc5ce2017-09-07 23:51:28 -060061 _PyGC_Initialize(&runtime->gc);
62 _PyEval_Initialize(&runtime->ceval);
Victor Stinner6e128382019-09-28 04:50:43 +020063
Victor Stinnerbdace212019-10-01 00:46:42 +020064 PyPreConfig_InitPythonConfig(&runtime->preconfig);
Michael W. Hudson188d4362005-06-20 16:52:57 +000065
Eric Snow2ebc5ce2017-09-07 23:51:28 -060066 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080067
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090068 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
69 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080070 Py_tss_t initial = Py_tss_NEEDS_INIT;
71 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000072
Eric Snow2ebc5ce2017-09-07 23:51:28 -060073 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080074 if (runtime->interpreters.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020075 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080076 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060077 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070078
79 runtime->xidregistry.mutex = PyThread_allocate_lock();
80 if (runtime->xidregistry.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020081 return _PyStatus_ERR("Can't initialize threads for cross-interpreter data registry");
Eric Snow7f8bfc92018-01-29 18:23:44 -070082 }
83
Eric Snow8479a342019-03-08 23:44:33 -070084 // Set it to the ID of the main thread of the main interpreter.
85 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070086
Victor Stinner331a6a52019-05-27 16:39:22 +020087 return _PyStatus_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060088}
Eric Snow05351c12017-09-05 21:43:08 -070089
Victor Stinner331a6a52019-05-27 16:39:22 +020090PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010091_PyRuntimeState_Init(_PyRuntimeState *runtime)
92{
93 /* Force default allocator, since _PyRuntimeState_Fini() must
94 use the same allocator than this function. */
95 PyMemAllocatorEx old_alloc;
96 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
97
Victor Stinner331a6a52019-05-27 16:39:22 +020098 PyStatus status = _PyRuntimeState_Init_impl(runtime);
Victor Stinner5d39e042017-11-29 17:20:38 +010099
100 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinner331a6a52019-05-27 16:39:22 +0200101 return status;
Victor Stinner5d39e042017-11-29 17:20:38 +0100102}
103
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600104void
105_PyRuntimeState_Fini(_PyRuntimeState *runtime)
106{
Victor Stinner5d39e042017-11-29 17:20:38 +0100107 /* Force the allocator used by _PyRuntimeState_Init(). */
108 PyMemAllocatorEx old_alloc;
109 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -0800110
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600111 if (runtime->interpreters.mutex != NULL) {
112 PyThread_free_lock(runtime->interpreters.mutex);
113 runtime->interpreters.mutex = NULL;
114 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800115
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100116 if (runtime->xidregistry.mutex != NULL) {
117 PyThread_free_lock(runtime->xidregistry.mutex);
118 runtime->xidregistry.mutex = NULL;
119 }
120
Victor Stinnerccb04422017-11-16 03:20:31 -0800121 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600122}
123
Eric Snow8479a342019-03-08 23:44:33 -0700124/* This function is called from PyOS_AfterFork_Child to ensure that
125 * newly created child processes do not share locks with the parent.
126 */
127
128void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200129_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700130{
131 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200132 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700133
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200134 /* Force default allocator, since _PyRuntimeState_Fini() must
135 use the same allocator than this function. */
136 PyMemAllocatorEx old_alloc;
137 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
138
139 runtime->interpreters.mutex = PyThread_allocate_lock();
140 runtime->interpreters.main->id_mutex = PyThread_allocate_lock();
141 runtime->xidregistry.mutex = PyThread_allocate_lock();
142
143 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
144
145 if (runtime->interpreters.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700146 Py_FatalError("Can't initialize lock for runtime interpreters");
147 }
148
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200149 if (runtime->interpreters.main->id_mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700150 Py_FatalError("Can't initialize ID lock for main interpreter");
151 }
152
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200153 if (runtime->xidregistry.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700154 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
155 }
156}
157
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200158#define HEAD_LOCK(runtime) \
159 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
160#define HEAD_UNLOCK(runtime) \
161 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700162
Victor Stinner8bb32302019-04-24 16:47:40 +0200163/* Forward declaration */
164static void _PyGILState_NoteThreadState(
165 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000166
Victor Stinner331a6a52019-05-27 16:39:22 +0200167PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600168_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700169{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200170 struct pyinterpreters *interpreters = &runtime->interpreters;
171 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100172
173 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
174 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200175 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100176 /* Force default allocator, since _PyRuntimeState_Fini() must
177 use the same allocator than this function. */
178 PyMemAllocatorEx old_alloc;
179 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
180
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200181 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100182
183 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
184
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200185 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200186 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800187 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600188 }
Victor Stinner5d926472018-03-06 14:31:37 +0100189
Victor Stinner331a6a52019-05-27 16:39:22 +0200190 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700191}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000192
193PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000194PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000195{
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 Snow4c6955e2018-02-16 18:53:40 -0700206 interp->id_refcount = -1;
Victor Stinnerd4341102017-11-23 00:12:09 +0100207 interp->check_interval = 100;
Victor Stinner022be022019-05-22 23:58:50 +0200208
Victor Stinner331a6a52019-05-27 16:39:22 +0200209 PyStatus status = PyConfig_InitPythonConfig(&interp->config);
210 if (_PyStatus_EXCEPTION(status)) {
211 /* Don't report status to caller: PyConfig_InitPythonConfig()
212 can only fail with a memory allocation error. */
213 PyConfig_Clear(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200214 PyMem_RawFree(interp);
215 return NULL;
216 }
217
Victor Stinnerd4341102017-11-23 00:12:09 +0100218 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000219#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300220#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100221 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000222#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100223 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000224#endif
225#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000226
Victor Stinner0fd2c302019-06-04 03:15:09 +0200227 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200228 struct pyinterpreters *interpreters = &runtime->interpreters;
229
230 HEAD_LOCK(runtime);
231 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100232 /* overflow or Py_Initialize() not called! */
233 PyErr_SetString(PyExc_RuntimeError,
234 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100235 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100236 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100237 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200238 else {
239 interp->id = interpreters->next_id;
240 interpreters->next_id += 1;
241 interp->next = interpreters->head;
242 if (interpreters->main == NULL) {
243 interpreters->main = interp;
244 }
245 interpreters->head = interp;
246 }
247 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000248
Pablo Galindo95d630e2018-08-31 22:49:29 +0100249 if (interp == NULL) {
250 return NULL;
251 }
252
Yury Selivanovf23746a2018-01-22 19:11:18 -0500253 interp->tstate_next_unique_id = 0;
254
Steve Dowerb82e17e2019-05-23 08:45:22 -0700255 interp->audit_hooks = NULL;
256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000258}
259
260
Victor Stinner0fd2c302019-06-04 03:15:09 +0200261static void
262_PyInterpreterState_Clear(_PyRuntimeState *runtime, PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000263{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700264 if (PySys_Audit("cpython.PyInterpreterState_Clear", NULL) < 0) {
265 PyErr_Clear();
266 }
267
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200268 HEAD_LOCK(runtime);
269 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200271 }
272 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700273
274 Py_CLEAR(interp->audit_hooks);
275
Victor Stinner331a6a52019-05-27 16:39:22 +0200276 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 Py_CLEAR(interp->codec_search_path);
278 Py_CLEAR(interp->codec_search_cache);
279 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700280 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 Py_CLEAR(interp->sysdict);
283 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200284 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400285 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300286 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600287 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200288#ifdef HAVE_FORK
289 Py_CLEAR(interp->before_forkers);
290 Py_CLEAR(interp->after_forkers_parent);
291 Py_CLEAR(interp->after_forkers_child);
292#endif
Eric Snow86ea5812019-05-10 13:29:55 -0400293 if (runtime->finalizing == NULL) {
294 _PyWarnings_Fini(interp);
295 }
Eric Snow5be45a62019-03-08 22:47:07 -0700296 // XXX Once we have one allocator per interpreter (i.e.
297 // per-interpreter GC) we must ensure that all of the interpreter's
298 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000299}
300
Victor Stinner0fd2c302019-06-04 03:15:09 +0200301void
302PyInterpreterState_Clear(PyInterpreterState *interp)
303{
304 _PyInterpreterState_Clear(&_PyRuntime, interp);
305}
306
Guido van Rossum25ce5661997-08-02 03:10:38 +0000307
308static void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200309zapthreads(_PyRuntimeState *runtime, PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000310{
Victor Stinner0fd2c302019-06-04 03:15:09 +0200311 PyThreadState *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 /* No need to lock the mutex here because this should only happen
313 when the threads are all really dead (XXX famous last words). */
Victor Stinner0fd2c302019-06-04 03:15:09 +0200314 while ((p = interp->tstate_head) != NULL) {
315 _PyThreadState_Delete(runtime, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000317}
318
319
Victor Stinner0fd2c302019-06-04 03:15:09 +0200320static void
321_PyInterpreterState_Delete(_PyRuntimeState *runtime,
322 PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200323{
324 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner0fd2c302019-06-04 03:15:09 +0200325 zapthreads(runtime, interp);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200326 HEAD_LOCK(runtime);
327 PyInterpreterState **p;
328 for (p = &interpreters->head; ; p = &(*p)->next) {
329 if (*p == NULL) {
330 Py_FatalError("PyInterpreterState_Delete: invalid interp");
331 }
332 if (*p == interp) {
333 break;
334 }
335 }
336 if (interp->tstate_head != NULL) {
337 Py_FatalError("PyInterpreterState_Delete: remaining threads");
338 }
339 *p = interp->next;
340 if (interpreters->main == interp) {
341 interpreters->main = NULL;
342 if (interpreters->head != NULL) {
343 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
344 }
345 }
346 HEAD_UNLOCK(runtime);
347 if (interp->id_mutex != NULL) {
348 PyThread_free_lock(interp->id_mutex);
349 }
350 PyMem_RawFree(interp);
351}
352
353
Victor Stinner0fd2c302019-06-04 03:15:09 +0200354void
355PyInterpreterState_Delete(PyInterpreterState *interp)
356{
357 _PyInterpreterState_Delete(&_PyRuntime, interp);
358}
359
360
Eric Snow59032962018-09-14 14:17:20 -0700361/*
362 * Delete all interpreter states except the main interpreter. If there
363 * is a current interpreter state, it *must* be the main interpreter.
364 */
365void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200366_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700367{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200368 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200369 struct pyinterpreters *interpreters = &runtime->interpreters;
370
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200371 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200372 if (tstate != NULL && tstate->interp != interpreters->main) {
Eric Snow59032962018-09-14 14:17:20 -0700373 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
374 }
375
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200376 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200377 PyInterpreterState *interp = interpreters->head;
378 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100379 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200380 if (interp == interpreters->main) {
381 interpreters->main->next = NULL;
382 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100383 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700384 continue;
385 }
386
Victor Stinner0fd2c302019-06-04 03:15:09 +0200387 _PyInterpreterState_Clear(runtime, interp); // XXX must activate?
388 zapthreads(runtime, interp);
Eric Snow59032962018-09-14 14:17:20 -0700389 if (interp->id_mutex != NULL) {
390 PyThread_free_lock(interp->id_mutex);
391 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100392 PyInterpreterState *prev_interp = interp;
393 interp = interp->next;
394 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700395 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200396 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700397
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200398 if (interpreters->head == NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700399 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
400 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200401 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700402}
403
404
Victor Stinnercaba55b2018-08-03 15:33:52 +0200405PyInterpreterState *
406_PyInterpreterState_Get(void)
407{
Victor Stinner50b48572018-11-01 01:51:40 +0100408 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200409 if (tstate == NULL) {
410 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
411 }
412 PyInterpreterState *interp = tstate->interp;
413 if (interp == NULL) {
414 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
415 }
416 return interp;
417}
418
419
Eric Snowe3774162017-05-22 19:46:40 -0700420int64_t
421PyInterpreterState_GetID(PyInterpreterState *interp)
422{
423 if (interp == NULL) {
424 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
425 return -1;
426 }
427 return interp->id;
428}
429
430
Eric Snow5be45a62019-03-08 22:47:07 -0700431static PyInterpreterState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200432interp_look_up_id(_PyRuntimeState *runtime, PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700433{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200434 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100435 while (interp != NULL) {
436 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700437 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100438 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700439 }
440 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100441 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700442 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100443 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700444 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100445 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700446}
447
Eric Snow5be45a62019-03-08 22:47:07 -0700448PyInterpreterState *
449_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
450{
451 PyInterpreterState *interp = NULL;
452 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200453 _PyRuntimeState *runtime = &_PyRuntime;
454 HEAD_LOCK(runtime);
455 interp = interp_look_up_id(runtime, requested_id);
456 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700457 }
458 if (interp == NULL && !PyErr_Occurred()) {
459 PyErr_Format(PyExc_RuntimeError,
460 "unrecognized interpreter ID %lld", requested_id);
461 }
462 return interp;
463}
464
Eric Snow4c6955e2018-02-16 18:53:40 -0700465
466int
467_PyInterpreterState_IDInitref(PyInterpreterState *interp)
468{
469 if (interp->id_mutex != NULL) {
470 return 0;
471 }
472 interp->id_mutex = PyThread_allocate_lock();
473 if (interp->id_mutex == NULL) {
474 PyErr_SetString(PyExc_RuntimeError,
475 "failed to create init interpreter ID mutex");
476 return -1;
477 }
478 interp->id_refcount = 0;
479 return 0;
480}
481
482
483void
484_PyInterpreterState_IDIncref(PyInterpreterState *interp)
485{
486 if (interp->id_mutex == NULL) {
487 return;
488 }
489 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
490 interp->id_refcount += 1;
491 PyThread_release_lock(interp->id_mutex);
492}
493
494
495void
496_PyInterpreterState_IDDecref(PyInterpreterState *interp)
497{
498 if (interp->id_mutex == NULL) {
499 return;
500 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200501 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700502 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
503 assert(interp->id_refcount != 0);
504 interp->id_refcount -= 1;
505 int64_t refcount = interp->id_refcount;
506 PyThread_release_lock(interp->id_mutex);
507
Eric Snowc11183c2019-03-15 16:35:46 -0600508 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700509 // XXX Using the "head" thread isn't strictly correct.
510 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
511 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200512 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700513 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200514 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700515 }
516}
517
Eric Snowc11183c2019-03-15 16:35:46 -0600518int
519_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
520{
521 return interp->requires_idref;
522}
523
524void
525_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
526{
527 interp->requires_idref = required ? 1 : 0;
528}
529
Eric Snowc11183c2019-03-15 16:35:46 -0600530PyObject *
531_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
532{
533 if (interp->modules == NULL) {
534 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
535 return NULL;
536 }
537 return PyMapping_GetItemString(interp->modules, "__main__");
538}
539
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600540PyObject *
541PyInterpreterState_GetDict(PyInterpreterState *interp)
542{
543 if (interp->dict == NULL) {
544 interp->dict = PyDict_New();
545 if (interp->dict == NULL) {
546 PyErr_Clear();
547 }
548 }
549 /* Returning NULL means no per-interpreter dict is available. */
550 return interp->dict;
551}
552
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000553/* Default implementation for _PyThreadState_GetFrame */
554static struct _frame *
555threadstate_getframe(PyThreadState *self)
556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000558}
559
Victor Stinner45b9be52010-03-03 23:28:07 +0000560static PyThreadState *
561new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000562{
Victor Stinner0fd2c302019-06-04 03:15:09 +0200563 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200564 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200565 if (tstate == NULL) {
566 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000568
Victor Stinner8bb32302019-04-24 16:47:40 +0200569 if (_PyThreadState_GetFrame == NULL) {
570 _PyThreadState_GetFrame = threadstate_getframe;
571 }
572
573 tstate->interp = interp;
574
575 tstate->frame = NULL;
576 tstate->recursion_depth = 0;
577 tstate->overflowed = 0;
578 tstate->recursion_critical = 0;
579 tstate->stackcheck_counter = 0;
580 tstate->tracing = 0;
581 tstate->use_tracing = 0;
582 tstate->gilstate_counter = 0;
583 tstate->async_exc = NULL;
584 tstate->thread_id = PyThread_get_thread_ident();
585
586 tstate->dict = NULL;
587
588 tstate->curexc_type = NULL;
589 tstate->curexc_value = NULL;
590 tstate->curexc_traceback = NULL;
591
592 tstate->exc_state.exc_type = NULL;
593 tstate->exc_state.exc_value = NULL;
594 tstate->exc_state.exc_traceback = NULL;
595 tstate->exc_state.previous_item = NULL;
596 tstate->exc_info = &tstate->exc_state;
597
598 tstate->c_profilefunc = NULL;
599 tstate->c_tracefunc = NULL;
600 tstate->c_profileobj = NULL;
601 tstate->c_traceobj = NULL;
602
603 tstate->trash_delete_nesting = 0;
604 tstate->trash_delete_later = NULL;
605 tstate->on_delete = NULL;
606 tstate->on_delete_data = NULL;
607
608 tstate->coroutine_origin_tracking_depth = 0;
609
Victor Stinner8bb32302019-04-24 16:47:40 +0200610 tstate->async_gen_firstiter = NULL;
611 tstate->async_gen_finalizer = NULL;
612
613 tstate->context = NULL;
614 tstate->context_ver = 1;
615
616 tstate->id = ++interp->tstate_next_unique_id;
617
618 if (init) {
Victor Stinner0fd2c302019-06-04 03:15:09 +0200619 _PyThreadState_Init(runtime, tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200620 }
621
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200622 HEAD_LOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200623 tstate->prev = NULL;
624 tstate->next = interp->tstate_head;
625 if (tstate->next)
626 tstate->next->prev = tstate;
627 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200628 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000631}
632
Victor Stinner45b9be52010-03-03 23:28:07 +0000633PyThreadState *
634PyThreadState_New(PyInterpreterState *interp)
635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000637}
638
639PyThreadState *
640_PyThreadState_Prealloc(PyInterpreterState *interp)
641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000643}
644
645void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200646_PyThreadState_Init(_PyRuntimeState *runtime, PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000647{
Victor Stinner8bb32302019-04-24 16:47:40 +0200648 _PyGILState_NoteThreadState(&runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000649}
650
Martin v. Löwis1a214512008-06-11 05:26:20 +0000651PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200652PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000653{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200654 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100655 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000657 if (module->m_slots) {
658 return NULL;
659 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 if (index == 0)
661 return NULL;
662 if (state->modules_by_index == NULL)
663 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200664 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 return NULL;
666 res = PyList_GET_ITEM(state->modules_by_index, index);
667 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000668}
669
670int
671_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
672{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000673 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300674 if (!def) {
675 assert(PyErr_Occurred());
676 return -1;
677 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000678 if (def->m_slots) {
679 PyErr_SetString(PyExc_SystemError,
680 "PyState_AddModule called on module with slots");
681 return -1;
682 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100683 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 if (!state->modules_by_index) {
685 state->modules_by_index = PyList_New(0);
686 if (!state->modules_by_index)
687 return -1;
688 }
Miss Islington (bot)a5a71022019-09-11 17:04:27 -0700689 while (PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 if (PyList_Append(state->modules_by_index, Py_None) < 0)
691 return -1;
692 Py_INCREF(module);
693 return PyList_SetItem(state->modules_by_index,
694 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000695}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000696
Martin v. Löwis7800f752012-06-22 12:20:55 +0200697int
698PyState_AddModule(PyObject* module, struct PyModuleDef* def)
699{
700 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100701 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200702 if (!def) {
703 Py_FatalError("PyState_AddModule: Module Definition is NULL");
704 return -1;
705 }
706 index = def->m_base.m_index;
Miss Islington (bot)a5a71022019-09-11 17:04:27 -0700707 if (state->modules_by_index &&
708 index < PyList_GET_SIZE(state->modules_by_index) &&
709 module == PyList_GET_ITEM(state->modules_by_index, index)) {
710 Py_FatalError("PyState_AddModule: Module already added!");
711 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200712 }
713 return _PyState_AddModule(module, def);
714}
715
716int
717PyState_RemoveModule(struct PyModuleDef* def)
718{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000719 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200720 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000721 if (def->m_slots) {
722 PyErr_SetString(PyExc_SystemError,
723 "PyState_RemoveModule called on module with slots");
724 return -1;
725 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100726 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200727 if (index == 0) {
728 Py_FatalError("PyState_RemoveModule: Module index invalid.");
729 return -1;
730 }
731 if (state->modules_by_index == NULL) {
Miss Islington (bot)4bd1d052019-08-30 13:42:54 -0700732 Py_FatalError("PyState_RemoveModule: Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200733 return -1;
734 }
735 if (index > PyList_GET_SIZE(state->modules_by_index)) {
736 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
737 return -1;
738 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700739 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200740 return PyList_SetItem(state->modules_by_index, index, Py_None);
741}
742
Antoine Pitrou40322e62013-08-11 00:30:09 +0200743/* used by import.c:PyImport_Cleanup */
744void
745_PyState_ClearModules(void)
746{
Victor Stinner9204fb82018-10-30 15:13:17 +0100747 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200748 if (state->modules_by_index) {
749 Py_ssize_t i;
750 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
751 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
752 if (PyModule_Check(m)) {
753 /* cleanup the saved copy of module dicts */
754 PyModuleDef *md = PyModule_GetDef(m);
755 if (md)
756 Py_CLEAR(md->m_base.m_copy);
757 }
758 }
759 /* Setting modules_by_index to NULL could be dangerous, so we
760 clear the list instead. */
761 if (PyList_SetSlice(state->modules_by_index,
762 0, PyList_GET_SIZE(state->modules_by_index),
763 NULL))
764 PyErr_WriteUnraisable(state->modules_by_index);
765 }
766}
767
Guido van Rossuma027efa1997-05-05 20:56:21 +0000768void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000769PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000770{
Victor Stinner331a6a52019-05-27 16:39:22 +0200771 int verbose = tstate->interp->config.verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200772
773 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 fprintf(stderr,
775 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 Py_CLEAR(tstate->dict);
780 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 Py_CLEAR(tstate->curexc_type);
783 Py_CLEAR(tstate->curexc_value);
784 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000785
Mark Shannonae3087c2017-10-22 22:41:51 +0100786 Py_CLEAR(tstate->exc_state.exc_type);
787 Py_CLEAR(tstate->exc_state.exc_value);
788 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300789
Mark Shannonae3087c2017-10-22 22:41:51 +0100790 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200791 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100792 fprintf(stderr,
793 "PyThreadState_Clear: warning: thread still has a generator\n");
794 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 tstate->c_profilefunc = NULL;
797 tstate->c_tracefunc = NULL;
798 Py_CLEAR(tstate->c_profileobj);
799 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400800
Yury Selivanoveb636452016-09-08 22:01:51 -0700801 Py_CLEAR(tstate->async_gen_firstiter);
802 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500803
804 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000805}
806
807
Guido van Rossum29757862001-01-23 01:46:06 +0000808/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
809static void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200810tstate_delete_common(_PyRuntimeState *runtime, PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000811{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200812 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 Py_FatalError("PyThreadState_Delete: NULL tstate");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200814 }
815 PyInterpreterState *interp = tstate->interp;
816 if (interp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 Py_FatalError("PyThreadState_Delete: NULL interp");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200818 }
819 HEAD_LOCK(runtime);
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200820 if (tstate->prev)
821 tstate->prev->next = tstate->next;
822 else
823 interp->tstate_head = tstate->next;
824 if (tstate->next)
825 tstate->next->prev = tstate->prev;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200826 HEAD_UNLOCK(runtime);
Antoine Pitrou7b476992013-09-07 23:38:37 +0200827 if (tstate->on_delete != NULL) {
828 tstate->on_delete(tstate->on_delete_data);
829 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200830 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000831}
832
833
Victor Stinner0fd2c302019-06-04 03:15:09 +0200834static void
835_PyThreadState_Delete(_PyRuntimeState *runtime, PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000836{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200837 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
838 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600840 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200841 if (gilstate->autoInterpreterState &&
842 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
843 {
844 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
845 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200846 tstate_delete_common(runtime, tstate);
847}
848
849
850void
851PyThreadState_Delete(PyThreadState *tstate)
852{
853 _PyThreadState_Delete(&_PyRuntime, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200854}
855
856
857static void
858_PyThreadState_DeleteCurrent(_PyRuntimeState *runtime)
859{
860 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
861 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 if (tstate == NULL)
863 Py_FatalError(
864 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner0fd2c302019-06-04 03:15:09 +0200865 tstate_delete_common(runtime, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200866 if (gilstate->autoInterpreterState &&
867 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600868 {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200869 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600870 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200871 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000873}
Guido van Rossum29757862001-01-23 01:46:06 +0000874
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200875void
876PyThreadState_DeleteCurrent()
877{
878 _PyThreadState_DeleteCurrent(&_PyRuntime);
879}
880
Guido van Rossum29757862001-01-23 01:46:06 +0000881
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200882/*
883 * Delete all thread states except the one passed as argument.
884 * Note that, if there is a current thread state, it *must* be the one
885 * passed as argument. Also, this won't touch any other interpreters
886 * than the current one, since we don't know which thread state should
Miss Islington (bot)4bd1d052019-08-30 13:42:54 -0700887 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200888 */
889void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200890_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200891{
892 PyInterpreterState *interp = tstate->interp;
893 PyThreadState *p, *next, *garbage;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200894 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200895 /* Remove all thread states, except tstate, from the linked list of
896 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200897 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200898 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200899 if (garbage == tstate)
900 garbage = tstate->next;
901 if (tstate->prev)
902 tstate->prev->next = tstate->next;
903 if (tstate->next)
904 tstate->next->prev = tstate->prev;
905 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200906 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200907 HEAD_UNLOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200908 /* Clear and deallocate all stale thread states. Even if this
909 executes Python code, we should be safe since it executes
910 in the current thread, not one of the stale threads. */
911 for (p = garbage; p; p = next) {
912 next = p->next;
913 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200914 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200915 }
916}
917
918
Guido van Rossuma027efa1997-05-05 20:56:21 +0000919PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100920_PyThreadState_UncheckedGet(void)
921{
Victor Stinner50b48572018-11-01 01:51:40 +0100922 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100923}
924
925
926PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000927PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000928{
Victor Stinner50b48572018-11-01 01:51:40 +0100929 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 if (tstate == NULL)
931 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000934}
935
936
Victor Stinner09532fe2019-05-10 23:39:09 +0200937PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200938_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000939{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200940 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000941
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200942 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 /* It should not be possible for more than one thread state
944 to be used for a thread. Check this the best we can in debug
945 builds.
946 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200947#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 if (newts) {
949 /* This can be called from PyEval_RestoreThread(). Similar
950 to it, we need to ensure errno doesn't change.
951 */
952 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200953 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (check && check->interp == newts->interp && check != newts)
955 Py_FatalError("Invalid thread state for this thread");
956 errno = err;
957 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000958#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000960}
Guido van Rossumede04391998-04-10 20:18:25 +0000961
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200962PyThreadState *
963PyThreadState_Swap(PyThreadState *newts)
964{
965 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
966}
967
Guido van Rossumede04391998-04-10 20:18:25 +0000968/* An extension mechanism to store arbitrary additional per-thread state.
969 PyThreadState_GetDict() returns a dictionary that can be used to hold such
970 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000971 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
972 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000973
974PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000975PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000976{
Victor Stinner50b48572018-11-01 01:51:40 +0100977 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 if (tstate == NULL)
979 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 if (tstate->dict == NULL) {
982 PyObject *d;
983 tstate->dict = d = PyDict_New();
984 if (d == NULL)
985 PyErr_Clear();
986 }
987 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000988}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000989
990
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000991/* Asynchronously raise an exception in a thread.
992 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000993 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000994 to call this, or use ctypes. Must be called with the GIL held.
995 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
996 match any known thread id). Can be called with exc=NULL to clear an
997 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000998
999int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001000PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1001{
Victor Stinner09532fe2019-05-10 23:39:09 +02001002 _PyRuntimeState *runtime = &_PyRuntime;
1003 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 /* Although the GIL is held, a few C API functions can be called
1006 * without the GIL held, and in particular some that create and
1007 * destroy thread and interpreter states. Those can mutate the
1008 * list of thread states we're traversing, so to prevent that we lock
1009 * head_mutex for the duration.
1010 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001011 HEAD_LOCK(runtime);
Victor Stinner09532fe2019-05-10 23:39:09 +02001012 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 if (p->thread_id == id) {
1014 /* Tricky: we need to decref the current value
1015 * (if any) in p->async_exc, but that can in turn
1016 * allow arbitrary Python code to run, including
1017 * perhaps calls to this function. To prevent
1018 * deadlock, we need to release head_mutex before
1019 * the decref.
1020 */
1021 PyObject *old_exc = p->async_exc;
1022 Py_XINCREF(exc);
1023 p->async_exc = exc;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001024 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 Py_XDECREF(old_exc);
Victor Stinnere225beb2019-06-03 18:14:24 +02001026 _PyEval_SignalAsyncExc(&runtime->ceval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 return 1;
1028 }
1029 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001030 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001032}
1033
1034
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001035/* Routines for advanced debuggers, requested by David Beazley.
1036 Don't use unless you know what you are doing! */
1037
1038PyInterpreterState *
1039PyInterpreterState_Head(void)
1040{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001041 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001042}
1043
1044PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001045PyInterpreterState_Main(void)
1046{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001047 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001048}
1049
1050PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001051PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001053}
1054
1055PyThreadState *
1056PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001058}
1059
1060PyThreadState *
1061PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001063}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001064
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001065/* The implementation of sys._current_frames(). This is intended to be
1066 called with the GIL held, as it will be when called via
1067 sys._current_frames(). It's possible it would work fine even without
1068 the GIL held, but haven't thought enough about that.
1069*/
1070PyObject *
1071_PyThread_CurrentFrames(void)
1072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 PyObject *result;
1074 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001075
Steve Dowerb82e17e2019-05-23 08:45:22 -07001076 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1077 return NULL;
1078 }
1079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 result = PyDict_New();
1081 if (result == NULL)
1082 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 /* for i in all interpreters:
1085 * for t in all of i's thread states:
1086 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001087 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 * need to grab head_mutex for the duration.
1089 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001090 _PyRuntimeState *runtime = &_PyRuntime;
1091 HEAD_LOCK(runtime);
1092 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 PyThreadState *t;
1094 for (t = i->tstate_head; t != NULL; t = t->next) {
1095 PyObject *id;
1096 int stat;
1097 struct _frame *frame = t->frame;
1098 if (frame == NULL)
1099 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001100 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (id == NULL)
1102 goto Fail;
1103 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1104 Py_DECREF(id);
1105 if (stat < 0)
1106 goto Fail;
1107 }
1108 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001109 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001111
1112 Fail:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001113 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 Py_DECREF(result);
1115 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001116}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001117
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001118/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001119
1120/* Keep this as a static, as it is not reliable! It can only
1121 ever be compared to the state for the *current* thread.
1122 * If not equal, then it doesn't matter that the actual
1123 value may change immediately after comparison, as it can't
1124 possibly change to the current thread's state.
1125 * If equal, then the current thread holds the lock, so the value can't
1126 change until we yield the lock.
1127*/
1128static int
1129PyThreadState_IsCurrent(PyThreadState *tstate)
1130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001132 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001133 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1134 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001135}
1136
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001137/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001138 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001139*/
Tim Peters19717fa2004-10-09 17:38:29 +00001140void
Victor Stinner0fd2c302019-06-04 03:15:09 +02001141_PyGILState_Init(_PyRuntimeState *runtime,
1142 PyInterpreterState *interp, PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001143{
Victor Stinner8bb32302019-04-24 16:47:40 +02001144 /* must init with valid states */
Eric Snow396e0a82019-05-31 21:16:47 -06001145 assert(interp != NULL);
Victor Stinner0fd2c302019-06-04 03:15:09 +02001146 assert(tstate != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001147
Victor Stinner8bb32302019-04-24 16:47:40 +02001148 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1149
1150 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001151 Py_FatalError("Could not allocate TSS entry");
1152 }
Victor Stinner8bb32302019-04-24 16:47:40 +02001153 gilstate->autoInterpreterState = interp;
1154 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1155 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001156
Victor Stinner8bb32302019-04-24 16:47:40 +02001157 _PyGILState_NoteThreadState(gilstate, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001158}
1159
Victor Stinner861d9ab2016-03-16 22:45:24 +01001160PyInterpreterState *
1161_PyGILState_GetInterpreterStateUnsafe(void)
1162{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001163 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001164}
1165
Tim Peters19717fa2004-10-09 17:38:29 +00001166void
Victor Stinner8e91c242019-04-24 17:24:01 +02001167_PyGILState_Fini(_PyRuntimeState *runtime)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001168{
Victor Stinner8e91c242019-04-24 17:24:01 +02001169 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1170 PyThread_tss_delete(&gilstate->autoTSSkey);
1171 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001172}
1173
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001174/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001175 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001176 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001177 */
1178void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001179_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001180{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001181 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001182 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001183
1184 PyThread_tss_delete(&gilstate->autoTSSkey);
1185 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001186 Py_FatalError("Could not allocate TSS entry");
1187 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001188
Charles-François Natalia233df82011-11-22 19:49:51 +01001189 /* If the thread had an associated auto thread state, reassociate it with
1190 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001191 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001192 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001193 {
1194 Py_FatalError("Couldn't create autoTSSkey mapping");
1195 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001196}
1197
Michael W. Hudson188d4362005-06-20 16:52:57 +00001198/* When a thread state is created for a thread by some mechanism other than
1199 PyGILState_Ensure, it's important that the GILState machinery knows about
1200 it so it doesn't try to create another thread state for the thread (this is
1201 a better fix for SF bug #1010677 than the first one attempted).
1202*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001203static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001204_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001205{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001206 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001207 threadstate created in Py_Initialize(). Don't do anything for now
1208 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001209 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001211 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001212
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001213 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 The only situation where you can legitimately have more than one
1216 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001217 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001218
Victor Stinner590cebe2013-12-13 11:08:56 +01001219 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1220 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001221
Victor Stinner590cebe2013-12-13 11:08:56 +01001222 The first thread state created for that given OS level thread will
1223 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001225 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1226 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001227 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001228 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001229 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 /* PyGILState_Release must not try to delete this thread state. */
1232 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001233}
1234
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001235/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001236static PyThreadState *
1237_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1238{
1239 if (gilstate->autoInterpreterState == NULL)
1240 return NULL;
1241 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1242}
1243
Tim Peters19717fa2004-10-09 17:38:29 +00001244PyThreadState *
1245PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001246{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001247 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001248}
1249
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001250int
1251PyGILState_Check(void)
1252{
Victor Stinner8a1be612016-03-14 22:07:55 +01001253
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001254 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001255 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001256 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001257
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001258 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1259 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1260 return 1;
1261 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001262
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001263 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1264 if (tstate == NULL) {
1265 return 0;
1266 }
1267
1268 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001269}
1270
Tim Peters19717fa2004-10-09 17:38:29 +00001271PyGILState_STATE
1272PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001273{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001274 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 int current;
1276 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001277 int need_init_threads = 0;
1278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 /* Note that we do not auto-init Python here - apart from
1280 potential races with 2 threads auto-initializing, pep-311
1281 spells out other issues. Embedders are expected to have
1282 called Py_Initialize() and usually PyEval_InitThreads().
1283 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001284 /* Py_Initialize() hasn't been called! */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001285 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001286
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001287 tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001289 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 /* Create a new thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001292 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 if (tcur == NULL)
1294 Py_FatalError("Couldn't create thread-state for new thread");
1295 /* This is our thread state! We'll need to delete it in the
1296 matching call to PyGILState_Release(). */
1297 tcur->gilstate_counter = 0;
1298 current = 0; /* new thread state is never current */
1299 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001300 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001302 }
1303
1304 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001306 }
1307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 /* Update our counter in the thread-state - no need for locks:
1309 - tcur will remain valid as we hold the GIL.
1310 - the counter is safe as we are the only thread "allowed"
1311 to modify this value
1312 */
1313 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001314
1315 if (need_init_threads) {
1316 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1317 called from a new thread for the first time, we need the create the
1318 GIL. */
1319 PyEval_InitThreads();
1320 }
1321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001323}
1324
Tim Peters19717fa2004-10-09 17:38:29 +00001325void
1326PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001327{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001328 _PyRuntimeState *runtime = &_PyRuntime;
1329 PyThreadState *tcur = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1330 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 Py_FatalError("auto-releasing thread-state, "
1332 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001333 }
1334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 /* We must hold the GIL and have our thread state current */
1336 /* XXX - remove the check - the assert should be fine,
1337 but while this is very new (April 2003), the extra check
1338 by release-only users can't hurt.
1339 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001340 if (!PyThreadState_IsCurrent(tcur)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 Py_FatalError("This thread state must be current when releasing");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001342 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 assert(PyThreadState_IsCurrent(tcur));
1344 --tcur->gilstate_counter;
1345 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 /* If we're going to destroy this thread-state, we must
1348 * clear it while the GIL is held, as destructors may run.
1349 */
1350 if (tcur->gilstate_counter == 0) {
1351 /* can't have been locked when we created it */
1352 assert(oldstate == PyGILState_UNLOCKED);
1353 PyThreadState_Clear(tcur);
1354 /* Delete the thread-state. Note this releases the GIL too!
1355 * It's vital that the GIL be held here, to avoid shutdown
1356 * races; see bugs 225673 and 1061968 (that nasty bug has a
1357 * habit of coming back).
1358 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001359 _PyThreadState_DeleteCurrent(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 }
1361 /* Release the lock if necessary */
1362 else if (oldstate == PyGILState_UNLOCKED)
1363 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001364}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001365
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001366
Eric Snow7f8bfc92018-01-29 18:23:44 -07001367/**************************/
1368/* cross-interpreter data */
1369/**************************/
1370
1371/* cross-interpreter data */
1372
1373crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1374
1375/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1376 to keep the registry code separate. */
1377static crossinterpdatafunc
1378_lookup_getdata(PyObject *obj)
1379{
1380 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1381 if (getdata == NULL && PyErr_Occurred() == 0)
1382 PyErr_Format(PyExc_ValueError,
1383 "%S does not support cross-interpreter data", obj);
1384 return getdata;
1385}
1386
1387int
1388_PyObject_CheckCrossInterpreterData(PyObject *obj)
1389{
1390 crossinterpdatafunc getdata = _lookup_getdata(obj);
1391 if (getdata == NULL) {
1392 return -1;
1393 }
1394 return 0;
1395}
1396
1397static int
1398_check_xidata(_PyCrossInterpreterData *data)
1399{
1400 // data->data can be anything, including NULL, so we don't check it.
1401
1402 // data->obj may be NULL, so we don't check it.
1403
1404 if (data->interp < 0) {
1405 PyErr_SetString(PyExc_SystemError, "missing interp");
1406 return -1;
1407 }
1408
1409 if (data->new_object == NULL) {
1410 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1411 return -1;
1412 }
1413
1414 // data->free may be NULL, so we don't check it.
1415
1416 return 0;
1417}
1418
1419int
1420_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1421{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001422 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001423 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001424 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001425
1426 // Reset data before re-populating.
1427 *data = (_PyCrossInterpreterData){0};
1428 data->free = PyMem_RawFree; // Set a default that may be overridden.
1429
1430 // Call the "getdata" func for the object.
1431 Py_INCREF(obj);
1432 crossinterpdatafunc getdata = _lookup_getdata(obj);
1433 if (getdata == NULL) {
1434 Py_DECREF(obj);
1435 return -1;
1436 }
1437 int res = getdata(obj, data);
1438 Py_DECREF(obj);
1439 if (res != 0) {
1440 return -1;
1441 }
1442
1443 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001444 data->interp = interp->id;
1445 if (_check_xidata(data) != 0) {
1446 _PyCrossInterpreterData_Release(data);
1447 return -1;
1448 }
1449
1450 return 0;
1451}
1452
Victor Stinnere225beb2019-06-03 18:14:24 +02001453static void
Eric Snow63799132018-06-01 18:45:20 -06001454_release_xidata(void *arg)
1455{
1456 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1457 if (data->free != NULL) {
1458 data->free(data->data);
1459 }
1460 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001461}
1462
1463static void
1464_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1465 PyInterpreterState *interp,
1466 void (*func)(void *), void *arg)
1467{
1468 /* We would use Py_AddPendingCall() if it weren't specific to the
1469 * main interpreter (see bpo-33608). In the meantime we take a
1470 * naive approach.
1471 */
1472 PyThreadState *save_tstate = NULL;
1473 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1474 // XXX Using the "head" thread isn't strictly correct.
1475 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1476 // XXX Possible GILState issues?
1477 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1478 }
1479
1480 func(arg);
1481
1482 // Switch back.
1483 if (save_tstate != NULL) {
1484 _PyThreadState_Swap(gilstate, save_tstate);
1485 }
Eric Snow63799132018-06-01 18:45:20 -06001486}
1487
Eric Snow7f8bfc92018-01-29 18:23:44 -07001488void
1489_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1490{
1491 if (data->data == NULL && data->obj == NULL) {
1492 // Nothing to release!
1493 return;
1494 }
1495
Victor Stinnere225beb2019-06-03 18:14:24 +02001496 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001497 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1498 if (interp == NULL) {
1499 // The intepreter was already destroyed.
1500 if (data->free != NULL) {
1501 // XXX Someone leaked some memory...
1502 }
1503 return;
1504 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001505
Eric Snow7f8bfc92018-01-29 18:23:44 -07001506 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001507 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1508 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001509}
1510
1511PyObject *
1512_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1513{
1514 return data->new_object(data);
1515}
1516
1517/* registry of {type -> crossinterpdatafunc} */
1518
1519/* For now we use a global registry of shareable classes. An
1520 alternative would be to add a tp_* slot for a class's
1521 crossinterpdatafunc. It would be simpler and more efficient. */
1522
1523static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001524_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1525 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001526{
1527 // Note that we effectively replace already registered classes
1528 // rather than failing.
1529 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1530 if (newhead == NULL)
1531 return -1;
1532 newhead->cls = cls;
1533 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001534 newhead->next = xidregistry->head;
1535 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001536 return 0;
1537}
1538
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001539static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001540
1541int
Eric Snowc11183c2019-03-15 16:35:46 -06001542_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001543 crossinterpdatafunc getdata)
1544{
1545 if (!PyType_Check(cls)) {
1546 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1547 return -1;
1548 }
1549 if (getdata == NULL) {
1550 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1551 return -1;
1552 }
1553
1554 // Make sure the class isn't ever deallocated.
1555 Py_INCREF((PyObject *)cls);
1556
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001557 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1558 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1559 if (xidregistry->head == NULL) {
1560 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001561 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001562 int res = _register_xidata(xidregistry, cls, getdata);
1563 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001564 return res;
1565}
1566
Eric Snow6d2cd902018-05-16 15:04:57 -04001567/* Cross-interpreter objects are looked up by exact match on the class.
1568 We can reassess this policy when we move from a global registry to a
1569 tp_* slot. */
1570
Eric Snow7f8bfc92018-01-29 18:23:44 -07001571crossinterpdatafunc
1572_PyCrossInterpreterData_Lookup(PyObject *obj)
1573{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001574 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001575 PyObject *cls = PyObject_Type(obj);
1576 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001577 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1578 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001579 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001580 _register_builtins_for_crossinterpreter_data(xidregistry);
1581 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001582 }
1583 for(; cur != NULL; cur = cur->next) {
1584 if (cur->cls == (PyTypeObject *)cls) {
1585 getdata = cur->getdata;
1586 break;
1587 }
1588 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001589 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001590 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001591 return getdata;
1592}
1593
1594/* cross-interpreter data for builtin types */
1595
Eric Snow6d2cd902018-05-16 15:04:57 -04001596struct _shared_bytes_data {
1597 char *bytes;
1598 Py_ssize_t len;
1599};
1600
Eric Snow7f8bfc92018-01-29 18:23:44 -07001601static PyObject *
1602_new_bytes_object(_PyCrossInterpreterData *data)
1603{
Eric Snow6d2cd902018-05-16 15:04:57 -04001604 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1605 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001606}
1607
1608static int
1609_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1610{
Eric Snow6d2cd902018-05-16 15:04:57 -04001611 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1612 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1613 return -1;
1614 }
1615 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001616 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001617 data->obj = obj; // Will be "released" (decref'ed) when data released.
1618 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001619 data->free = PyMem_Free;
1620 return 0;
1621}
1622
1623struct _shared_str_data {
1624 int kind;
1625 const void *buffer;
1626 Py_ssize_t len;
1627};
1628
1629static PyObject *
1630_new_str_object(_PyCrossInterpreterData *data)
1631{
1632 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1633 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1634}
1635
1636static int
1637_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1638{
1639 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1640 shared->kind = PyUnicode_KIND(obj);
1641 shared->buffer = PyUnicode_DATA(obj);
1642 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1643 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001644 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001645 data->obj = obj; // Will be "released" (decref'ed) when data released.
1646 data->new_object = _new_str_object;
1647 data->free = PyMem_Free;
1648 return 0;
1649}
1650
1651static PyObject *
1652_new_long_object(_PyCrossInterpreterData *data)
1653{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001654 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001655}
1656
1657static int
1658_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1659{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001660 /* Note that this means the size of shareable ints is bounded by
1661 * sys.maxsize. Hence on 32-bit architectures that is half the
1662 * size of maximum shareable ints on 64-bit.
1663 */
1664 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001665 if (value == -1 && PyErr_Occurred()) {
1666 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1667 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1668 }
1669 return -1;
1670 }
1671 data->data = (void *)value;
1672 data->obj = NULL;
1673 data->new_object = _new_long_object;
1674 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001675 return 0;
1676}
1677
1678static PyObject *
1679_new_none_object(_PyCrossInterpreterData *data)
1680{
1681 // XXX Singleton refcounts are problematic across interpreters...
1682 Py_INCREF(Py_None);
1683 return Py_None;
1684}
1685
1686static int
1687_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1688{
1689 data->data = NULL;
1690 // data->obj remains NULL
1691 data->new_object = _new_none_object;
1692 data->free = NULL; // There is nothing to free.
1693 return 0;
1694}
1695
1696static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001697_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001698{
1699 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001700 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001701 Py_FatalError("could not register None for cross-interpreter sharing");
1702 }
1703
Eric Snow6d2cd902018-05-16 15:04:57 -04001704 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001705 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001706 Py_FatalError("could not register int for cross-interpreter sharing");
1707 }
1708
Eric Snow7f8bfc92018-01-29 18:23:44 -07001709 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001710 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001711 Py_FatalError("could not register bytes for cross-interpreter sharing");
1712 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001713
1714 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001715 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001716 Py_FatalError("could not register str for cross-interpreter sharing");
1717 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001718}
1719
1720
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001721#ifdef __cplusplus
1722}
1723#endif