blob: f0662fa706572159b6d257739cfb2cc6a038e282 [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
64 runtime->preconfig.struct_size = sizeof(PyPreConfig);
65 PyStatus status = PyPreConfig_InitPythonConfig(&runtime->preconfig);
66 if (_PyStatus_EXCEPTION(status)) {
67 return status;
68 }
Michael W. Hudson188d4362005-06-20 16:52:57 +000069
Eric Snow2ebc5ce2017-09-07 23:51:28 -060070 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080071
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090072 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
73 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080074 Py_tss_t initial = Py_tss_NEEDS_INIT;
75 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000076
Eric Snow2ebc5ce2017-09-07 23:51:28 -060077 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080078 if (runtime->interpreters.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020079 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080080 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060081 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070082
83 runtime->xidregistry.mutex = PyThread_allocate_lock();
84 if (runtime->xidregistry.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020085 return _PyStatus_ERR("Can't initialize threads for cross-interpreter data registry");
Eric Snow7f8bfc92018-01-29 18:23:44 -070086 }
87
Eric Snow8479a342019-03-08 23:44:33 -070088 // Set it to the ID of the main thread of the main interpreter.
89 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070090
Victor Stinner331a6a52019-05-27 16:39:22 +020091 return _PyStatus_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060092}
Eric Snow05351c12017-09-05 21:43:08 -070093
Victor Stinner331a6a52019-05-27 16:39:22 +020094PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010095_PyRuntimeState_Init(_PyRuntimeState *runtime)
96{
97 /* Force default allocator, since _PyRuntimeState_Fini() must
98 use the same allocator than this function. */
99 PyMemAllocatorEx old_alloc;
100 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
101
Victor Stinner331a6a52019-05-27 16:39:22 +0200102 PyStatus status = _PyRuntimeState_Init_impl(runtime);
Victor Stinner5d39e042017-11-29 17:20:38 +0100103
104 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinner331a6a52019-05-27 16:39:22 +0200105 return status;
Victor Stinner5d39e042017-11-29 17:20:38 +0100106}
107
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600108void
109_PyRuntimeState_Fini(_PyRuntimeState *runtime)
110{
Victor Stinner5d39e042017-11-29 17:20:38 +0100111 /* Force the allocator used by _PyRuntimeState_Init(). */
112 PyMemAllocatorEx old_alloc;
113 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -0800114
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600115 if (runtime->interpreters.mutex != NULL) {
116 PyThread_free_lock(runtime->interpreters.mutex);
117 runtime->interpreters.mutex = NULL;
118 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800119
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100120 if (runtime->xidregistry.mutex != NULL) {
121 PyThread_free_lock(runtime->xidregistry.mutex);
122 runtime->xidregistry.mutex = NULL;
123 }
124
Victor Stinnerccb04422017-11-16 03:20:31 -0800125 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600126}
127
Eric Snow8479a342019-03-08 23:44:33 -0700128/* This function is called from PyOS_AfterFork_Child to ensure that
129 * newly created child processes do not share locks with the parent.
130 */
131
132void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200133_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700134{
135 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200136 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700137
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200138 /* Force default allocator, since _PyRuntimeState_Fini() must
139 use the same allocator than this function. */
140 PyMemAllocatorEx old_alloc;
141 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
142
143 runtime->interpreters.mutex = PyThread_allocate_lock();
144 runtime->interpreters.main->id_mutex = PyThread_allocate_lock();
145 runtime->xidregistry.mutex = PyThread_allocate_lock();
146
147 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
148
149 if (runtime->interpreters.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700150 Py_FatalError("Can't initialize lock for runtime interpreters");
151 }
152
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200153 if (runtime->interpreters.main->id_mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700154 Py_FatalError("Can't initialize ID lock for main interpreter");
155 }
156
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200157 if (runtime->xidregistry.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700158 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
159 }
160}
161
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200162#define HEAD_LOCK(runtime) \
163 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
164#define HEAD_UNLOCK(runtime) \
165 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700166
Victor Stinner8bb32302019-04-24 16:47:40 +0200167/* Forward declaration */
168static void _PyGILState_NoteThreadState(
169 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000170
Victor Stinner331a6a52019-05-27 16:39:22 +0200171PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600172_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700173{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200174 struct pyinterpreters *interpreters = &runtime->interpreters;
175 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100176
177 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
178 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200179 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100180 /* Force default allocator, since _PyRuntimeState_Fini() must
181 use the same allocator than this function. */
182 PyMemAllocatorEx old_alloc;
183 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
184
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200185 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100186
187 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
188
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200189 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200190 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800191 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600192 }
Victor Stinner5d926472018-03-06 14:31:37 +0100193
Victor Stinner331a6a52019-05-27 16:39:22 +0200194 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700195}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000196
197PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000198PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000199{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700200 if (PySys_Audit("cpython.PyInterpreterState_New", NULL) < 0) {
201 return NULL;
202 }
203
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200204 PyInterpreterState *interp = PyMem_RawMalloc(sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100205 if (interp == NULL) {
206 return NULL;
207 }
208
Eric Snow5be45a62019-03-08 22:47:07 -0700209 memset(interp, 0, sizeof(*interp));
Eric Snow4c6955e2018-02-16 18:53:40 -0700210 interp->id_refcount = -1;
Victor Stinnerd4341102017-11-23 00:12:09 +0100211 interp->check_interval = 100;
Victor Stinner022be022019-05-22 23:58:50 +0200212
Victor Stinner6e128382019-09-28 04:50:43 +0200213 interp->config.struct_size = sizeof(PyConfig);
Victor Stinner331a6a52019-05-27 16:39:22 +0200214 PyStatus status = PyConfig_InitPythonConfig(&interp->config);
215 if (_PyStatus_EXCEPTION(status)) {
216 /* Don't report status to caller: PyConfig_InitPythonConfig()
217 can only fail with a memory allocation error. */
218 PyConfig_Clear(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200219 PyMem_RawFree(interp);
220 return NULL;
221 }
222
Victor Stinnerd4341102017-11-23 00:12:09 +0100223 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000224#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300225#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100226 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000227#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100228 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000229#endif
230#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000231
Victor Stinner0fd2c302019-06-04 03:15:09 +0200232 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200233 struct pyinterpreters *interpreters = &runtime->interpreters;
234
235 HEAD_LOCK(runtime);
236 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100237 /* overflow or Py_Initialize() not called! */
238 PyErr_SetString(PyExc_RuntimeError,
239 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100240 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100241 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100242 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200243 else {
244 interp->id = interpreters->next_id;
245 interpreters->next_id += 1;
246 interp->next = interpreters->head;
247 if (interpreters->main == NULL) {
248 interpreters->main = interp;
249 }
250 interpreters->head = interp;
251 }
252 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000253
Pablo Galindo95d630e2018-08-31 22:49:29 +0100254 if (interp == NULL) {
255 return NULL;
256 }
257
Yury Selivanovf23746a2018-01-22 19:11:18 -0500258 interp->tstate_next_unique_id = 0;
259
Steve Dowerb82e17e2019-05-23 08:45:22 -0700260 interp->audit_hooks = NULL;
261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000263}
264
265
Victor Stinner0fd2c302019-06-04 03:15:09 +0200266static void
267_PyInterpreterState_Clear(_PyRuntimeState *runtime, PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000268{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700269 if (PySys_Audit("cpython.PyInterpreterState_Clear", NULL) < 0) {
270 PyErr_Clear();
271 }
272
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200273 HEAD_LOCK(runtime);
274 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200276 }
277 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700278
279 Py_CLEAR(interp->audit_hooks);
280
Victor Stinner331a6a52019-05-27 16:39:22 +0200281 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 Py_CLEAR(interp->codec_search_path);
283 Py_CLEAR(interp->codec_search_cache);
284 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700285 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 Py_CLEAR(interp->sysdict);
288 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200289 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400290 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300291 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600292 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200293#ifdef HAVE_FORK
294 Py_CLEAR(interp->before_forkers);
295 Py_CLEAR(interp->after_forkers_parent);
296 Py_CLEAR(interp->after_forkers_child);
297#endif
Eric Snow86ea5812019-05-10 13:29:55 -0400298 if (runtime->finalizing == NULL) {
299 _PyWarnings_Fini(interp);
300 }
Eric Snow5be45a62019-03-08 22:47:07 -0700301 // XXX Once we have one allocator per interpreter (i.e.
302 // per-interpreter GC) we must ensure that all of the interpreter's
303 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000304}
305
Victor Stinner0fd2c302019-06-04 03:15:09 +0200306void
307PyInterpreterState_Clear(PyInterpreterState *interp)
308{
309 _PyInterpreterState_Clear(&_PyRuntime, interp);
310}
311
Guido van Rossum25ce5661997-08-02 03:10:38 +0000312
313static void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200314zapthreads(_PyRuntimeState *runtime, PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000315{
Victor Stinner0fd2c302019-06-04 03:15:09 +0200316 PyThreadState *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 /* No need to lock the mutex here because this should only happen
318 when the threads are all really dead (XXX famous last words). */
Victor Stinner0fd2c302019-06-04 03:15:09 +0200319 while ((p = interp->tstate_head) != NULL) {
320 _PyThreadState_Delete(runtime, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000322}
323
324
Victor Stinner0fd2c302019-06-04 03:15:09 +0200325static void
326_PyInterpreterState_Delete(_PyRuntimeState *runtime,
327 PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200328{
329 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner0fd2c302019-06-04 03:15:09 +0200330 zapthreads(runtime, interp);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200331 HEAD_LOCK(runtime);
332 PyInterpreterState **p;
333 for (p = &interpreters->head; ; p = &(*p)->next) {
334 if (*p == NULL) {
335 Py_FatalError("PyInterpreterState_Delete: invalid interp");
336 }
337 if (*p == interp) {
338 break;
339 }
340 }
341 if (interp->tstate_head != NULL) {
342 Py_FatalError("PyInterpreterState_Delete: remaining threads");
343 }
344 *p = interp->next;
345 if (interpreters->main == interp) {
346 interpreters->main = NULL;
347 if (interpreters->head != NULL) {
348 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
349 }
350 }
351 HEAD_UNLOCK(runtime);
352 if (interp->id_mutex != NULL) {
353 PyThread_free_lock(interp->id_mutex);
354 }
355 PyMem_RawFree(interp);
356}
357
358
Victor Stinner0fd2c302019-06-04 03:15:09 +0200359void
360PyInterpreterState_Delete(PyInterpreterState *interp)
361{
362 _PyInterpreterState_Delete(&_PyRuntime, interp);
363}
364
365
Eric Snow59032962018-09-14 14:17:20 -0700366/*
367 * Delete all interpreter states except the main interpreter. If there
368 * is a current interpreter state, it *must* be the main interpreter.
369 */
370void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200371_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700372{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200373 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200374 struct pyinterpreters *interpreters = &runtime->interpreters;
375
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200376 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200377 if (tstate != NULL && tstate->interp != interpreters->main) {
Eric Snow59032962018-09-14 14:17:20 -0700378 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
379 }
380
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200381 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200382 PyInterpreterState *interp = interpreters->head;
383 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100384 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200385 if (interp == interpreters->main) {
386 interpreters->main->next = NULL;
387 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100388 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700389 continue;
390 }
391
Victor Stinner0fd2c302019-06-04 03:15:09 +0200392 _PyInterpreterState_Clear(runtime, interp); // XXX must activate?
393 zapthreads(runtime, interp);
Eric Snow59032962018-09-14 14:17:20 -0700394 if (interp->id_mutex != NULL) {
395 PyThread_free_lock(interp->id_mutex);
396 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100397 PyInterpreterState *prev_interp = interp;
398 interp = interp->next;
399 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700400 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200401 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700402
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200403 if (interpreters->head == NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700404 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
405 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200406 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700407}
408
409
Victor Stinnercaba55b2018-08-03 15:33:52 +0200410PyInterpreterState *
411_PyInterpreterState_Get(void)
412{
Victor Stinner50b48572018-11-01 01:51:40 +0100413 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200414 if (tstate == NULL) {
415 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
416 }
417 PyInterpreterState *interp = tstate->interp;
418 if (interp == NULL) {
419 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
420 }
421 return interp;
422}
423
424
Eric Snowe3774162017-05-22 19:46:40 -0700425int64_t
426PyInterpreterState_GetID(PyInterpreterState *interp)
427{
428 if (interp == NULL) {
429 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
430 return -1;
431 }
432 return interp->id;
433}
434
435
Eric Snow5be45a62019-03-08 22:47:07 -0700436static PyInterpreterState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200437interp_look_up_id(_PyRuntimeState *runtime, PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700438{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200439 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100440 while (interp != NULL) {
441 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700442 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100443 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700444 }
445 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100446 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700447 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100448 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700449 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100450 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700451}
452
Eric Snow5be45a62019-03-08 22:47:07 -0700453PyInterpreterState *
454_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
455{
456 PyInterpreterState *interp = NULL;
457 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200458 _PyRuntimeState *runtime = &_PyRuntime;
459 HEAD_LOCK(runtime);
460 interp = interp_look_up_id(runtime, requested_id);
461 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700462 }
463 if (interp == NULL && !PyErr_Occurred()) {
464 PyErr_Format(PyExc_RuntimeError,
465 "unrecognized interpreter ID %lld", requested_id);
466 }
467 return interp;
468}
469
Eric Snow4c6955e2018-02-16 18:53:40 -0700470
471int
472_PyInterpreterState_IDInitref(PyInterpreterState *interp)
473{
474 if (interp->id_mutex != NULL) {
475 return 0;
476 }
477 interp->id_mutex = PyThread_allocate_lock();
478 if (interp->id_mutex == NULL) {
479 PyErr_SetString(PyExc_RuntimeError,
480 "failed to create init interpreter ID mutex");
481 return -1;
482 }
483 interp->id_refcount = 0;
484 return 0;
485}
486
487
488void
489_PyInterpreterState_IDIncref(PyInterpreterState *interp)
490{
491 if (interp->id_mutex == NULL) {
492 return;
493 }
494 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
495 interp->id_refcount += 1;
496 PyThread_release_lock(interp->id_mutex);
497}
498
499
500void
501_PyInterpreterState_IDDecref(PyInterpreterState *interp)
502{
503 if (interp->id_mutex == NULL) {
504 return;
505 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200506 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700507 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
508 assert(interp->id_refcount != 0);
509 interp->id_refcount -= 1;
510 int64_t refcount = interp->id_refcount;
511 PyThread_release_lock(interp->id_mutex);
512
Eric Snowc11183c2019-03-15 16:35:46 -0600513 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700514 // XXX Using the "head" thread isn't strictly correct.
515 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
516 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200517 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700518 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200519 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700520 }
521}
522
Eric Snowc11183c2019-03-15 16:35:46 -0600523int
524_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
525{
526 return interp->requires_idref;
527}
528
529void
530_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
531{
532 interp->requires_idref = required ? 1 : 0;
533}
534
Eric Snowc11183c2019-03-15 16:35:46 -0600535PyObject *
536_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
537{
538 if (interp->modules == NULL) {
539 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
540 return NULL;
541 }
542 return PyMapping_GetItemString(interp->modules, "__main__");
543}
544
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600545PyObject *
546PyInterpreterState_GetDict(PyInterpreterState *interp)
547{
548 if (interp->dict == NULL) {
549 interp->dict = PyDict_New();
550 if (interp->dict == NULL) {
551 PyErr_Clear();
552 }
553 }
554 /* Returning NULL means no per-interpreter dict is available. */
555 return interp->dict;
556}
557
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000558/* Default implementation for _PyThreadState_GetFrame */
559static struct _frame *
560threadstate_getframe(PyThreadState *self)
561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000563}
564
Victor Stinner45b9be52010-03-03 23:28:07 +0000565static PyThreadState *
566new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000567{
Victor Stinner0fd2c302019-06-04 03:15:09 +0200568 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200569 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200570 if (tstate == NULL) {
571 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573
Victor Stinner8bb32302019-04-24 16:47:40 +0200574 if (_PyThreadState_GetFrame == NULL) {
575 _PyThreadState_GetFrame = threadstate_getframe;
576 }
577
578 tstate->interp = interp;
579
580 tstate->frame = NULL;
581 tstate->recursion_depth = 0;
582 tstate->overflowed = 0;
583 tstate->recursion_critical = 0;
584 tstate->stackcheck_counter = 0;
585 tstate->tracing = 0;
586 tstate->use_tracing = 0;
587 tstate->gilstate_counter = 0;
588 tstate->async_exc = NULL;
589 tstate->thread_id = PyThread_get_thread_ident();
590
591 tstate->dict = NULL;
592
593 tstate->curexc_type = NULL;
594 tstate->curexc_value = NULL;
595 tstate->curexc_traceback = NULL;
596
597 tstate->exc_state.exc_type = NULL;
598 tstate->exc_state.exc_value = NULL;
599 tstate->exc_state.exc_traceback = NULL;
600 tstate->exc_state.previous_item = NULL;
601 tstate->exc_info = &tstate->exc_state;
602
603 tstate->c_profilefunc = NULL;
604 tstate->c_tracefunc = NULL;
605 tstate->c_profileobj = NULL;
606 tstate->c_traceobj = NULL;
607
608 tstate->trash_delete_nesting = 0;
609 tstate->trash_delete_later = NULL;
610 tstate->on_delete = NULL;
611 tstate->on_delete_data = NULL;
612
613 tstate->coroutine_origin_tracking_depth = 0;
614
Victor Stinner8bb32302019-04-24 16:47:40 +0200615 tstate->async_gen_firstiter = NULL;
616 tstate->async_gen_finalizer = NULL;
617
618 tstate->context = NULL;
619 tstate->context_ver = 1;
620
621 tstate->id = ++interp->tstate_next_unique_id;
622
623 if (init) {
Victor Stinner0fd2c302019-06-04 03:15:09 +0200624 _PyThreadState_Init(runtime, tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200625 }
626
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200627 HEAD_LOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200628 tstate->prev = NULL;
629 tstate->next = interp->tstate_head;
630 if (tstate->next)
631 tstate->next->prev = tstate;
632 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200633 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000636}
637
Victor Stinner45b9be52010-03-03 23:28:07 +0000638PyThreadState *
639PyThreadState_New(PyInterpreterState *interp)
640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000642}
643
644PyThreadState *
645_PyThreadState_Prealloc(PyInterpreterState *interp)
646{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000648}
649
650void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200651_PyThreadState_Init(_PyRuntimeState *runtime, PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000652{
Victor Stinner8bb32302019-04-24 16:47:40 +0200653 _PyGILState_NoteThreadState(&runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000654}
655
Martin v. Löwis1a214512008-06-11 05:26:20 +0000656PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200657PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000658{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200659 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100660 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000662 if (module->m_slots) {
663 return NULL;
664 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 if (index == 0)
666 return NULL;
667 if (state->modules_by_index == NULL)
668 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200669 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 return NULL;
671 res = PyList_GET_ITEM(state->modules_by_index, index);
672 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000673}
674
675int
676_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
677{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000678 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300679 if (!def) {
680 assert(PyErr_Occurred());
681 return -1;
682 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000683 if (def->m_slots) {
684 PyErr_SetString(PyExc_SystemError,
685 "PyState_AddModule called on module with slots");
686 return -1;
687 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100688 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 if (!state->modules_by_index) {
690 state->modules_by_index = PyList_New(0);
691 if (!state->modules_by_index)
692 return -1;
693 }
Miss Islington (bot)a5a71022019-09-11 17:04:27 -0700694 while (PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 if (PyList_Append(state->modules_by_index, Py_None) < 0)
696 return -1;
697 Py_INCREF(module);
698 return PyList_SetItem(state->modules_by_index,
699 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000700}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000701
Martin v. Löwis7800f752012-06-22 12:20:55 +0200702int
703PyState_AddModule(PyObject* module, struct PyModuleDef* def)
704{
705 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100706 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200707 if (!def) {
708 Py_FatalError("PyState_AddModule: Module Definition is NULL");
709 return -1;
710 }
711 index = def->m_base.m_index;
Miss Islington (bot)a5a71022019-09-11 17:04:27 -0700712 if (state->modules_by_index &&
713 index < PyList_GET_SIZE(state->modules_by_index) &&
714 module == PyList_GET_ITEM(state->modules_by_index, index)) {
715 Py_FatalError("PyState_AddModule: Module already added!");
716 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200717 }
718 return _PyState_AddModule(module, def);
719}
720
721int
722PyState_RemoveModule(struct PyModuleDef* def)
723{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000724 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200725 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000726 if (def->m_slots) {
727 PyErr_SetString(PyExc_SystemError,
728 "PyState_RemoveModule called on module with slots");
729 return -1;
730 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100731 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200732 if (index == 0) {
733 Py_FatalError("PyState_RemoveModule: Module index invalid.");
734 return -1;
735 }
736 if (state->modules_by_index == NULL) {
Miss Islington (bot)4bd1d052019-08-30 13:42:54 -0700737 Py_FatalError("PyState_RemoveModule: Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200738 return -1;
739 }
740 if (index > PyList_GET_SIZE(state->modules_by_index)) {
741 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
742 return -1;
743 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700744 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200745 return PyList_SetItem(state->modules_by_index, index, Py_None);
746}
747
Antoine Pitrou40322e62013-08-11 00:30:09 +0200748/* used by import.c:PyImport_Cleanup */
749void
750_PyState_ClearModules(void)
751{
Victor Stinner9204fb82018-10-30 15:13:17 +0100752 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200753 if (state->modules_by_index) {
754 Py_ssize_t i;
755 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
756 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
757 if (PyModule_Check(m)) {
758 /* cleanup the saved copy of module dicts */
759 PyModuleDef *md = PyModule_GetDef(m);
760 if (md)
761 Py_CLEAR(md->m_base.m_copy);
762 }
763 }
764 /* Setting modules_by_index to NULL could be dangerous, so we
765 clear the list instead. */
766 if (PyList_SetSlice(state->modules_by_index,
767 0, PyList_GET_SIZE(state->modules_by_index),
768 NULL))
769 PyErr_WriteUnraisable(state->modules_by_index);
770 }
771}
772
Guido van Rossuma027efa1997-05-05 20:56:21 +0000773void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000774PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000775{
Victor Stinner331a6a52019-05-27 16:39:22 +0200776 int verbose = tstate->interp->config.verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200777
778 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 fprintf(stderr,
780 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 Py_CLEAR(tstate->dict);
785 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 Py_CLEAR(tstate->curexc_type);
788 Py_CLEAR(tstate->curexc_value);
789 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000790
Mark Shannonae3087c2017-10-22 22:41:51 +0100791 Py_CLEAR(tstate->exc_state.exc_type);
792 Py_CLEAR(tstate->exc_state.exc_value);
793 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300794
Mark Shannonae3087c2017-10-22 22:41:51 +0100795 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200796 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100797 fprintf(stderr,
798 "PyThreadState_Clear: warning: thread still has a generator\n");
799 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 tstate->c_profilefunc = NULL;
802 tstate->c_tracefunc = NULL;
803 Py_CLEAR(tstate->c_profileobj);
804 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400805
Yury Selivanoveb636452016-09-08 22:01:51 -0700806 Py_CLEAR(tstate->async_gen_firstiter);
807 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500808
809 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000810}
811
812
Guido van Rossum29757862001-01-23 01:46:06 +0000813/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
814static void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200815tstate_delete_common(_PyRuntimeState *runtime, PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000816{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200817 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 Py_FatalError("PyThreadState_Delete: NULL tstate");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200819 }
820 PyInterpreterState *interp = tstate->interp;
821 if (interp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 Py_FatalError("PyThreadState_Delete: NULL interp");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200823 }
824 HEAD_LOCK(runtime);
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200825 if (tstate->prev)
826 tstate->prev->next = tstate->next;
827 else
828 interp->tstate_head = tstate->next;
829 if (tstate->next)
830 tstate->next->prev = tstate->prev;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200831 HEAD_UNLOCK(runtime);
Antoine Pitrou7b476992013-09-07 23:38:37 +0200832 if (tstate->on_delete != NULL) {
833 tstate->on_delete(tstate->on_delete_data);
834 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200835 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000836}
837
838
Victor Stinner0fd2c302019-06-04 03:15:09 +0200839static void
840_PyThreadState_Delete(_PyRuntimeState *runtime, PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000841{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200842 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
843 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600845 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200846 if (gilstate->autoInterpreterState &&
847 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
848 {
849 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
850 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200851 tstate_delete_common(runtime, tstate);
852}
853
854
855void
856PyThreadState_Delete(PyThreadState *tstate)
857{
858 _PyThreadState_Delete(&_PyRuntime, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200859}
860
861
862static void
863_PyThreadState_DeleteCurrent(_PyRuntimeState *runtime)
864{
865 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
866 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 if (tstate == NULL)
868 Py_FatalError(
869 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner0fd2c302019-06-04 03:15:09 +0200870 tstate_delete_common(runtime, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200871 if (gilstate->autoInterpreterState &&
872 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600873 {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200874 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600875 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200876 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000878}
Guido van Rossum29757862001-01-23 01:46:06 +0000879
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200880void
881PyThreadState_DeleteCurrent()
882{
883 _PyThreadState_DeleteCurrent(&_PyRuntime);
884}
885
Guido van Rossum29757862001-01-23 01:46:06 +0000886
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200887/*
888 * Delete all thread states except the one passed as argument.
889 * Note that, if there is a current thread state, it *must* be the one
890 * passed as argument. Also, this won't touch any other interpreters
891 * than the current one, since we don't know which thread state should
Miss Islington (bot)4bd1d052019-08-30 13:42:54 -0700892 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200893 */
894void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200895_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200896{
897 PyInterpreterState *interp = tstate->interp;
898 PyThreadState *p, *next, *garbage;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200899 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200900 /* Remove all thread states, except tstate, from the linked list of
901 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200902 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200903 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200904 if (garbage == tstate)
905 garbage = tstate->next;
906 if (tstate->prev)
907 tstate->prev->next = tstate->next;
908 if (tstate->next)
909 tstate->next->prev = tstate->prev;
910 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200911 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200912 HEAD_UNLOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200913 /* Clear and deallocate all stale thread states. Even if this
914 executes Python code, we should be safe since it executes
915 in the current thread, not one of the stale threads. */
916 for (p = garbage; p; p = next) {
917 next = p->next;
918 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200919 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200920 }
921}
922
923
Guido van Rossuma027efa1997-05-05 20:56:21 +0000924PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100925_PyThreadState_UncheckedGet(void)
926{
Victor Stinner50b48572018-11-01 01:51:40 +0100927 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100928}
929
930
931PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000932PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000933{
Victor Stinner50b48572018-11-01 01:51:40 +0100934 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 if (tstate == NULL)
936 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000939}
940
941
Victor Stinner09532fe2019-05-10 23:39:09 +0200942PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200943_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000944{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200945 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000946
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200947 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 /* It should not be possible for more than one thread state
949 to be used for a thread. Check this the best we can in debug
950 builds.
951 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200952#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 if (newts) {
954 /* This can be called from PyEval_RestoreThread(). Similar
955 to it, we need to ensure errno doesn't change.
956 */
957 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200958 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 if (check && check->interp == newts->interp && check != newts)
960 Py_FatalError("Invalid thread state for this thread");
961 errno = err;
962 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000963#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000965}
Guido van Rossumede04391998-04-10 20:18:25 +0000966
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200967PyThreadState *
968PyThreadState_Swap(PyThreadState *newts)
969{
970 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
971}
972
Guido van Rossumede04391998-04-10 20:18:25 +0000973/* An extension mechanism to store arbitrary additional per-thread state.
974 PyThreadState_GetDict() returns a dictionary that can be used to hold such
975 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000976 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
977 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000978
979PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000980PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000981{
Victor Stinner50b48572018-11-01 01:51:40 +0100982 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 if (tstate == NULL)
984 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (tstate->dict == NULL) {
987 PyObject *d;
988 tstate->dict = d = PyDict_New();
989 if (d == NULL)
990 PyErr_Clear();
991 }
992 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000993}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000994
995
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000996/* Asynchronously raise an exception in a thread.
997 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000998 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000999 to call this, or use ctypes. Must be called with the GIL held.
1000 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1001 match any known thread id). Can be called with exc=NULL to clear an
1002 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001003
1004int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001005PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1006{
Victor Stinner09532fe2019-05-10 23:39:09 +02001007 _PyRuntimeState *runtime = &_PyRuntime;
1008 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001009
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 /* Although the GIL is held, a few C API functions can be called
1011 * without the GIL held, and in particular some that create and
1012 * destroy thread and interpreter states. Those can mutate the
1013 * list of thread states we're traversing, so to prevent that we lock
1014 * head_mutex for the duration.
1015 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001016 HEAD_LOCK(runtime);
Victor Stinner09532fe2019-05-10 23:39:09 +02001017 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 if (p->thread_id == id) {
1019 /* Tricky: we need to decref the current value
1020 * (if any) in p->async_exc, but that can in turn
1021 * allow arbitrary Python code to run, including
1022 * perhaps calls to this function. To prevent
1023 * deadlock, we need to release head_mutex before
1024 * the decref.
1025 */
1026 PyObject *old_exc = p->async_exc;
1027 Py_XINCREF(exc);
1028 p->async_exc = exc;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001029 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001030 Py_XDECREF(old_exc);
Victor Stinnere225beb2019-06-03 18:14:24 +02001031 _PyEval_SignalAsyncExc(&runtime->ceval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 return 1;
1033 }
1034 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001035 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001037}
1038
1039
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001040/* Routines for advanced debuggers, requested by David Beazley.
1041 Don't use unless you know what you are doing! */
1042
1043PyInterpreterState *
1044PyInterpreterState_Head(void)
1045{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001046 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001047}
1048
1049PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001050PyInterpreterState_Main(void)
1051{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001052 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001053}
1054
1055PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001056PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001058}
1059
1060PyThreadState *
1061PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001063}
1064
1065PyThreadState *
1066PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001068}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001069
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001070/* The implementation of sys._current_frames(). This is intended to be
1071 called with the GIL held, as it will be when called via
1072 sys._current_frames(). It's possible it would work fine even without
1073 the GIL held, but haven't thought enough about that.
1074*/
1075PyObject *
1076_PyThread_CurrentFrames(void)
1077{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 PyObject *result;
1079 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001080
Steve Dowerb82e17e2019-05-23 08:45:22 -07001081 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1082 return NULL;
1083 }
1084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 result = PyDict_New();
1086 if (result == NULL)
1087 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 /* for i in all interpreters:
1090 * for t in all of i's thread states:
1091 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001092 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093 * need to grab head_mutex for the duration.
1094 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001095 _PyRuntimeState *runtime = &_PyRuntime;
1096 HEAD_LOCK(runtime);
1097 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyThreadState *t;
1099 for (t = i->tstate_head; t != NULL; t = t->next) {
1100 PyObject *id;
1101 int stat;
1102 struct _frame *frame = t->frame;
1103 if (frame == NULL)
1104 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001105 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 if (id == NULL)
1107 goto Fail;
1108 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1109 Py_DECREF(id);
1110 if (stat < 0)
1111 goto Fail;
1112 }
1113 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001114 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001116
1117 Fail:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001118 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 Py_DECREF(result);
1120 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001121}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001122
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001123/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001124
1125/* Keep this as a static, as it is not reliable! It can only
1126 ever be compared to the state for the *current* thread.
1127 * If not equal, then it doesn't matter that the actual
1128 value may change immediately after comparison, as it can't
1129 possibly change to the current thread's state.
1130 * If equal, then the current thread holds the lock, so the value can't
1131 change until we yield the lock.
1132*/
1133static int
1134PyThreadState_IsCurrent(PyThreadState *tstate)
1135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001137 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001138 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1139 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001140}
1141
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001142/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001143 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001144*/
Tim Peters19717fa2004-10-09 17:38:29 +00001145void
Victor Stinner0fd2c302019-06-04 03:15:09 +02001146_PyGILState_Init(_PyRuntimeState *runtime,
1147 PyInterpreterState *interp, PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001148{
Victor Stinner8bb32302019-04-24 16:47:40 +02001149 /* must init with valid states */
Eric Snow396e0a82019-05-31 21:16:47 -06001150 assert(interp != NULL);
Victor Stinner0fd2c302019-06-04 03:15:09 +02001151 assert(tstate != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001152
Victor Stinner8bb32302019-04-24 16:47:40 +02001153 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1154
1155 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001156 Py_FatalError("Could not allocate TSS entry");
1157 }
Victor Stinner8bb32302019-04-24 16:47:40 +02001158 gilstate->autoInterpreterState = interp;
1159 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1160 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001161
Victor Stinner8bb32302019-04-24 16:47:40 +02001162 _PyGILState_NoteThreadState(gilstate, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001163}
1164
Victor Stinner861d9ab2016-03-16 22:45:24 +01001165PyInterpreterState *
1166_PyGILState_GetInterpreterStateUnsafe(void)
1167{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001168 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001169}
1170
Tim Peters19717fa2004-10-09 17:38:29 +00001171void
Victor Stinner8e91c242019-04-24 17:24:01 +02001172_PyGILState_Fini(_PyRuntimeState *runtime)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001173{
Victor Stinner8e91c242019-04-24 17:24:01 +02001174 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1175 PyThread_tss_delete(&gilstate->autoTSSkey);
1176 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001177}
1178
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001179/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001180 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001181 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001182 */
1183void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001184_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001185{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001186 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001187 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001188
1189 PyThread_tss_delete(&gilstate->autoTSSkey);
1190 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001191 Py_FatalError("Could not allocate TSS entry");
1192 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001193
Charles-François Natalia233df82011-11-22 19:49:51 +01001194 /* If the thread had an associated auto thread state, reassociate it with
1195 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001196 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001197 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001198 {
1199 Py_FatalError("Couldn't create autoTSSkey mapping");
1200 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001201}
1202
Michael W. Hudson188d4362005-06-20 16:52:57 +00001203/* When a thread state is created for a thread by some mechanism other than
1204 PyGILState_Ensure, it's important that the GILState machinery knows about
1205 it so it doesn't try to create another thread state for the thread (this is
1206 a better fix for SF bug #1010677 than the first one attempted).
1207*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001208static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001209_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001210{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001211 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001212 threadstate created in Py_Initialize(). Don't do anything for now
1213 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001214 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001216 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001217
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001218 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 The only situation where you can legitimately have more than one
1221 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001222 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001223
Victor Stinner590cebe2013-12-13 11:08:56 +01001224 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1225 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001226
Victor Stinner590cebe2013-12-13 11:08:56 +01001227 The first thread state created for that given OS level thread will
1228 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001230 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1231 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001232 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001233 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001234 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 /* PyGILState_Release must not try to delete this thread state. */
1237 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001238}
1239
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001240/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001241static PyThreadState *
1242_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1243{
1244 if (gilstate->autoInterpreterState == NULL)
1245 return NULL;
1246 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1247}
1248
Tim Peters19717fa2004-10-09 17:38:29 +00001249PyThreadState *
1250PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001251{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001252 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001253}
1254
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001255int
1256PyGILState_Check(void)
1257{
Victor Stinner8a1be612016-03-14 22:07:55 +01001258
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001259 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001260 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001261 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001262
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001263 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1264 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1265 return 1;
1266 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001267
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001268 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1269 if (tstate == NULL) {
1270 return 0;
1271 }
1272
1273 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001274}
1275
Tim Peters19717fa2004-10-09 17:38:29 +00001276PyGILState_STATE
1277PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001278{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001279 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001280 int current;
1281 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001282 int need_init_threads = 0;
1283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 /* Note that we do not auto-init Python here - apart from
1285 potential races with 2 threads auto-initializing, pep-311
1286 spells out other issues. Embedders are expected to have
1287 called Py_Initialize() and usually PyEval_InitThreads().
1288 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001289 /* Py_Initialize() hasn't been called! */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001290 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001291
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001292 tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001294 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 /* Create a new thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001297 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 if (tcur == NULL)
1299 Py_FatalError("Couldn't create thread-state for new thread");
1300 /* This is our thread state! We'll need to delete it in the
1301 matching call to PyGILState_Release(). */
1302 tcur->gilstate_counter = 0;
1303 current = 0; /* new thread state is never current */
1304 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001305 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001307 }
1308
1309 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001311 }
1312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 /* Update our counter in the thread-state - no need for locks:
1314 - tcur will remain valid as we hold the GIL.
1315 - the counter is safe as we are the only thread "allowed"
1316 to modify this value
1317 */
1318 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001319
1320 if (need_init_threads) {
1321 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1322 called from a new thread for the first time, we need the create the
1323 GIL. */
1324 PyEval_InitThreads();
1325 }
1326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001328}
1329
Tim Peters19717fa2004-10-09 17:38:29 +00001330void
1331PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001332{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001333 _PyRuntimeState *runtime = &_PyRuntime;
1334 PyThreadState *tcur = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1335 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 Py_FatalError("auto-releasing thread-state, "
1337 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001338 }
1339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 /* We must hold the GIL and have our thread state current */
1341 /* XXX - remove the check - the assert should be fine,
1342 but while this is very new (April 2003), the extra check
1343 by release-only users can't hurt.
1344 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001345 if (!PyThreadState_IsCurrent(tcur)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 Py_FatalError("This thread state must be current when releasing");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001347 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 assert(PyThreadState_IsCurrent(tcur));
1349 --tcur->gilstate_counter;
1350 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 /* If we're going to destroy this thread-state, we must
1353 * clear it while the GIL is held, as destructors may run.
1354 */
1355 if (tcur->gilstate_counter == 0) {
1356 /* can't have been locked when we created it */
1357 assert(oldstate == PyGILState_UNLOCKED);
1358 PyThreadState_Clear(tcur);
1359 /* Delete the thread-state. Note this releases the GIL too!
1360 * It's vital that the GIL be held here, to avoid shutdown
1361 * races; see bugs 225673 and 1061968 (that nasty bug has a
1362 * habit of coming back).
1363 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001364 _PyThreadState_DeleteCurrent(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 }
1366 /* Release the lock if necessary */
1367 else if (oldstate == PyGILState_UNLOCKED)
1368 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001369}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001370
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001371
Eric Snow7f8bfc92018-01-29 18:23:44 -07001372/**************************/
1373/* cross-interpreter data */
1374/**************************/
1375
1376/* cross-interpreter data */
1377
1378crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1379
1380/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1381 to keep the registry code separate. */
1382static crossinterpdatafunc
1383_lookup_getdata(PyObject *obj)
1384{
1385 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1386 if (getdata == NULL && PyErr_Occurred() == 0)
1387 PyErr_Format(PyExc_ValueError,
1388 "%S does not support cross-interpreter data", obj);
1389 return getdata;
1390}
1391
1392int
1393_PyObject_CheckCrossInterpreterData(PyObject *obj)
1394{
1395 crossinterpdatafunc getdata = _lookup_getdata(obj);
1396 if (getdata == NULL) {
1397 return -1;
1398 }
1399 return 0;
1400}
1401
1402static int
1403_check_xidata(_PyCrossInterpreterData *data)
1404{
1405 // data->data can be anything, including NULL, so we don't check it.
1406
1407 // data->obj may be NULL, so we don't check it.
1408
1409 if (data->interp < 0) {
1410 PyErr_SetString(PyExc_SystemError, "missing interp");
1411 return -1;
1412 }
1413
1414 if (data->new_object == NULL) {
1415 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1416 return -1;
1417 }
1418
1419 // data->free may be NULL, so we don't check it.
1420
1421 return 0;
1422}
1423
1424int
1425_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1426{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001427 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001428 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001429 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001430
1431 // Reset data before re-populating.
1432 *data = (_PyCrossInterpreterData){0};
1433 data->free = PyMem_RawFree; // Set a default that may be overridden.
1434
1435 // Call the "getdata" func for the object.
1436 Py_INCREF(obj);
1437 crossinterpdatafunc getdata = _lookup_getdata(obj);
1438 if (getdata == NULL) {
1439 Py_DECREF(obj);
1440 return -1;
1441 }
1442 int res = getdata(obj, data);
1443 Py_DECREF(obj);
1444 if (res != 0) {
1445 return -1;
1446 }
1447
1448 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001449 data->interp = interp->id;
1450 if (_check_xidata(data) != 0) {
1451 _PyCrossInterpreterData_Release(data);
1452 return -1;
1453 }
1454
1455 return 0;
1456}
1457
Victor Stinnere225beb2019-06-03 18:14:24 +02001458static void
Eric Snow63799132018-06-01 18:45:20 -06001459_release_xidata(void *arg)
1460{
1461 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1462 if (data->free != NULL) {
1463 data->free(data->data);
1464 }
1465 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001466}
1467
1468static void
1469_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1470 PyInterpreterState *interp,
1471 void (*func)(void *), void *arg)
1472{
1473 /* We would use Py_AddPendingCall() if it weren't specific to the
1474 * main interpreter (see bpo-33608). In the meantime we take a
1475 * naive approach.
1476 */
1477 PyThreadState *save_tstate = NULL;
1478 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1479 // XXX Using the "head" thread isn't strictly correct.
1480 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1481 // XXX Possible GILState issues?
1482 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1483 }
1484
1485 func(arg);
1486
1487 // Switch back.
1488 if (save_tstate != NULL) {
1489 _PyThreadState_Swap(gilstate, save_tstate);
1490 }
Eric Snow63799132018-06-01 18:45:20 -06001491}
1492
Eric Snow7f8bfc92018-01-29 18:23:44 -07001493void
1494_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1495{
1496 if (data->data == NULL && data->obj == NULL) {
1497 // Nothing to release!
1498 return;
1499 }
1500
Victor Stinnere225beb2019-06-03 18:14:24 +02001501 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001502 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1503 if (interp == NULL) {
1504 // The intepreter was already destroyed.
1505 if (data->free != NULL) {
1506 // XXX Someone leaked some memory...
1507 }
1508 return;
1509 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001510
Eric Snow7f8bfc92018-01-29 18:23:44 -07001511 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001512 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1513 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001514}
1515
1516PyObject *
1517_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1518{
1519 return data->new_object(data);
1520}
1521
1522/* registry of {type -> crossinterpdatafunc} */
1523
1524/* For now we use a global registry of shareable classes. An
1525 alternative would be to add a tp_* slot for a class's
1526 crossinterpdatafunc. It would be simpler and more efficient. */
1527
1528static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001529_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1530 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001531{
1532 // Note that we effectively replace already registered classes
1533 // rather than failing.
1534 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1535 if (newhead == NULL)
1536 return -1;
1537 newhead->cls = cls;
1538 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001539 newhead->next = xidregistry->head;
1540 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001541 return 0;
1542}
1543
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001544static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001545
1546int
Eric Snowc11183c2019-03-15 16:35:46 -06001547_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001548 crossinterpdatafunc getdata)
1549{
1550 if (!PyType_Check(cls)) {
1551 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1552 return -1;
1553 }
1554 if (getdata == NULL) {
1555 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1556 return -1;
1557 }
1558
1559 // Make sure the class isn't ever deallocated.
1560 Py_INCREF((PyObject *)cls);
1561
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001562 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1563 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1564 if (xidregistry->head == NULL) {
1565 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001566 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001567 int res = _register_xidata(xidregistry, cls, getdata);
1568 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001569 return res;
1570}
1571
Eric Snow6d2cd902018-05-16 15:04:57 -04001572/* Cross-interpreter objects are looked up by exact match on the class.
1573 We can reassess this policy when we move from a global registry to a
1574 tp_* slot. */
1575
Eric Snow7f8bfc92018-01-29 18:23:44 -07001576crossinterpdatafunc
1577_PyCrossInterpreterData_Lookup(PyObject *obj)
1578{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001579 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001580 PyObject *cls = PyObject_Type(obj);
1581 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001582 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1583 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001584 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001585 _register_builtins_for_crossinterpreter_data(xidregistry);
1586 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001587 }
1588 for(; cur != NULL; cur = cur->next) {
1589 if (cur->cls == (PyTypeObject *)cls) {
1590 getdata = cur->getdata;
1591 break;
1592 }
1593 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001594 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001595 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001596 return getdata;
1597}
1598
1599/* cross-interpreter data for builtin types */
1600
Eric Snow6d2cd902018-05-16 15:04:57 -04001601struct _shared_bytes_data {
1602 char *bytes;
1603 Py_ssize_t len;
1604};
1605
Eric Snow7f8bfc92018-01-29 18:23:44 -07001606static PyObject *
1607_new_bytes_object(_PyCrossInterpreterData *data)
1608{
Eric Snow6d2cd902018-05-16 15:04:57 -04001609 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1610 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001611}
1612
1613static int
1614_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1615{
Eric Snow6d2cd902018-05-16 15:04:57 -04001616 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1617 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1618 return -1;
1619 }
1620 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001621 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001622 data->obj = obj; // Will be "released" (decref'ed) when data released.
1623 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001624 data->free = PyMem_Free;
1625 return 0;
1626}
1627
1628struct _shared_str_data {
1629 int kind;
1630 const void *buffer;
1631 Py_ssize_t len;
1632};
1633
1634static PyObject *
1635_new_str_object(_PyCrossInterpreterData *data)
1636{
1637 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1638 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1639}
1640
1641static int
1642_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1643{
1644 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1645 shared->kind = PyUnicode_KIND(obj);
1646 shared->buffer = PyUnicode_DATA(obj);
1647 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1648 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001649 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001650 data->obj = obj; // Will be "released" (decref'ed) when data released.
1651 data->new_object = _new_str_object;
1652 data->free = PyMem_Free;
1653 return 0;
1654}
1655
1656static PyObject *
1657_new_long_object(_PyCrossInterpreterData *data)
1658{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001659 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001660}
1661
1662static int
1663_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1664{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001665 /* Note that this means the size of shareable ints is bounded by
1666 * sys.maxsize. Hence on 32-bit architectures that is half the
1667 * size of maximum shareable ints on 64-bit.
1668 */
1669 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001670 if (value == -1 && PyErr_Occurred()) {
1671 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1672 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1673 }
1674 return -1;
1675 }
1676 data->data = (void *)value;
1677 data->obj = NULL;
1678 data->new_object = _new_long_object;
1679 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001680 return 0;
1681}
1682
1683static PyObject *
1684_new_none_object(_PyCrossInterpreterData *data)
1685{
1686 // XXX Singleton refcounts are problematic across interpreters...
1687 Py_INCREF(Py_None);
1688 return Py_None;
1689}
1690
1691static int
1692_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1693{
1694 data->data = NULL;
1695 // data->obj remains NULL
1696 data->new_object = _new_none_object;
1697 data->free = NULL; // There is nothing to free.
1698 return 0;
1699}
1700
1701static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001702_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001703{
1704 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001705 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001706 Py_FatalError("could not register None for cross-interpreter sharing");
1707 }
1708
Eric Snow6d2cd902018-05-16 15:04:57 -04001709 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001710 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001711 Py_FatalError("could not register int for cross-interpreter sharing");
1712 }
1713
Eric Snow7f8bfc92018-01-29 18:23:44 -07001714 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001715 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001716 Py_FatalError("could not register bytes for cross-interpreter sharing");
1717 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001718
1719 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001720 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001721 Py_FatalError("could not register str for cross-interpreter sharing");
1722 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001723}
1724
1725
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001726#ifdef __cplusplus
1727}
1728#endif