blob: 41c66223390d054af2b5952d50916eaa19ab8b73 [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 Stinnerf684d832019-03-01 03:44:13 +01006#include "pycore_coreconfig.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);
42static void _PyThreadState_Delete(_PyRuntimeState *runtime, PyThreadState *tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +020043
44
Victor Stinner5d39e042017-11-29 17:20:38 +010045static _PyInitError
46_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 Stinner022be022019-05-22 23:58:50 +020063 _PyPreConfig_InitPythonConfig(&runtime->preconfig);
Michael W. Hudson188d4362005-06-20 16:52:57 +000064
Eric Snow2ebc5ce2017-09-07 23:51:28 -060065 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080066
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090067 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
68 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080069 Py_tss_t initial = Py_tss_NEEDS_INIT;
70 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000071
Eric Snow2ebc5ce2017-09-07 23:51:28 -060072 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080073 if (runtime->interpreters.mutex == NULL) {
74 return _Py_INIT_ERR("Can't initialize threads for interpreter");
75 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060076 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070077
78 runtime->xidregistry.mutex = PyThread_allocate_lock();
79 if (runtime->xidregistry.mutex == NULL) {
80 return _Py_INIT_ERR("Can't initialize threads for cross-interpreter data registry");
81 }
82
Eric Snow8479a342019-03-08 23:44:33 -070083 // Set it to the ID of the main thread of the main interpreter.
84 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070085
Victor Stinnerf7e5b562017-11-15 15:48:08 -080086 return _Py_INIT_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060087}
Eric Snow05351c12017-09-05 21:43:08 -070088
Victor Stinner5d39e042017-11-29 17:20:38 +010089_PyInitError
90_PyRuntimeState_Init(_PyRuntimeState *runtime)
91{
92 /* Force default allocator, since _PyRuntimeState_Fini() must
93 use the same allocator than this function. */
94 PyMemAllocatorEx old_alloc;
95 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
96
97 _PyInitError err = _PyRuntimeState_Init_impl(runtime);
98
99 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
100 return err;
101}
102
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600103void
104_PyRuntimeState_Fini(_PyRuntimeState *runtime)
105{
Victor Stinner5d39e042017-11-29 17:20:38 +0100106 /* Force the allocator used by _PyRuntimeState_Init(). */
107 PyMemAllocatorEx old_alloc;
108 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -0800109
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600110 if (runtime->interpreters.mutex != NULL) {
111 PyThread_free_lock(runtime->interpreters.mutex);
112 runtime->interpreters.mutex = NULL;
113 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800114
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100115 if (runtime->xidregistry.mutex != NULL) {
116 PyThread_free_lock(runtime->xidregistry.mutex);
117 runtime->xidregistry.mutex = NULL;
118 }
119
Victor Stinnerccb04422017-11-16 03:20:31 -0800120 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600121}
122
Eric Snow8479a342019-03-08 23:44:33 -0700123/* This function is called from PyOS_AfterFork_Child to ensure that
124 * newly created child processes do not share locks with the parent.
125 */
126
127void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200128_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700129{
130 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200131 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700132
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200133 /* Force default allocator, since _PyRuntimeState_Fini() must
134 use the same allocator than this function. */
135 PyMemAllocatorEx old_alloc;
136 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
137
138 runtime->interpreters.mutex = PyThread_allocate_lock();
139 runtime->interpreters.main->id_mutex = PyThread_allocate_lock();
140 runtime->xidregistry.mutex = PyThread_allocate_lock();
141
142 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
143
144 if (runtime->interpreters.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700145 Py_FatalError("Can't initialize lock for runtime interpreters");
146 }
147
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200148 if (runtime->interpreters.main->id_mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700149 Py_FatalError("Can't initialize ID lock for main interpreter");
150 }
151
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200152 if (runtime->xidregistry.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700153 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
154 }
155}
156
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200157#define HEAD_LOCK(runtime) \
158 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
159#define HEAD_UNLOCK(runtime) \
160 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700161
Victor Stinner8bb32302019-04-24 16:47:40 +0200162/* Forward declaration */
163static void _PyGILState_NoteThreadState(
164 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000165
Victor Stinnera7368ac2017-11-15 18:11:45 -0800166_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600167_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700168{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200169 struct pyinterpreters *interpreters = &runtime->interpreters;
170 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100171
172 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
173 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200174 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100175 /* Force default allocator, since _PyRuntimeState_Fini() must
176 use the same allocator than this function. */
177 PyMemAllocatorEx old_alloc;
178 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
179
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200180 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100181
182 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
183
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200184 if (interpreters->mutex == NULL) {
Victor Stinnera7368ac2017-11-15 18:11:45 -0800185 return _Py_INIT_ERR("Can't initialize threads for interpreter");
186 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600187 }
Victor Stinner5d926472018-03-06 14:31:37 +0100188
Victor Stinnera7368ac2017-11-15 18:11:45 -0800189 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700190}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000191
192PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000193PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000194{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700195 if (PySys_Audit("cpython.PyInterpreterState_New", NULL) < 0) {
196 return NULL;
197 }
198
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200199 PyInterpreterState *interp = PyMem_RawMalloc(sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100200 if (interp == NULL) {
201 return NULL;
202 }
203
Eric Snow5be45a62019-03-08 22:47:07 -0700204 memset(interp, 0, sizeof(*interp));
Eric Snow4c6955e2018-02-16 18:53:40 -0700205 interp->id_refcount = -1;
Victor Stinnerd4341102017-11-23 00:12:09 +0100206 interp->check_interval = 100;
Victor Stinner022be022019-05-22 23:58:50 +0200207
208 _PyInitError err = _PyCoreConfig_InitPythonConfig(&interp->core_config);
209 if (_Py_INIT_FAILED(err)) {
210 PyMem_RawFree(interp);
211 return NULL;
212 }
213
Victor Stinnerd4341102017-11-23 00:12:09 +0100214 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000215#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300216#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100217 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000218#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100219 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000220#endif
221#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000222
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200223 _PyRuntimeState *runtime = &_PyRuntime;
224 struct pyinterpreters *interpreters = &runtime->interpreters;
225
226 HEAD_LOCK(runtime);
227 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100228 /* overflow or Py_Initialize() not called! */
229 PyErr_SetString(PyExc_RuntimeError,
230 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100231 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100232 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100233 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200234 else {
235 interp->id = interpreters->next_id;
236 interpreters->next_id += 1;
237 interp->next = interpreters->head;
238 if (interpreters->main == NULL) {
239 interpreters->main = interp;
240 }
241 interpreters->head = interp;
242 }
243 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000244
Pablo Galindo95d630e2018-08-31 22:49:29 +0100245 if (interp == NULL) {
246 return NULL;
247 }
248
Yury Selivanovf23746a2018-01-22 19:11:18 -0500249 interp->tstate_next_unique_id = 0;
250
Steve Dowerb82e17e2019-05-23 08:45:22 -0700251 interp->audit_hooks = NULL;
252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000254}
255
256
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200257static void
258_PyInterpreterState_Clear(_PyRuntimeState *runtime, PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000259{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700260 if (PySys_Audit("cpython.PyInterpreterState_Clear", NULL) < 0) {
261 PyErr_Clear();
262 }
263
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200264 HEAD_LOCK(runtime);
265 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200267 }
268 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700269
270 Py_CLEAR(interp->audit_hooks);
271
Victor Stinnerda273412017-12-15 01:46:02 +0100272 _PyCoreConfig_Clear(&interp->core_config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 Py_CLEAR(interp->codec_search_path);
274 Py_CLEAR(interp->codec_search_cache);
275 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700276 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 Py_CLEAR(interp->sysdict);
279 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200280 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400281 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300282 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600283 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200284#ifdef HAVE_FORK
285 Py_CLEAR(interp->before_forkers);
286 Py_CLEAR(interp->after_forkers_parent);
287 Py_CLEAR(interp->after_forkers_child);
288#endif
Eric Snow86ea5812019-05-10 13:29:55 -0400289 if (runtime->finalizing == NULL) {
290 _PyWarnings_Fini(interp);
291 }
Eric Snow5be45a62019-03-08 22:47:07 -0700292 // XXX Once we have one allocator per interpreter (i.e.
293 // per-interpreter GC) we must ensure that all of the interpreter's
294 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000295}
296
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200297void
298PyInterpreterState_Clear(PyInterpreterState *interp)
299{
300 _PyInterpreterState_Clear(&_PyRuntime, interp);
301}
302
Guido van Rossum25ce5661997-08-02 03:10:38 +0000303
304static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200305zapthreads(_PyRuntimeState *runtime, PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 PyThreadState *p;
308 /* No need to lock the mutex here because this should only happen
309 when the threads are all really dead (XXX famous last words). */
310 while ((p = interp->tstate_head) != NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200311 _PyThreadState_Delete(runtime, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000313}
314
315
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200316static void
317_PyInterpreterState_Delete(_PyRuntimeState *runtime,
318 PyInterpreterState *interp)
319{
320 struct pyinterpreters *interpreters = &runtime->interpreters;
321 zapthreads(runtime, interp);
322 HEAD_LOCK(runtime);
323 PyInterpreterState **p;
324 for (p = &interpreters->head; ; p = &(*p)->next) {
325 if (*p == NULL) {
326 Py_FatalError("PyInterpreterState_Delete: invalid interp");
327 }
328 if (*p == interp) {
329 break;
330 }
331 }
332 if (interp->tstate_head != NULL) {
333 Py_FatalError("PyInterpreterState_Delete: remaining threads");
334 }
335 *p = interp->next;
336 if (interpreters->main == interp) {
337 interpreters->main = NULL;
338 if (interpreters->head != NULL) {
339 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
340 }
341 }
342 HEAD_UNLOCK(runtime);
343 if (interp->id_mutex != NULL) {
344 PyThread_free_lock(interp->id_mutex);
345 }
346 PyMem_RawFree(interp);
347}
348
349
Guido van Rossum25ce5661997-08-02 03:10:38 +0000350void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000351PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000352{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200353 _PyInterpreterState_Delete(&_PyRuntime, interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000354}
355
356
Eric Snow59032962018-09-14 14:17:20 -0700357/*
358 * Delete all interpreter states except the main interpreter. If there
359 * is a current interpreter state, it *must* be the main interpreter.
360 */
361void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200362_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700363{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200364 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200365 struct pyinterpreters *interpreters = &runtime->interpreters;
366
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200367 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200368 if (tstate != NULL && tstate->interp != interpreters->main) {
Eric Snow59032962018-09-14 14:17:20 -0700369 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
370 }
371
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200372 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200373 PyInterpreterState *interp = interpreters->head;
374 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100375 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200376 if (interp == interpreters->main) {
377 interpreters->main->next = NULL;
378 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100379 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700380 continue;
381 }
382
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200383 _PyInterpreterState_Clear(runtime, interp); // XXX must activate?
384 zapthreads(runtime, interp);
Eric Snow59032962018-09-14 14:17:20 -0700385 if (interp->id_mutex != NULL) {
386 PyThread_free_lock(interp->id_mutex);
387 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100388 PyInterpreterState *prev_interp = interp;
389 interp = interp->next;
390 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700391 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200392 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700393
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200394 if (interpreters->head == NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700395 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
396 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200397 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700398}
399
400
Victor Stinnercaba55b2018-08-03 15:33:52 +0200401PyInterpreterState *
402_PyInterpreterState_Get(void)
403{
Victor Stinner50b48572018-11-01 01:51:40 +0100404 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200405 if (tstate == NULL) {
406 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
407 }
408 PyInterpreterState *interp = tstate->interp;
409 if (interp == NULL) {
410 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
411 }
412 return interp;
413}
414
415
Eric Snowe3774162017-05-22 19:46:40 -0700416int64_t
417PyInterpreterState_GetID(PyInterpreterState *interp)
418{
419 if (interp == NULL) {
420 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
421 return -1;
422 }
423 return interp->id;
424}
425
426
Eric Snow5be45a62019-03-08 22:47:07 -0700427static PyInterpreterState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200428interp_look_up_id(_PyRuntimeState *runtime, PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700429{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200430 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100431 while (interp != NULL) {
432 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700433 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100434 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700435 }
436 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100437 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700438 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100439 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700440 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100441 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700442}
443
Eric Snow5be45a62019-03-08 22:47:07 -0700444PyInterpreterState *
445_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
446{
447 PyInterpreterState *interp = NULL;
448 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200449 _PyRuntimeState *runtime = &_PyRuntime;
450 HEAD_LOCK(runtime);
451 interp = interp_look_up_id(runtime, requested_id);
452 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700453 }
454 if (interp == NULL && !PyErr_Occurred()) {
455 PyErr_Format(PyExc_RuntimeError,
456 "unrecognized interpreter ID %lld", requested_id);
457 }
458 return interp;
459}
460
Eric Snow4c6955e2018-02-16 18:53:40 -0700461
462int
463_PyInterpreterState_IDInitref(PyInterpreterState *interp)
464{
465 if (interp->id_mutex != NULL) {
466 return 0;
467 }
468 interp->id_mutex = PyThread_allocate_lock();
469 if (interp->id_mutex == NULL) {
470 PyErr_SetString(PyExc_RuntimeError,
471 "failed to create init interpreter ID mutex");
472 return -1;
473 }
474 interp->id_refcount = 0;
475 return 0;
476}
477
478
479void
480_PyInterpreterState_IDIncref(PyInterpreterState *interp)
481{
482 if (interp->id_mutex == NULL) {
483 return;
484 }
485 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
486 interp->id_refcount += 1;
487 PyThread_release_lock(interp->id_mutex);
488}
489
490
491void
492_PyInterpreterState_IDDecref(PyInterpreterState *interp)
493{
494 if (interp->id_mutex == NULL) {
495 return;
496 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200497 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700498 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
499 assert(interp->id_refcount != 0);
500 interp->id_refcount -= 1;
501 int64_t refcount = interp->id_refcount;
502 PyThread_release_lock(interp->id_mutex);
503
Eric Snowc11183c2019-03-15 16:35:46 -0600504 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700505 // XXX Using the "head" thread isn't strictly correct.
506 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
507 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200508 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700509 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200510 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700511 }
512}
513
Eric Snowc11183c2019-03-15 16:35:46 -0600514int
515_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
516{
517 return interp->requires_idref;
518}
519
520void
521_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
522{
523 interp->requires_idref = required ? 1 : 0;
524}
525
Eric Snowbe3b2952019-02-23 11:35:52 -0700526_PyCoreConfig *
527_PyInterpreterState_GetCoreConfig(PyInterpreterState *interp)
528{
529 return &interp->core_config;
530}
531
Eric Snowc11183c2019-03-15 16:35:46 -0600532PyObject *
533_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
534{
535 if (interp->modules == NULL) {
536 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
537 return NULL;
538 }
539 return PyMapping_GetItemString(interp->modules, "__main__");
540}
541
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600542PyObject *
543PyInterpreterState_GetDict(PyInterpreterState *interp)
544{
545 if (interp->dict == NULL) {
546 interp->dict = PyDict_New();
547 if (interp->dict == NULL) {
548 PyErr_Clear();
549 }
550 }
551 /* Returning NULL means no per-interpreter dict is available. */
552 return interp->dict;
553}
554
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000555/* Default implementation for _PyThreadState_GetFrame */
556static struct _frame *
557threadstate_getframe(PyThreadState *self)
558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000560}
561
Victor Stinner45b9be52010-03-03 23:28:07 +0000562static PyThreadState *
563new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000564{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200565 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200566 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200567 if (tstate == NULL) {
568 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000570
Victor Stinner8bb32302019-04-24 16:47:40 +0200571 if (_PyThreadState_GetFrame == NULL) {
572 _PyThreadState_GetFrame = threadstate_getframe;
573 }
574
575 tstate->interp = interp;
576
577 tstate->frame = NULL;
578 tstate->recursion_depth = 0;
579 tstate->overflowed = 0;
580 tstate->recursion_critical = 0;
581 tstate->stackcheck_counter = 0;
582 tstate->tracing = 0;
583 tstate->use_tracing = 0;
584 tstate->gilstate_counter = 0;
585 tstate->async_exc = NULL;
586 tstate->thread_id = PyThread_get_thread_ident();
587
588 tstate->dict = NULL;
589
590 tstate->curexc_type = NULL;
591 tstate->curexc_value = NULL;
592 tstate->curexc_traceback = NULL;
593
594 tstate->exc_state.exc_type = NULL;
595 tstate->exc_state.exc_value = NULL;
596 tstate->exc_state.exc_traceback = NULL;
597 tstate->exc_state.previous_item = NULL;
598 tstate->exc_info = &tstate->exc_state;
599
600 tstate->c_profilefunc = NULL;
601 tstate->c_tracefunc = NULL;
602 tstate->c_profileobj = NULL;
603 tstate->c_traceobj = NULL;
604
605 tstate->trash_delete_nesting = 0;
606 tstate->trash_delete_later = NULL;
607 tstate->on_delete = NULL;
608 tstate->on_delete_data = NULL;
609
610 tstate->coroutine_origin_tracking_depth = 0;
611
612 tstate->coroutine_wrapper = NULL;
613 tstate->in_coroutine_wrapper = 0;
614
615 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 Stinner10c8e6a2019-04-26 01:53:18 +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 Stinner8bb32302019-04-24 16:47:40 +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 }
694 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
695 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;
712 if (state->modules_by_index) {
713 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
714 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
715 Py_FatalError("PyState_AddModule: Module already added!");
716 return -1;
717 }
718 }
719 }
720 return _PyState_AddModule(module, def);
721}
722
723int
724PyState_RemoveModule(struct PyModuleDef* def)
725{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000726 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200727 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000728 if (def->m_slots) {
729 PyErr_SetString(PyExc_SystemError,
730 "PyState_RemoveModule called on module with slots");
731 return -1;
732 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100733 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200734 if (index == 0) {
735 Py_FatalError("PyState_RemoveModule: Module index invalid.");
736 return -1;
737 }
738 if (state->modules_by_index == NULL) {
739 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
740 return -1;
741 }
742 if (index > PyList_GET_SIZE(state->modules_by_index)) {
743 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
744 return -1;
745 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700746 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200747 return PyList_SetItem(state->modules_by_index, index, Py_None);
748}
749
Antoine Pitrou40322e62013-08-11 00:30:09 +0200750/* used by import.c:PyImport_Cleanup */
751void
752_PyState_ClearModules(void)
753{
Victor Stinner9204fb82018-10-30 15:13:17 +0100754 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200755 if (state->modules_by_index) {
756 Py_ssize_t i;
757 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
758 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
759 if (PyModule_Check(m)) {
760 /* cleanup the saved copy of module dicts */
761 PyModuleDef *md = PyModule_GetDef(m);
762 if (md)
763 Py_CLEAR(md->m_base.m_copy);
764 }
765 }
766 /* Setting modules_by_index to NULL could be dangerous, so we
767 clear the list instead. */
768 if (PyList_SetSlice(state->modules_by_index,
769 0, PyList_GET_SIZE(state->modules_by_index),
770 NULL))
771 PyErr_WriteUnraisable(state->modules_by_index);
772 }
773}
774
Guido van Rossuma027efa1997-05-05 20:56:21 +0000775void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000776PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000777{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200778 int verbose = tstate->interp->core_config.verbose;
779
780 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 fprintf(stderr,
782 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 Py_CLEAR(tstate->dict);
787 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 Py_CLEAR(tstate->curexc_type);
790 Py_CLEAR(tstate->curexc_value);
791 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000792
Mark Shannonae3087c2017-10-22 22:41:51 +0100793 Py_CLEAR(tstate->exc_state.exc_type);
794 Py_CLEAR(tstate->exc_state.exc_value);
795 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300796
Mark Shannonae3087c2017-10-22 22:41:51 +0100797 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200798 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100799 fprintf(stderr,
800 "PyThreadState_Clear: warning: thread still has a generator\n");
801 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 tstate->c_profilefunc = NULL;
804 tstate->c_tracefunc = NULL;
805 Py_CLEAR(tstate->c_profileobj);
806 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400807
808 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700809 Py_CLEAR(tstate->async_gen_firstiter);
810 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500811
812 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000813}
814
815
Guido van Rossum29757862001-01-23 01:46:06 +0000816/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
817static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200818tstate_delete_common(_PyRuntimeState *runtime, PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000819{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200820 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 Py_FatalError("PyThreadState_Delete: NULL tstate");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200822 }
823 PyInterpreterState *interp = tstate->interp;
824 if (interp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 Py_FatalError("PyThreadState_Delete: NULL interp");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200826 }
827 HEAD_LOCK(runtime);
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200828 if (tstate->prev)
829 tstate->prev->next = tstate->next;
830 else
831 interp->tstate_head = tstate->next;
832 if (tstate->next)
833 tstate->next->prev = tstate->prev;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200834 HEAD_UNLOCK(runtime);
Antoine Pitrou7b476992013-09-07 23:38:37 +0200835 if (tstate->on_delete != NULL) {
836 tstate->on_delete(tstate->on_delete_data);
837 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200838 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000839}
840
841
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200842static void
843_PyThreadState_Delete(_PyRuntimeState *runtime, PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000844{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200845 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
846 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600848 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200849 if (gilstate->autoInterpreterState &&
850 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
851 {
852 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
853 }
854 tstate_delete_common(runtime, tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000855}
856
857
Guido van Rossum29757862001-01-23 01:46:06 +0000858void
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200859PyThreadState_Delete(PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000860{
Victor Stinner99e69d42019-04-26 05:48:51 +0200861 _PyThreadState_Delete(&_PyRuntime, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200862}
863
864
865static void
866_PyThreadState_DeleteCurrent(_PyRuntimeState *runtime)
867{
868 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
869 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 if (tstate == NULL)
871 Py_FatalError(
872 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200873 tstate_delete_common(runtime, tstate);
874 if (gilstate->autoInterpreterState &&
875 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600876 {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200877 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600878 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200879 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000881}
Guido van Rossum29757862001-01-23 01:46:06 +0000882
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200883void
884PyThreadState_DeleteCurrent()
885{
886 _PyThreadState_DeleteCurrent(&_PyRuntime);
887}
888
Guido van Rossum29757862001-01-23 01:46:06 +0000889
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200890/*
891 * Delete all thread states except the one passed as argument.
892 * Note that, if there is a current thread state, it *must* be the one
893 * passed as argument. Also, this won't touch any other interpreters
894 * than the current one, since we don't know which thread state should
895 * be kept in those other interpreteres.
896 */
897void
Victor Stinner09532fe2019-05-10 23:39:09 +0200898_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200899{
900 PyInterpreterState *interp = tstate->interp;
901 PyThreadState *p, *next, *garbage;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200902 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200903 /* Remove all thread states, except tstate, from the linked list of
904 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200905 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200906 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200907 if (garbage == tstate)
908 garbage = tstate->next;
909 if (tstate->prev)
910 tstate->prev->next = tstate->next;
911 if (tstate->next)
912 tstate->next->prev = tstate->prev;
913 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200914 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200915 HEAD_UNLOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200916 /* Clear and deallocate all stale thread states. Even if this
917 executes Python code, we should be safe since it executes
918 in the current thread, not one of the stale threads. */
919 for (p = garbage; p; p = next) {
920 next = p->next;
921 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200922 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200923 }
924}
925
926
Guido van Rossuma027efa1997-05-05 20:56:21 +0000927PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100928_PyThreadState_UncheckedGet(void)
929{
Victor Stinner50b48572018-11-01 01:51:40 +0100930 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100931}
932
933
934PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000935PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000936{
Victor Stinner50b48572018-11-01 01:51:40 +0100937 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 if (tstate == NULL)
939 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000942}
943
944
Victor Stinner09532fe2019-05-10 23:39:09 +0200945PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200946_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000947{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200948 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000949
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200950 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 /* It should not be possible for more than one thread state
952 to be used for a thread. Check this the best we can in debug
953 builds.
954 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200955#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 if (newts) {
957 /* This can be called from PyEval_RestoreThread(). Similar
958 to it, we need to ensure errno doesn't change.
959 */
960 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200961 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 if (check && check->interp == newts->interp && check != newts)
963 Py_FatalError("Invalid thread state for this thread");
964 errno = err;
965 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000966#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000968}
Guido van Rossumede04391998-04-10 20:18:25 +0000969
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200970PyThreadState *
971PyThreadState_Swap(PyThreadState *newts)
972{
973 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
974}
975
Guido van Rossumede04391998-04-10 20:18:25 +0000976/* An extension mechanism to store arbitrary additional per-thread state.
977 PyThreadState_GetDict() returns a dictionary that can be used to hold such
978 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000979 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
980 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000981
982PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000983PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000984{
Victor Stinner50b48572018-11-01 01:51:40 +0100985 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 if (tstate == NULL)
987 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 if (tstate->dict == NULL) {
990 PyObject *d;
991 tstate->dict = d = PyDict_New();
992 if (d == NULL)
993 PyErr_Clear();
994 }
995 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000996}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000997
998
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000999/* Asynchronously raise an exception in a thread.
1000 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +00001001 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001002 to call this, or use ctypes. Must be called with the GIL held.
1003 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
1004 match any known thread id). Can be called with exc=NULL to clear an
1005 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001006
1007int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001008PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
1009{
Victor Stinner09532fe2019-05-10 23:39:09 +02001010 _PyRuntimeState *runtime = &_PyRuntime;
1011 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 /* Although the GIL is held, a few C API functions can be called
1014 * without the GIL held, and in particular some that create and
1015 * destroy thread and interpreter states. Those can mutate the
1016 * list of thread states we're traversing, so to prevent that we lock
1017 * head_mutex for the duration.
1018 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001019 HEAD_LOCK(runtime);
Victor Stinner09532fe2019-05-10 23:39:09 +02001020 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 if (p->thread_id == id) {
1022 /* Tricky: we need to decref the current value
1023 * (if any) in p->async_exc, but that can in turn
1024 * allow arbitrary Python code to run, including
1025 * perhaps calls to this function. To prevent
1026 * deadlock, we need to release head_mutex before
1027 * the decref.
1028 */
1029 PyObject *old_exc = p->async_exc;
1030 Py_XINCREF(exc);
1031 p->async_exc = exc;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001032 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 Py_XDECREF(old_exc);
Victor Stinner09532fe2019-05-10 23:39:09 +02001034 _PyEval_SignalAsyncExc(&runtime->ceval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 return 1;
1036 }
1037 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001038 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001040}
1041
1042
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001043/* Routines for advanced debuggers, requested by David Beazley.
1044 Don't use unless you know what you are doing! */
1045
1046PyInterpreterState *
1047PyInterpreterState_Head(void)
1048{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001049 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001050}
1051
1052PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001053PyInterpreterState_Main(void)
1054{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001055 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001056}
1057
1058PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001059PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001061}
1062
1063PyThreadState *
1064PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001066}
1067
1068PyThreadState *
1069PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001071}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001072
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001073/* The implementation of sys._current_frames(). This is intended to be
1074 called with the GIL held, as it will be when called via
1075 sys._current_frames(). It's possible it would work fine even without
1076 the GIL held, but haven't thought enough about that.
1077*/
1078PyObject *
1079_PyThread_CurrentFrames(void)
1080{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 PyObject *result;
1082 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001083
Steve Dowerb82e17e2019-05-23 08:45:22 -07001084 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1085 return NULL;
1086 }
1087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 result = PyDict_New();
1089 if (result == NULL)
1090 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 /* for i in all interpreters:
1093 * for t in all of i's thread states:
1094 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001095 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 * need to grab head_mutex for the duration.
1097 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001098 _PyRuntimeState *runtime = &_PyRuntime;
1099 HEAD_LOCK(runtime);
1100 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 PyThreadState *t;
1102 for (t = i->tstate_head; t != NULL; t = t->next) {
1103 PyObject *id;
1104 int stat;
1105 struct _frame *frame = t->frame;
1106 if (frame == NULL)
1107 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001108 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 if (id == NULL)
1110 goto Fail;
1111 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1112 Py_DECREF(id);
1113 if (stat < 0)
1114 goto Fail;
1115 }
1116 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001117 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001119
1120 Fail:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001121 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 Py_DECREF(result);
1123 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001124}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001125
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001126/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001127
1128/* Keep this as a static, as it is not reliable! It can only
1129 ever be compared to the state for the *current* thread.
1130 * If not equal, then it doesn't matter that the actual
1131 value may change immediately after comparison, as it can't
1132 possibly change to the current thread's state.
1133 * If equal, then the current thread holds the lock, so the value can't
1134 change until we yield the lock.
1135*/
1136static int
1137PyThreadState_IsCurrent(PyThreadState *tstate)
1138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 /* Must be the tstate for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001140 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1141 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1142 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001143}
1144
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001145/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001146 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001147*/
Tim Peters19717fa2004-10-09 17:38:29 +00001148void
Victor Stinner43125222019-04-24 18:23:53 +02001149_PyGILState_Init(_PyRuntimeState *runtime,
1150 PyInterpreterState *interp, PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001151{
Victor Stinner8bb32302019-04-24 16:47:40 +02001152 /* must init with valid states */
1153 assert(interp != NULL);
1154 assert(tstate != NULL);
1155
Victor Stinner8bb32302019-04-24 16:47:40 +02001156 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1157
1158 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001159 Py_FatalError("Could not allocate TSS entry");
1160 }
Victor Stinner8bb32302019-04-24 16:47:40 +02001161 gilstate->autoInterpreterState = interp;
1162 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1163 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001164
Victor Stinner8bb32302019-04-24 16:47:40 +02001165 _PyGILState_NoteThreadState(gilstate, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001166}
1167
Victor Stinner861d9ab2016-03-16 22:45:24 +01001168PyInterpreterState *
1169_PyGILState_GetInterpreterStateUnsafe(void)
1170{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001171 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001172}
1173
Tim Peters19717fa2004-10-09 17:38:29 +00001174void
Victor Stinner8e91c242019-04-24 17:24:01 +02001175_PyGILState_Fini(_PyRuntimeState *runtime)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001176{
Victor Stinner8e91c242019-04-24 17:24:01 +02001177 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1178 PyThread_tss_delete(&gilstate->autoTSSkey);
1179 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001180}
1181
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001182/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001183 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001184 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001185 */
1186void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001187_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001188{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001189 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001190 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001191
1192 PyThread_tss_delete(&gilstate->autoTSSkey);
1193 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001194 Py_FatalError("Could not allocate TSS entry");
1195 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001196
Charles-François Natalia233df82011-11-22 19:49:51 +01001197 /* If the thread had an associated auto thread state, reassociate it with
1198 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001199 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001200 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001201 {
1202 Py_FatalError("Couldn't create autoTSSkey mapping");
1203 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001204}
1205
Michael W. Hudson188d4362005-06-20 16:52:57 +00001206/* When a thread state is created for a thread by some mechanism other than
1207 PyGILState_Ensure, it's important that the GILState machinery knows about
1208 it so it doesn't try to create another thread state for the thread (this is
1209 a better fix for SF bug #1010677 than the first one attempted).
1210*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001211static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001212_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001213{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001214 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001215 threadstate created in Py_Initialize(). Don't do anything for now
1216 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001217 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001219 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001220
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001221 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001222
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 The only situation where you can legitimately have more than one
1224 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001225 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001226
Victor Stinner590cebe2013-12-13 11:08:56 +01001227 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1228 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001229
Victor Stinner590cebe2013-12-13 11:08:56 +01001230 The first thread state created for that given OS level thread will
1231 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001233 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1234 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001235 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001236 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001237 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 /* PyGILState_Release must not try to delete this thread state. */
1240 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001241}
1242
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001243/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001244static PyThreadState *
1245_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1246{
1247 if (gilstate->autoInterpreterState == NULL)
1248 return NULL;
1249 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1250}
1251
Tim Peters19717fa2004-10-09 17:38:29 +00001252PyThreadState *
1253PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001254{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001255 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001256}
1257
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001258int
1259PyGILState_Check(void)
1260{
Victor Stinner8a1be612016-03-14 22:07:55 +01001261
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001262 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001263 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001264 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001265
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001266 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1267 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1268 return 1;
1269 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001270
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001271 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1272 if (tstate == NULL) {
1273 return 0;
1274 }
1275
1276 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001277}
1278
Tim Peters19717fa2004-10-09 17:38:29 +00001279PyGILState_STATE
1280PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001281{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001282 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 int current;
1284 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001285 int need_init_threads = 0;
1286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 /* Note that we do not auto-init Python here - apart from
1288 potential races with 2 threads auto-initializing, pep-311
1289 spells out other issues. Embedders are expected to have
1290 called Py_Initialize() and usually PyEval_InitThreads().
1291 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001292 /* Py_Initialize() hasn't been called! */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001293 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001294
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001295 tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001297 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 /* Create a new thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001300 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 if (tcur == NULL)
1302 Py_FatalError("Couldn't create thread-state for new thread");
1303 /* This is our thread state! We'll need to delete it in the
1304 matching call to PyGILState_Release(). */
1305 tcur->gilstate_counter = 0;
1306 current = 0; /* new thread state is never current */
1307 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001308 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001310 }
1311
1312 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001314 }
1315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001316 /* Update our counter in the thread-state - no need for locks:
1317 - tcur will remain valid as we hold the GIL.
1318 - the counter is safe as we are the only thread "allowed"
1319 to modify this value
1320 */
1321 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001322
1323 if (need_init_threads) {
1324 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1325 called from a new thread for the first time, we need the create the
1326 GIL. */
1327 PyEval_InitThreads();
1328 }
1329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001331}
1332
Tim Peters19717fa2004-10-09 17:38:29 +00001333void
1334PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001335{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001336 _PyRuntimeState *runtime = &_PyRuntime;
1337 PyThreadState *tcur = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1338 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 Py_FatalError("auto-releasing thread-state, "
1340 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001341 }
1342
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 /* We must hold the GIL and have our thread state current */
1344 /* XXX - remove the check - the assert should be fine,
1345 but while this is very new (April 2003), the extra check
1346 by release-only users can't hurt.
1347 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001348 if (!PyThreadState_IsCurrent(tcur)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 Py_FatalError("This thread state must be current when releasing");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001350 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 assert(PyThreadState_IsCurrent(tcur));
1352 --tcur->gilstate_counter;
1353 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 /* If we're going to destroy this thread-state, we must
1356 * clear it while the GIL is held, as destructors may run.
1357 */
1358 if (tcur->gilstate_counter == 0) {
1359 /* can't have been locked when we created it */
1360 assert(oldstate == PyGILState_UNLOCKED);
1361 PyThreadState_Clear(tcur);
1362 /* Delete the thread-state. Note this releases the GIL too!
1363 * It's vital that the GIL be held here, to avoid shutdown
1364 * races; see bugs 225673 and 1061968 (that nasty bug has a
1365 * habit of coming back).
1366 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001367 _PyThreadState_DeleteCurrent(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 }
1369 /* Release the lock if necessary */
1370 else if (oldstate == PyGILState_UNLOCKED)
1371 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001372}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001373
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001374
Eric Snow7f8bfc92018-01-29 18:23:44 -07001375/**************************/
1376/* cross-interpreter data */
1377/**************************/
1378
1379/* cross-interpreter data */
1380
1381crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1382
1383/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1384 to keep the registry code separate. */
1385static crossinterpdatafunc
1386_lookup_getdata(PyObject *obj)
1387{
1388 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1389 if (getdata == NULL && PyErr_Occurred() == 0)
1390 PyErr_Format(PyExc_ValueError,
1391 "%S does not support cross-interpreter data", obj);
1392 return getdata;
1393}
1394
1395int
1396_PyObject_CheckCrossInterpreterData(PyObject *obj)
1397{
1398 crossinterpdatafunc getdata = _lookup_getdata(obj);
1399 if (getdata == NULL) {
1400 return -1;
1401 }
1402 return 0;
1403}
1404
1405static int
1406_check_xidata(_PyCrossInterpreterData *data)
1407{
1408 // data->data can be anything, including NULL, so we don't check it.
1409
1410 // data->obj may be NULL, so we don't check it.
1411
1412 if (data->interp < 0) {
1413 PyErr_SetString(PyExc_SystemError, "missing interp");
1414 return -1;
1415 }
1416
1417 if (data->new_object == NULL) {
1418 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1419 return -1;
1420 }
1421
1422 // data->free may be NULL, so we don't check it.
1423
1424 return 0;
1425}
1426
1427int
1428_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1429{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001430 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001431 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001432 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001433
1434 // Reset data before re-populating.
1435 *data = (_PyCrossInterpreterData){0};
1436 data->free = PyMem_RawFree; // Set a default that may be overridden.
1437
1438 // Call the "getdata" func for the object.
1439 Py_INCREF(obj);
1440 crossinterpdatafunc getdata = _lookup_getdata(obj);
1441 if (getdata == NULL) {
1442 Py_DECREF(obj);
1443 return -1;
1444 }
1445 int res = getdata(obj, data);
1446 Py_DECREF(obj);
1447 if (res != 0) {
1448 return -1;
1449 }
1450
1451 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001452 data->interp = interp->id;
1453 if (_check_xidata(data) != 0) {
1454 _PyCrossInterpreterData_Release(data);
1455 return -1;
1456 }
1457
1458 return 0;
1459}
1460
Eric Snowb75b1a352019-04-12 10:20:10 -06001461static void
Eric Snow63799132018-06-01 18:45:20 -06001462_release_xidata(void *arg)
1463{
1464 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1465 if (data->free != NULL) {
1466 data->free(data->data);
1467 }
1468 Py_XDECREF(data->obj);
Eric Snowb75b1a352019-04-12 10:20:10 -06001469}
1470
1471static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001472_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1473 PyInterpreterState *interp,
Eric Snowb75b1a352019-04-12 10:20:10 -06001474 void (*func)(void *), void *arg)
1475{
1476 /* We would use Py_AddPendingCall() if it weren't specific to the
1477 * main interpreter (see bpo-33608). In the meantime we take a
1478 * naive approach.
1479 */
1480 PyThreadState *save_tstate = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001481 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
Eric Snowb75b1a352019-04-12 10:20:10 -06001482 // XXX Using the "head" thread isn't strictly correct.
1483 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1484 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001485 save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snowb75b1a352019-04-12 10:20:10 -06001486 }
1487
1488 func(arg);
1489
1490 // Switch back.
1491 if (save_tstate != NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001492 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snowb75b1a352019-04-12 10:20:10 -06001493 }
Eric Snow63799132018-06-01 18:45:20 -06001494}
1495
Eric Snow7f8bfc92018-01-29 18:23:44 -07001496void
1497_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1498{
1499 if (data->data == NULL && data->obj == NULL) {
1500 // Nothing to release!
1501 return;
1502 }
1503
Eric Snowb75b1a352019-04-12 10:20:10 -06001504 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001505 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1506 if (interp == NULL) {
1507 // The intepreter was already destroyed.
1508 if (data->free != NULL) {
1509 // XXX Someone leaked some memory...
1510 }
1511 return;
1512 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001513
Eric Snow7f8bfc92018-01-29 18:23:44 -07001514 // "Release" the data and/or the object.
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001515 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1516 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001517}
1518
1519PyObject *
1520_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1521{
1522 return data->new_object(data);
1523}
1524
1525/* registry of {type -> crossinterpdatafunc} */
1526
1527/* For now we use a global registry of shareable classes. An
1528 alternative would be to add a tp_* slot for a class's
1529 crossinterpdatafunc. It would be simpler and more efficient. */
1530
1531static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001532_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1533 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001534{
1535 // Note that we effectively replace already registered classes
1536 // rather than failing.
1537 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1538 if (newhead == NULL)
1539 return -1;
1540 newhead->cls = cls;
1541 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001542 newhead->next = xidregistry->head;
1543 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001544 return 0;
1545}
1546
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001547static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001548
1549int
Eric Snowc11183c2019-03-15 16:35:46 -06001550_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001551 crossinterpdatafunc getdata)
1552{
1553 if (!PyType_Check(cls)) {
1554 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1555 return -1;
1556 }
1557 if (getdata == NULL) {
1558 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1559 return -1;
1560 }
1561
1562 // Make sure the class isn't ever deallocated.
1563 Py_INCREF((PyObject *)cls);
1564
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001565 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1566 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1567 if (xidregistry->head == NULL) {
1568 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001569 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001570 int res = _register_xidata(xidregistry, cls, getdata);
1571 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001572 return res;
1573}
1574
Eric Snow6d2cd902018-05-16 15:04:57 -04001575/* Cross-interpreter objects are looked up by exact match on the class.
1576 We can reassess this policy when we move from a global registry to a
1577 tp_* slot. */
1578
Eric Snow7f8bfc92018-01-29 18:23:44 -07001579crossinterpdatafunc
1580_PyCrossInterpreterData_Lookup(PyObject *obj)
1581{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001582 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001583 PyObject *cls = PyObject_Type(obj);
1584 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001585 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1586 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001587 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001588 _register_builtins_for_crossinterpreter_data(xidregistry);
1589 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001590 }
1591 for(; cur != NULL; cur = cur->next) {
1592 if (cur->cls == (PyTypeObject *)cls) {
1593 getdata = cur->getdata;
1594 break;
1595 }
1596 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001597 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001598 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001599 return getdata;
1600}
1601
1602/* cross-interpreter data for builtin types */
1603
Eric Snow6d2cd902018-05-16 15:04:57 -04001604struct _shared_bytes_data {
1605 char *bytes;
1606 Py_ssize_t len;
1607};
1608
Eric Snow7f8bfc92018-01-29 18:23:44 -07001609static PyObject *
1610_new_bytes_object(_PyCrossInterpreterData *data)
1611{
Eric Snow6d2cd902018-05-16 15:04:57 -04001612 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1613 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001614}
1615
1616static int
1617_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1618{
Eric Snow6d2cd902018-05-16 15:04:57 -04001619 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1620 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1621 return -1;
1622 }
1623 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001624 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001625 data->obj = obj; // Will be "released" (decref'ed) when data released.
1626 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001627 data->free = PyMem_Free;
1628 return 0;
1629}
1630
1631struct _shared_str_data {
1632 int kind;
1633 const void *buffer;
1634 Py_ssize_t len;
1635};
1636
1637static PyObject *
1638_new_str_object(_PyCrossInterpreterData *data)
1639{
1640 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1641 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1642}
1643
1644static int
1645_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1646{
1647 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1648 shared->kind = PyUnicode_KIND(obj);
1649 shared->buffer = PyUnicode_DATA(obj);
1650 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1651 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001652 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001653 data->obj = obj; // Will be "released" (decref'ed) when data released.
1654 data->new_object = _new_str_object;
1655 data->free = PyMem_Free;
1656 return 0;
1657}
1658
1659static PyObject *
1660_new_long_object(_PyCrossInterpreterData *data)
1661{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001662 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001663}
1664
1665static int
1666_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1667{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001668 /* Note that this means the size of shareable ints is bounded by
1669 * sys.maxsize. Hence on 32-bit architectures that is half the
1670 * size of maximum shareable ints on 64-bit.
1671 */
1672 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001673 if (value == -1 && PyErr_Occurred()) {
1674 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1675 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1676 }
1677 return -1;
1678 }
1679 data->data = (void *)value;
1680 data->obj = NULL;
1681 data->new_object = _new_long_object;
1682 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001683 return 0;
1684}
1685
1686static PyObject *
1687_new_none_object(_PyCrossInterpreterData *data)
1688{
1689 // XXX Singleton refcounts are problematic across interpreters...
1690 Py_INCREF(Py_None);
1691 return Py_None;
1692}
1693
1694static int
1695_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1696{
1697 data->data = NULL;
1698 // data->obj remains NULL
1699 data->new_object = _new_none_object;
1700 data->free = NULL; // There is nothing to free.
1701 return 0;
1702}
1703
1704static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001705_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001706{
1707 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001708 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001709 Py_FatalError("could not register None for cross-interpreter sharing");
1710 }
1711
Eric Snow6d2cd902018-05-16 15:04:57 -04001712 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001713 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001714 Py_FatalError("could not register int for cross-interpreter sharing");
1715 }
1716
Eric Snow7f8bfc92018-01-29 18:23:44 -07001717 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001718 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001719 Py_FatalError("could not register bytes for cross-interpreter sharing");
1720 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001721
1722 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001723 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001724 Py_FatalError("could not register str for cross-interpreter sharing");
1725 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001726}
1727
1728
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001729#ifdef __cplusplus
1730}
1731#endif