blob: aba673c00a432233d38700718e3d5797b8b45a5a [file] [log] [blame]
Guido van Rossuma027efa1997-05-05 20:56:21 +00001
2/* Thread and interpreter state structures and their interfaces */
3
4#include "Python.h"
Victor Stinner09532fe2019-05-10 23:39:09 +02005#include "pycore_ceval.h"
Victor Stinner331a6a52019-05-27 16:39:22 +02006#include "pycore_initconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01007#include "pycore_pymem.h"
8#include "pycore_pystate.h"
Eric Snow86ea5812019-05-10 13:29:55 -04009#include "pycore_pylifecycle.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +000010
Tim Peters84705582004-10-10 02:47:33 +000011/* --------------------------------------------------------------------------
12CAUTION
13
Victor Stinner1a7425f2013-07-07 16:25:15 +020014Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
15number of these functions are advertised as safe to call when the GIL isn't
16held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
17debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
18to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000019-------------------------------------------------------------------------- */
20
Martin v. Löwisf0473d52001-07-18 16:17:16 +000021#ifdef HAVE_DLOPEN
22#ifdef HAVE_DLFCN_H
23#include <dlfcn.h>
24#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030025#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000026#define RTLD_LAZY 1
27#endif
28#endif
29
Benjamin Peterson43162b82012-04-13 11:58:27 -040030#ifdef __cplusplus
31extern "C" {
32#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000033
Victor Stinner10c8e6a2019-04-26 01:53:18 +020034#define _PyRuntimeGILState_GetThreadState(gilstate) \
35 ((PyThreadState*)_Py_atomic_load_relaxed(&(gilstate)->tstate_current))
36#define _PyRuntimeGILState_SetThreadState(gilstate, value) \
37 _Py_atomic_store_relaxed(&(gilstate)->tstate_current, \
38 (uintptr_t)(value))
39
40/* Forward declarations */
41static PyThreadState *_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate);
Victor Stinner0fd2c302019-06-04 03:15:09 +020042static void _PyThreadState_Delete(_PyRuntimeState *runtime, PyThreadState *tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +020043
44
Victor Stinner331a6a52019-05-27 16:39:22 +020045static PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010046_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060047{
Steve Dowerb82e17e2019-05-23 08:45:22 -070048 /* We preserve the hook across init, because there is
49 currently no public API to set it between runtime
50 initialization and interpreter initialization. */
51 void *open_code_hook = runtime->open_code_hook;
52 void *open_code_userdata = runtime->open_code_userdata;
53 _Py_AuditHookEntry *audit_hook_head = runtime->audit_hook_head;
54
Eric Snow2ebc5ce2017-09-07 23:51:28 -060055 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010056
Steve Dowerb82e17e2019-05-23 08:45:22 -070057 runtime->open_code_hook = open_code_hook;
58 runtime->open_code_userdata = open_code_userdata;
59 runtime->audit_hook_head = audit_hook_head;
60
Eric Snow2ebc5ce2017-09-07 23:51:28 -060061 _PyGC_Initialize(&runtime->gc);
62 _PyEval_Initialize(&runtime->ceval);
Victor Stinner6e128382019-09-28 04:50:43 +020063
Victor Stinnerbdace212019-10-01 00:46:42 +020064 PyPreConfig_InitPythonConfig(&runtime->preconfig);
Michael W. Hudson188d4362005-06-20 16:52:57 +000065
Eric Snow2ebc5ce2017-09-07 23:51:28 -060066 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080067
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090068 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
69 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080070 Py_tss_t initial = Py_tss_NEEDS_INIT;
71 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000072
Eric Snow2ebc5ce2017-09-07 23:51:28 -060073 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080074 if (runtime->interpreters.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020075 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnerf7e5b562017-11-15 15:48:08 -080076 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060077 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070078
79 runtime->xidregistry.mutex = PyThread_allocate_lock();
80 if (runtime->xidregistry.mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +020081 return _PyStatus_ERR("Can't initialize threads for cross-interpreter data registry");
Eric Snow7f8bfc92018-01-29 18:23:44 -070082 }
83
Eric Snow8479a342019-03-08 23:44:33 -070084 // Set it to the ID of the main thread of the main interpreter.
85 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070086
Victor Stinner331a6a52019-05-27 16:39:22 +020087 return _PyStatus_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060088}
Eric Snow05351c12017-09-05 21:43:08 -070089
Victor Stinner331a6a52019-05-27 16:39:22 +020090PyStatus
Victor Stinner5d39e042017-11-29 17:20:38 +010091_PyRuntimeState_Init(_PyRuntimeState *runtime)
92{
93 /* Force default allocator, since _PyRuntimeState_Fini() must
94 use the same allocator than this function. */
95 PyMemAllocatorEx old_alloc;
96 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
97
Victor Stinner331a6a52019-05-27 16:39:22 +020098 PyStatus status = _PyRuntimeState_Init_impl(runtime);
Victor Stinner5d39e042017-11-29 17:20:38 +010099
100 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinner331a6a52019-05-27 16:39:22 +0200101 return status;
Victor Stinner5d39e042017-11-29 17:20:38 +0100102}
103
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600104void
105_PyRuntimeState_Fini(_PyRuntimeState *runtime)
106{
Victor Stinner5d39e042017-11-29 17:20:38 +0100107 /* Force the allocator used by _PyRuntimeState_Init(). */
108 PyMemAllocatorEx old_alloc;
109 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -0800110
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600111 if (runtime->interpreters.mutex != NULL) {
112 PyThread_free_lock(runtime->interpreters.mutex);
113 runtime->interpreters.mutex = NULL;
114 }
Victor Stinnerccb04422017-11-16 03:20:31 -0800115
Stéphane Wirtel943395f2019-03-19 11:51:32 +0100116 if (runtime->xidregistry.mutex != NULL) {
117 PyThread_free_lock(runtime->xidregistry.mutex);
118 runtime->xidregistry.mutex = NULL;
119 }
120
Victor Stinnerccb04422017-11-16 03:20:31 -0800121 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600122}
123
Eric Snow8479a342019-03-08 23:44:33 -0700124/* This function is called from PyOS_AfterFork_Child to ensure that
125 * newly created child processes do not share locks with the parent.
126 */
127
128void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200129_PyRuntimeState_ReInitThreads(_PyRuntimeState *runtime)
Eric Snow8479a342019-03-08 23:44:33 -0700130{
131 // This was initially set in _PyRuntimeState_Init().
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200132 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow8479a342019-03-08 23:44:33 -0700133
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200134 /* Force default allocator, since _PyRuntimeState_Fini() must
135 use the same allocator than this function. */
136 PyMemAllocatorEx old_alloc;
137 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
138
139 runtime->interpreters.mutex = PyThread_allocate_lock();
140 runtime->interpreters.main->id_mutex = PyThread_allocate_lock();
141 runtime->xidregistry.mutex = PyThread_allocate_lock();
142
143 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
144
145 if (runtime->interpreters.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700146 Py_FatalError("Can't initialize lock for runtime interpreters");
147 }
148
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200149 if (runtime->interpreters.main->id_mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700150 Py_FatalError("Can't initialize ID lock for main interpreter");
151 }
152
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200153 if (runtime->xidregistry.mutex == NULL) {
Eric Snow8479a342019-03-08 23:44:33 -0700154 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
155 }
156}
157
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200158#define HEAD_LOCK(runtime) \
159 PyThread_acquire_lock((runtime)->interpreters.mutex, WAIT_LOCK)
160#define HEAD_UNLOCK(runtime) \
161 PyThread_release_lock((runtime)->interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700162
Victor Stinner8bb32302019-04-24 16:47:40 +0200163/* Forward declaration */
164static void _PyGILState_NoteThreadState(
165 struct _gilstate_runtime_state *gilstate, PyThreadState* tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000166
Victor Stinner331a6a52019-05-27 16:39:22 +0200167PyStatus
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600168_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700169{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200170 struct pyinterpreters *interpreters = &runtime->interpreters;
171 interpreters->next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100172
173 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
174 Create a new mutex if needed. */
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200175 if (interpreters->mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100176 /* Force default allocator, since _PyRuntimeState_Fini() must
177 use the same allocator than this function. */
178 PyMemAllocatorEx old_alloc;
179 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
180
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200181 interpreters->mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100182
183 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
184
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200185 if (interpreters->mutex == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +0200186 return _PyStatus_ERR("Can't initialize threads for interpreter");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800187 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600188 }
Victor Stinner5d926472018-03-06 14:31:37 +0100189
Victor Stinner331a6a52019-05-27 16:39:22 +0200190 return _PyStatus_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700191}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000192
193PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000194PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000195{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700196 if (PySys_Audit("cpython.PyInterpreterState_New", NULL) < 0) {
197 return NULL;
198 }
199
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200200 PyInterpreterState *interp = PyMem_RawMalloc(sizeof(PyInterpreterState));
Victor Stinnerd4341102017-11-23 00:12:09 +0100201 if (interp == NULL) {
202 return NULL;
203 }
204
Eric Snow5be45a62019-03-08 22:47:07 -0700205 memset(interp, 0, sizeof(*interp));
Eric Snow4c6955e2018-02-16 18:53:40 -0700206 interp->id_refcount = -1;
Victor Stinnerd4341102017-11-23 00:12:09 +0100207 interp->check_interval = 100;
Victor Stinner022be022019-05-22 23:58:50 +0200208
Miss Islington (bot)d49f0962019-10-01 03:26:04 -0700209 PyConfig_InitPythonConfig(&interp->config);
Victor Stinner022be022019-05-22 23:58:50 +0200210
Victor Stinnerd4341102017-11-23 00:12:09 +0100211 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000212#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300213#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100214 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000215#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100216 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000217#endif
218#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000219
Victor Stinner0fd2c302019-06-04 03:15:09 +0200220 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200221 struct pyinterpreters *interpreters = &runtime->interpreters;
222
223 HEAD_LOCK(runtime);
224 if (interpreters->next_id < 0) {
Victor Stinnerd4341102017-11-23 00:12:09 +0100225 /* overflow or Py_Initialize() not called! */
226 PyErr_SetString(PyExc_RuntimeError,
227 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100228 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100229 interp = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100230 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200231 else {
232 interp->id = interpreters->next_id;
233 interpreters->next_id += 1;
234 interp->next = interpreters->head;
235 if (interpreters->main == NULL) {
236 interpreters->main = interp;
237 }
238 interpreters->head = interp;
239 }
240 HEAD_UNLOCK(runtime);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000241
Pablo Galindo95d630e2018-08-31 22:49:29 +0100242 if (interp == NULL) {
243 return NULL;
244 }
245
Yury Selivanovf23746a2018-01-22 19:11:18 -0500246 interp->tstate_next_unique_id = 0;
247
Steve Dowerb82e17e2019-05-23 08:45:22 -0700248 interp->audit_hooks = NULL;
249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000251}
252
253
Victor Stinner0fd2c302019-06-04 03:15:09 +0200254static void
255_PyInterpreterState_Clear(_PyRuntimeState *runtime, PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000256{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700257 if (PySys_Audit("cpython.PyInterpreterState_Clear", NULL) < 0) {
258 PyErr_Clear();
259 }
260
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200261 HEAD_LOCK(runtime);
262 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 PyThreadState_Clear(p);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200264 }
265 HEAD_UNLOCK(runtime);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700266
267 Py_CLEAR(interp->audit_hooks);
268
Victor Stinner331a6a52019-05-27 16:39:22 +0200269 PyConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 Py_CLEAR(interp->codec_search_path);
271 Py_CLEAR(interp->codec_search_cache);
272 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700273 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 Py_CLEAR(interp->sysdict);
276 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200277 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400278 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300279 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600280 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200281#ifdef HAVE_FORK
282 Py_CLEAR(interp->before_forkers);
283 Py_CLEAR(interp->after_forkers_parent);
284 Py_CLEAR(interp->after_forkers_child);
285#endif
Eric Snow86ea5812019-05-10 13:29:55 -0400286 if (runtime->finalizing == NULL) {
287 _PyWarnings_Fini(interp);
288 }
Eric Snow5be45a62019-03-08 22:47:07 -0700289 // XXX Once we have one allocator per interpreter (i.e.
290 // per-interpreter GC) we must ensure that all of the interpreter's
291 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000292}
293
Victor Stinner0fd2c302019-06-04 03:15:09 +0200294void
295PyInterpreterState_Clear(PyInterpreterState *interp)
296{
297 _PyInterpreterState_Clear(&_PyRuntime, interp);
298}
299
Guido van Rossum25ce5661997-08-02 03:10:38 +0000300
301static void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200302zapthreads(_PyRuntimeState *runtime, PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000303{
Victor Stinner0fd2c302019-06-04 03:15:09 +0200304 PyThreadState *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 /* No need to lock the mutex here because this should only happen
306 when the threads are all really dead (XXX famous last words). */
Victor Stinner0fd2c302019-06-04 03:15:09 +0200307 while ((p = interp->tstate_head) != NULL) {
308 _PyThreadState_Delete(runtime, p);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000310}
311
312
Victor Stinner0fd2c302019-06-04 03:15:09 +0200313static void
314_PyInterpreterState_Delete(_PyRuntimeState *runtime,
315 PyInterpreterState *interp)
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200316{
317 struct pyinterpreters *interpreters = &runtime->interpreters;
Victor Stinner0fd2c302019-06-04 03:15:09 +0200318 zapthreads(runtime, interp);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200319 HEAD_LOCK(runtime);
320 PyInterpreterState **p;
321 for (p = &interpreters->head; ; p = &(*p)->next) {
322 if (*p == NULL) {
323 Py_FatalError("PyInterpreterState_Delete: invalid interp");
324 }
325 if (*p == interp) {
326 break;
327 }
328 }
329 if (interp->tstate_head != NULL) {
330 Py_FatalError("PyInterpreterState_Delete: remaining threads");
331 }
332 *p = interp->next;
333 if (interpreters->main == interp) {
334 interpreters->main = NULL;
335 if (interpreters->head != NULL) {
336 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
337 }
338 }
339 HEAD_UNLOCK(runtime);
340 if (interp->id_mutex != NULL) {
341 PyThread_free_lock(interp->id_mutex);
342 }
343 PyMem_RawFree(interp);
344}
345
346
Victor Stinner0fd2c302019-06-04 03:15:09 +0200347void
348PyInterpreterState_Delete(PyInterpreterState *interp)
349{
350 _PyInterpreterState_Delete(&_PyRuntime, interp);
351}
352
353
Eric Snow59032962018-09-14 14:17:20 -0700354/*
355 * Delete all interpreter states except the main interpreter. If there
356 * is a current interpreter state, it *must* be the main interpreter.
357 */
358void
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200359_PyInterpreterState_DeleteExceptMain(_PyRuntimeState *runtime)
Eric Snow59032962018-09-14 14:17:20 -0700360{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200361 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200362 struct pyinterpreters *interpreters = &runtime->interpreters;
363
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200364 PyThreadState *tstate = _PyThreadState_Swap(gilstate, NULL);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200365 if (tstate != NULL && tstate->interp != interpreters->main) {
Eric Snow59032962018-09-14 14:17:20 -0700366 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
367 }
368
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200369 HEAD_LOCK(runtime);
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200370 PyInterpreterState *interp = interpreters->head;
371 interpreters->head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100372 while (interp != NULL) {
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200373 if (interp == interpreters->main) {
374 interpreters->main->next = NULL;
375 interpreters->head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100376 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700377 continue;
378 }
379
Victor Stinner0fd2c302019-06-04 03:15:09 +0200380 _PyInterpreterState_Clear(runtime, interp); // XXX must activate?
381 zapthreads(runtime, interp);
Eric Snow59032962018-09-14 14:17:20 -0700382 if (interp->id_mutex != NULL) {
383 PyThread_free_lock(interp->id_mutex);
384 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100385 PyInterpreterState *prev_interp = interp;
386 interp = interp->next;
387 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700388 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200389 HEAD_UNLOCK(runtime);
Eric Snow59032962018-09-14 14:17:20 -0700390
Victor Stinnerb930a2d2019-04-24 17:14:33 +0200391 if (interpreters->head == NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700392 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
393 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200394 _PyThreadState_Swap(gilstate, tstate);
Eric Snow59032962018-09-14 14:17:20 -0700395}
396
397
Victor Stinnercaba55b2018-08-03 15:33:52 +0200398PyInterpreterState *
399_PyInterpreterState_Get(void)
400{
Victor Stinner50b48572018-11-01 01:51:40 +0100401 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200402 if (tstate == NULL) {
403 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
404 }
405 PyInterpreterState *interp = tstate->interp;
406 if (interp == NULL) {
407 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
408 }
409 return interp;
410}
411
412
Eric Snowe3774162017-05-22 19:46:40 -0700413int64_t
414PyInterpreterState_GetID(PyInterpreterState *interp)
415{
416 if (interp == NULL) {
417 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
418 return -1;
419 }
420 return interp->id;
421}
422
423
Eric Snow5be45a62019-03-08 22:47:07 -0700424static PyInterpreterState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200425interp_look_up_id(_PyRuntimeState *runtime, PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700426{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200427 PyInterpreterState *interp = runtime->interpreters.head;
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100428 while (interp != NULL) {
429 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700430 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100431 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700432 }
433 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100434 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700435 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100436 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700437 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100438 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700439}
440
Eric Snow5be45a62019-03-08 22:47:07 -0700441PyInterpreterState *
442_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
443{
444 PyInterpreterState *interp = NULL;
445 if (requested_id >= 0) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200446 _PyRuntimeState *runtime = &_PyRuntime;
447 HEAD_LOCK(runtime);
448 interp = interp_look_up_id(runtime, requested_id);
449 HEAD_UNLOCK(runtime);
Eric Snow5be45a62019-03-08 22:47:07 -0700450 }
451 if (interp == NULL && !PyErr_Occurred()) {
452 PyErr_Format(PyExc_RuntimeError,
453 "unrecognized interpreter ID %lld", requested_id);
454 }
455 return interp;
456}
457
Eric Snow4c6955e2018-02-16 18:53:40 -0700458
459int
460_PyInterpreterState_IDInitref(PyInterpreterState *interp)
461{
462 if (interp->id_mutex != NULL) {
463 return 0;
464 }
465 interp->id_mutex = PyThread_allocate_lock();
466 if (interp->id_mutex == NULL) {
467 PyErr_SetString(PyExc_RuntimeError,
468 "failed to create init interpreter ID mutex");
469 return -1;
470 }
471 interp->id_refcount = 0;
472 return 0;
473}
474
475
476void
477_PyInterpreterState_IDIncref(PyInterpreterState *interp)
478{
479 if (interp->id_mutex == NULL) {
480 return;
481 }
482 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
483 interp->id_refcount += 1;
484 PyThread_release_lock(interp->id_mutex);
485}
486
487
488void
489_PyInterpreterState_IDDecref(PyInterpreterState *interp)
490{
491 if (interp->id_mutex == NULL) {
492 return;
493 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200494 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Eric Snow4c6955e2018-02-16 18:53:40 -0700495 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
496 assert(interp->id_refcount != 0);
497 interp->id_refcount -= 1;
498 int64_t refcount = interp->id_refcount;
499 PyThread_release_lock(interp->id_mutex);
500
Eric Snowc11183c2019-03-15 16:35:46 -0600501 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700502 // XXX Using the "head" thread isn't strictly correct.
503 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
504 // XXX Possible GILState issues?
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200505 PyThreadState *save_tstate = _PyThreadState_Swap(gilstate, tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700506 Py_EndInterpreter(tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200507 _PyThreadState_Swap(gilstate, save_tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700508 }
509}
510
Eric Snowc11183c2019-03-15 16:35:46 -0600511int
512_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
513{
514 return interp->requires_idref;
515}
516
517void
518_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
519{
520 interp->requires_idref = required ? 1 : 0;
521}
522
Eric Snowc11183c2019-03-15 16:35:46 -0600523PyObject *
524_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
525{
526 if (interp->modules == NULL) {
527 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
528 return NULL;
529 }
530 return PyMapping_GetItemString(interp->modules, "__main__");
531}
532
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600533PyObject *
534PyInterpreterState_GetDict(PyInterpreterState *interp)
535{
536 if (interp->dict == NULL) {
537 interp->dict = PyDict_New();
538 if (interp->dict == NULL) {
539 PyErr_Clear();
540 }
541 }
542 /* Returning NULL means no per-interpreter dict is available. */
543 return interp->dict;
544}
545
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000546/* Default implementation for _PyThreadState_GetFrame */
547static struct _frame *
548threadstate_getframe(PyThreadState *self)
549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000551}
552
Victor Stinner45b9be52010-03-03 23:28:07 +0000553static PyThreadState *
554new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000555{
Victor Stinner0fd2c302019-06-04 03:15:09 +0200556 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner1a7425f2013-07-07 16:25:15 +0200557 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Victor Stinner8bb32302019-04-24 16:47:40 +0200558 if (tstate == NULL) {
559 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561
Victor Stinner8bb32302019-04-24 16:47:40 +0200562 if (_PyThreadState_GetFrame == NULL) {
563 _PyThreadState_GetFrame = threadstate_getframe;
564 }
565
566 tstate->interp = interp;
567
568 tstate->frame = NULL;
569 tstate->recursion_depth = 0;
570 tstate->overflowed = 0;
571 tstate->recursion_critical = 0;
572 tstate->stackcheck_counter = 0;
573 tstate->tracing = 0;
574 tstate->use_tracing = 0;
575 tstate->gilstate_counter = 0;
576 tstate->async_exc = NULL;
577 tstate->thread_id = PyThread_get_thread_ident();
578
579 tstate->dict = NULL;
580
581 tstate->curexc_type = NULL;
582 tstate->curexc_value = NULL;
583 tstate->curexc_traceback = NULL;
584
585 tstate->exc_state.exc_type = NULL;
586 tstate->exc_state.exc_value = NULL;
587 tstate->exc_state.exc_traceback = NULL;
588 tstate->exc_state.previous_item = NULL;
589 tstate->exc_info = &tstate->exc_state;
590
591 tstate->c_profilefunc = NULL;
592 tstate->c_tracefunc = NULL;
593 tstate->c_profileobj = NULL;
594 tstate->c_traceobj = NULL;
595
596 tstate->trash_delete_nesting = 0;
597 tstate->trash_delete_later = NULL;
598 tstate->on_delete = NULL;
599 tstate->on_delete_data = NULL;
600
601 tstate->coroutine_origin_tracking_depth = 0;
602
Victor Stinner8bb32302019-04-24 16:47:40 +0200603 tstate->async_gen_firstiter = NULL;
604 tstate->async_gen_finalizer = NULL;
605
606 tstate->context = NULL;
607 tstate->context_ver = 1;
608
609 tstate->id = ++interp->tstate_next_unique_id;
610
611 if (init) {
Victor Stinner0fd2c302019-06-04 03:15:09 +0200612 _PyThreadState_Init(runtime, tstate);
Victor Stinner8bb32302019-04-24 16:47:40 +0200613 }
614
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200615 HEAD_LOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200616 tstate->prev = NULL;
617 tstate->next = interp->tstate_head;
618 if (tstate->next)
619 tstate->next->prev = tstate;
620 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200621 HEAD_UNLOCK(runtime);
Victor Stinner8bb32302019-04-24 16:47:40 +0200622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000624}
625
Victor Stinner45b9be52010-03-03 23:28:07 +0000626PyThreadState *
627PyThreadState_New(PyInterpreterState *interp)
628{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000630}
631
632PyThreadState *
633_PyThreadState_Prealloc(PyInterpreterState *interp)
634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000636}
637
638void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200639_PyThreadState_Init(_PyRuntimeState *runtime, PyThreadState *tstate)
Victor Stinner45b9be52010-03-03 23:28:07 +0000640{
Victor Stinner8bb32302019-04-24 16:47:40 +0200641 _PyGILState_NoteThreadState(&runtime->gilstate, tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000642}
643
Martin v. Löwis1a214512008-06-11 05:26:20 +0000644PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200645PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000646{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200647 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100648 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000650 if (module->m_slots) {
651 return NULL;
652 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 if (index == 0)
654 return NULL;
655 if (state->modules_by_index == NULL)
656 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200657 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 return NULL;
659 res = PyList_GET_ITEM(state->modules_by_index, index);
660 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000661}
662
663int
664_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
665{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000666 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300667 if (!def) {
668 assert(PyErr_Occurred());
669 return -1;
670 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000671 if (def->m_slots) {
672 PyErr_SetString(PyExc_SystemError,
673 "PyState_AddModule called on module with slots");
674 return -1;
675 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100676 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 if (!state->modules_by_index) {
678 state->modules_by_index = PyList_New(0);
679 if (!state->modules_by_index)
680 return -1;
681 }
Miss Islington (bot)a5a71022019-09-11 17:04:27 -0700682 while (PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 if (PyList_Append(state->modules_by_index, Py_None) < 0)
684 return -1;
685 Py_INCREF(module);
686 return PyList_SetItem(state->modules_by_index,
687 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000688}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000689
Martin v. Löwis7800f752012-06-22 12:20:55 +0200690int
691PyState_AddModule(PyObject* module, struct PyModuleDef* def)
692{
693 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100694 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200695 if (!def) {
696 Py_FatalError("PyState_AddModule: Module Definition is NULL");
697 return -1;
698 }
699 index = def->m_base.m_index;
Miss Islington (bot)a5a71022019-09-11 17:04:27 -0700700 if (state->modules_by_index &&
701 index < PyList_GET_SIZE(state->modules_by_index) &&
702 module == PyList_GET_ITEM(state->modules_by_index, index)) {
703 Py_FatalError("PyState_AddModule: Module already added!");
704 return -1;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200705 }
706 return _PyState_AddModule(module, def);
707}
708
709int
710PyState_RemoveModule(struct PyModuleDef* def)
711{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000712 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200713 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000714 if (def->m_slots) {
715 PyErr_SetString(PyExc_SystemError,
716 "PyState_RemoveModule called on module with slots");
717 return -1;
718 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100719 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200720 if (index == 0) {
721 Py_FatalError("PyState_RemoveModule: Module index invalid.");
722 return -1;
723 }
724 if (state->modules_by_index == NULL) {
Miss Islington (bot)4bd1d052019-08-30 13:42:54 -0700725 Py_FatalError("PyState_RemoveModule: Interpreters module-list not accessible.");
Martin v. Löwis7800f752012-06-22 12:20:55 +0200726 return -1;
727 }
728 if (index > PyList_GET_SIZE(state->modules_by_index)) {
729 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
730 return -1;
731 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700732 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200733 return PyList_SetItem(state->modules_by_index, index, Py_None);
734}
735
Antoine Pitrou40322e62013-08-11 00:30:09 +0200736/* used by import.c:PyImport_Cleanup */
737void
738_PyState_ClearModules(void)
739{
Victor Stinner9204fb82018-10-30 15:13:17 +0100740 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200741 if (state->modules_by_index) {
742 Py_ssize_t i;
743 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
744 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
745 if (PyModule_Check(m)) {
746 /* cleanup the saved copy of module dicts */
747 PyModuleDef *md = PyModule_GetDef(m);
748 if (md)
749 Py_CLEAR(md->m_base.m_copy);
750 }
751 }
752 /* Setting modules_by_index to NULL could be dangerous, so we
753 clear the list instead. */
754 if (PyList_SetSlice(state->modules_by_index,
755 0, PyList_GET_SIZE(state->modules_by_index),
756 NULL))
757 PyErr_WriteUnraisable(state->modules_by_index);
758 }
759}
760
Guido van Rossuma027efa1997-05-05 20:56:21 +0000761void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000762PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000763{
Victor Stinner331a6a52019-05-27 16:39:22 +0200764 int verbose = tstate->interp->config.verbose;
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200765
766 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 fprintf(stderr,
768 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 Py_CLEAR(tstate->dict);
773 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 Py_CLEAR(tstate->curexc_type);
776 Py_CLEAR(tstate->curexc_value);
777 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000778
Mark Shannonae3087c2017-10-22 22:41:51 +0100779 Py_CLEAR(tstate->exc_state.exc_type);
780 Py_CLEAR(tstate->exc_state.exc_value);
781 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300782
Mark Shannonae3087c2017-10-22 22:41:51 +0100783 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200784 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100785 fprintf(stderr,
786 "PyThreadState_Clear: warning: thread still has a generator\n");
787 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 tstate->c_profilefunc = NULL;
790 tstate->c_tracefunc = NULL;
791 Py_CLEAR(tstate->c_profileobj);
792 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400793
Yury Selivanoveb636452016-09-08 22:01:51 -0700794 Py_CLEAR(tstate->async_gen_firstiter);
795 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500796
797 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000798}
799
800
Guido van Rossum29757862001-01-23 01:46:06 +0000801/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
802static void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200803tstate_delete_common(_PyRuntimeState *runtime, PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000804{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200805 if (tstate == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 Py_FatalError("PyThreadState_Delete: NULL tstate");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200807 }
808 PyInterpreterState *interp = tstate->interp;
809 if (interp == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 Py_FatalError("PyThreadState_Delete: NULL interp");
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200811 }
812 HEAD_LOCK(runtime);
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200813 if (tstate->prev)
814 tstate->prev->next = tstate->next;
815 else
816 interp->tstate_head = tstate->next;
817 if (tstate->next)
818 tstate->next->prev = tstate->prev;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200819 HEAD_UNLOCK(runtime);
Antoine Pitrou7b476992013-09-07 23:38:37 +0200820 if (tstate->on_delete != NULL) {
821 tstate->on_delete(tstate->on_delete_data);
822 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200823 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000824}
825
826
Victor Stinner0fd2c302019-06-04 03:15:09 +0200827static void
828_PyThreadState_Delete(_PyRuntimeState *runtime, PyThreadState *tstate)
Guido van Rossum29757862001-01-23 01:46:06 +0000829{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200830 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
831 if (tstate == _PyRuntimeGILState_GetThreadState(gilstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600833 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200834 if (gilstate->autoInterpreterState &&
835 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
836 {
837 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
838 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200839 tstate_delete_common(runtime, tstate);
840}
841
842
843void
844PyThreadState_Delete(PyThreadState *tstate)
845{
846 _PyThreadState_Delete(&_PyRuntime, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200847}
848
849
850static void
851_PyThreadState_DeleteCurrent(_PyRuntimeState *runtime)
852{
853 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
854 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 if (tstate == NULL)
856 Py_FatalError(
857 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner0fd2c302019-06-04 03:15:09 +0200858 tstate_delete_common(runtime, tstate);
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200859 if (gilstate->autoInterpreterState &&
860 PyThread_tss_get(&gilstate->autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600861 {
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200862 PyThread_tss_set(&gilstate->autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600863 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200864 _PyRuntimeGILState_SetThreadState(gilstate, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000866}
Guido van Rossum29757862001-01-23 01:46:06 +0000867
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200868void
869PyThreadState_DeleteCurrent()
870{
871 _PyThreadState_DeleteCurrent(&_PyRuntime);
872}
873
Guido van Rossum29757862001-01-23 01:46:06 +0000874
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200875/*
876 * Delete all thread states except the one passed as argument.
877 * Note that, if there is a current thread state, it *must* be the one
878 * passed as argument. Also, this won't touch any other interpreters
879 * than the current one, since we don't know which thread state should
Miss Islington (bot)4bd1d052019-08-30 13:42:54 -0700880 * be kept in those other interpreters.
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200881 */
882void
Victor Stinner0fd2c302019-06-04 03:15:09 +0200883_PyThreadState_DeleteExcept(_PyRuntimeState *runtime, PyThreadState *tstate)
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200884{
885 PyInterpreterState *interp = tstate->interp;
886 PyThreadState *p, *next, *garbage;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200887 HEAD_LOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200888 /* Remove all thread states, except tstate, from the linked list of
889 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200890 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200891 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200892 if (garbage == tstate)
893 garbage = tstate->next;
894 if (tstate->prev)
895 tstate->prev->next = tstate->next;
896 if (tstate->next)
897 tstate->next->prev = tstate->prev;
898 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200899 interp->tstate_head = tstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200900 HEAD_UNLOCK(runtime);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200901 /* Clear and deallocate all stale thread states. Even if this
902 executes Python code, we should be safe since it executes
903 in the current thread, not one of the stale threads. */
904 for (p = garbage; p; p = next) {
905 next = p->next;
906 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200907 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200908 }
909}
910
911
Guido van Rossuma027efa1997-05-05 20:56:21 +0000912PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100913_PyThreadState_UncheckedGet(void)
914{
Victor Stinner50b48572018-11-01 01:51:40 +0100915 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100916}
917
918
919PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000920PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000921{
Victor Stinner50b48572018-11-01 01:51:40 +0100922 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 if (tstate == NULL)
924 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000925
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000927}
928
929
Victor Stinner09532fe2019-05-10 23:39:09 +0200930PyThreadState *
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200931_PyThreadState_Swap(struct _gilstate_runtime_state *gilstate, PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000932{
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200933 PyThreadState *oldts = _PyRuntimeGILState_GetThreadState(gilstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000934
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200935 _PyRuntimeGILState_SetThreadState(gilstate, newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 /* It should not be possible for more than one thread state
937 to be used for a thread. Check this the best we can in debug
938 builds.
939 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200940#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 if (newts) {
942 /* This can be called from PyEval_RestoreThread(). Similar
943 to it, we need to ensure errno doesn't change.
944 */
945 int err = errno;
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200946 PyThreadState *check = _PyGILState_GetThisThreadState(gilstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 if (check && check->interp == newts->interp && check != newts)
948 Py_FatalError("Invalid thread state for this thread");
949 errno = err;
950 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000951#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000953}
Guido van Rossumede04391998-04-10 20:18:25 +0000954
Victor Stinner10c8e6a2019-04-26 01:53:18 +0200955PyThreadState *
956PyThreadState_Swap(PyThreadState *newts)
957{
958 return _PyThreadState_Swap(&_PyRuntime.gilstate, newts);
959}
960
Guido van Rossumede04391998-04-10 20:18:25 +0000961/* An extension mechanism to store arbitrary additional per-thread state.
962 PyThreadState_GetDict() returns a dictionary that can be used to hold such
963 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000964 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
965 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000966
967PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000968PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000969{
Victor Stinner50b48572018-11-01 01:51:40 +0100970 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (tstate == NULL)
972 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (tstate->dict == NULL) {
975 PyObject *d;
976 tstate->dict = d = PyDict_New();
977 if (d == NULL)
978 PyErr_Clear();
979 }
980 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000981}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000982
983
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000984/* Asynchronously raise an exception in a thread.
985 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000986 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000987 to call this, or use ctypes. Must be called with the GIL held.
988 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
989 match any known thread id). Can be called with exc=NULL to clear an
990 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000991
992int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200993PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
994{
Victor Stinner09532fe2019-05-10 23:39:09 +0200995 _PyRuntimeState *runtime = &_PyRuntime;
996 PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 /* Although the GIL is held, a few C API functions can be called
999 * without the GIL held, and in particular some that create and
1000 * destroy thread and interpreter states. Those can mutate the
1001 * list of thread states we're traversing, so to prevent that we lock
1002 * head_mutex for the duration.
1003 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001004 HEAD_LOCK(runtime);
Victor Stinner09532fe2019-05-10 23:39:09 +02001005 for (PyThreadState *p = interp->tstate_head; p != NULL; p = p->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 if (p->thread_id == id) {
1007 /* Tricky: we need to decref the current value
1008 * (if any) in p->async_exc, but that can in turn
1009 * allow arbitrary Python code to run, including
1010 * perhaps calls to this function. To prevent
1011 * deadlock, we need to release head_mutex before
1012 * the decref.
1013 */
1014 PyObject *old_exc = p->async_exc;
1015 Py_XINCREF(exc);
1016 p->async_exc = exc;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001017 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 Py_XDECREF(old_exc);
Victor Stinnere225beb2019-06-03 18:14:24 +02001019 _PyEval_SignalAsyncExc(&runtime->ceval);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 return 1;
1021 }
1022 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001023 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001025}
1026
1027
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001028/* Routines for advanced debuggers, requested by David Beazley.
1029 Don't use unless you know what you are doing! */
1030
1031PyInterpreterState *
1032PyInterpreterState_Head(void)
1033{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001034 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001035}
1036
1037PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -07001038PyInterpreterState_Main(void)
1039{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001040 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -07001041}
1042
1043PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001044PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001046}
1047
1048PyThreadState *
1049PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001051}
1052
1053PyThreadState *
1054PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +00001056}
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001057
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001058/* The implementation of sys._current_frames(). This is intended to be
1059 called with the GIL held, as it will be when called via
1060 sys._current_frames(). It's possible it would work fine even without
1061 the GIL held, but haven't thought enough about that.
1062*/
1063PyObject *
1064_PyThread_CurrentFrames(void)
1065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 PyObject *result;
1067 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001068
Steve Dowerb82e17e2019-05-23 08:45:22 -07001069 if (PySys_Audit("sys._current_frames", NULL) < 0) {
1070 return NULL;
1071 }
1072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 result = PyDict_New();
1074 if (result == NULL)
1075 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 /* for i in all interpreters:
1078 * for t in all of i's thread states:
1079 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +02001080 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 * need to grab head_mutex for the duration.
1082 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001083 _PyRuntimeState *runtime = &_PyRuntime;
1084 HEAD_LOCK(runtime);
1085 for (i = runtime->interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 PyThreadState *t;
1087 for (t = i->tstate_head; t != NULL; t = t->next) {
1088 PyObject *id;
1089 int stat;
1090 struct _frame *frame = t->frame;
1091 if (frame == NULL)
1092 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001093 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 if (id == NULL)
1095 goto Fail;
1096 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1097 Py_DECREF(id);
1098 if (stat < 0)
1099 goto Fail;
1100 }
1101 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001102 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001104
1105 Fail:
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001106 HEAD_UNLOCK(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 Py_DECREF(result);
1108 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001109}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001110
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001111/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001112
1113/* Keep this as a static, as it is not reliable! It can only
1114 ever be compared to the state for the *current* thread.
1115 * If not equal, then it doesn't matter that the actual
1116 value may change immediately after comparison, as it can't
1117 possibly change to the current thread's state.
1118 * If equal, then the current thread holds the lock, so the value can't
1119 change until we yield the lock.
1120*/
1121static int
1122PyThreadState_IsCurrent(PyThreadState *tstate)
1123{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 /* Must be the tstate for this thread */
Victor Stinner0fd2c302019-06-04 03:15:09 +02001125 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001126 assert(_PyGILState_GetThisThreadState(gilstate) == tstate);
1127 return tstate == _PyRuntimeGILState_GetThreadState(gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001128}
1129
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001130/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001131 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001132*/
Tim Peters19717fa2004-10-09 17:38:29 +00001133void
Victor Stinner0fd2c302019-06-04 03:15:09 +02001134_PyGILState_Init(_PyRuntimeState *runtime,
1135 PyInterpreterState *interp, PyThreadState *tstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001136{
Victor Stinner8bb32302019-04-24 16:47:40 +02001137 /* must init with valid states */
Eric Snow396e0a82019-05-31 21:16:47 -06001138 assert(interp != NULL);
Victor Stinner0fd2c302019-06-04 03:15:09 +02001139 assert(tstate != NULL);
Victor Stinner8bb32302019-04-24 16:47:40 +02001140
Victor Stinner8bb32302019-04-24 16:47:40 +02001141 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1142
1143 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001144 Py_FatalError("Could not allocate TSS entry");
1145 }
Victor Stinner8bb32302019-04-24 16:47:40 +02001146 gilstate->autoInterpreterState = interp;
1147 assert(PyThread_tss_get(&gilstate->autoTSSkey) == NULL);
1148 assert(tstate->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001149
Victor Stinner8bb32302019-04-24 16:47:40 +02001150 _PyGILState_NoteThreadState(gilstate, tstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001151}
1152
Victor Stinner861d9ab2016-03-16 22:45:24 +01001153PyInterpreterState *
1154_PyGILState_GetInterpreterStateUnsafe(void)
1155{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001156 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001157}
1158
Tim Peters19717fa2004-10-09 17:38:29 +00001159void
Victor Stinner8e91c242019-04-24 17:24:01 +02001160_PyGILState_Fini(_PyRuntimeState *runtime)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001161{
Victor Stinner8e91c242019-04-24 17:24:01 +02001162 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
1163 PyThread_tss_delete(&gilstate->autoTSSkey);
1164 gilstate->autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001165}
1166
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001167/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001168 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001169 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001170 */
1171void
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001172_PyGILState_Reinit(_PyRuntimeState *runtime)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001173{
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001174 struct _gilstate_runtime_state *gilstate = &runtime->gilstate;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001175 PyThreadState *tstate = _PyGILState_GetThisThreadState(gilstate);
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001176
1177 PyThread_tss_delete(&gilstate->autoTSSkey);
1178 if (PyThread_tss_create(&gilstate->autoTSSkey) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001179 Py_FatalError("Could not allocate TSS entry");
1180 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001181
Charles-François Natalia233df82011-11-22 19:49:51 +01001182 /* If the thread had an associated auto thread state, reassociate it with
1183 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001184 if (tstate &&
Victor Stinnerb930a2d2019-04-24 17:14:33 +02001185 PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate) != 0)
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001186 {
1187 Py_FatalError("Couldn't create autoTSSkey mapping");
1188 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001189}
1190
Michael W. Hudson188d4362005-06-20 16:52:57 +00001191/* When a thread state is created for a thread by some mechanism other than
1192 PyGILState_Ensure, it's important that the GILState machinery knows about
1193 it so it doesn't try to create another thread state for the thread (this is
1194 a better fix for SF bug #1010677 than the first one attempted).
1195*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001196static void
Victor Stinner8bb32302019-04-24 16:47:40 +02001197_PyGILState_NoteThreadState(struct _gilstate_runtime_state *gilstate, PyThreadState* tstate)
Michael W. Hudson188d4362005-06-20 16:52:57 +00001198{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001199 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001200 threadstate created in Py_Initialize(). Don't do anything for now
1201 (we'll be back here when _PyGILState_Init is called). */
Victor Stinner8bb32302019-04-24 16:47:40 +02001202 if (!gilstate->autoInterpreterState) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 return;
Victor Stinner8bb32302019-04-24 16:47:40 +02001204 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001205
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001206 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 The only situation where you can legitimately have more than one
1209 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001210 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001211
Victor Stinner590cebe2013-12-13 11:08:56 +01001212 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1213 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001214
Victor Stinner590cebe2013-12-13 11:08:56 +01001215 The first thread state created for that given OS level thread will
1216 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 */
Victor Stinner8bb32302019-04-24 16:47:40 +02001218 if (PyThread_tss_get(&gilstate->autoTSSkey) == NULL) {
1219 if ((PyThread_tss_set(&gilstate->autoTSSkey, (void *)tstate)) != 0) {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001220 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001221 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001222 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001223
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 /* PyGILState_Release must not try to delete this thread state. */
1225 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001226}
1227
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001228/* The public functions */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001229static PyThreadState *
1230_PyGILState_GetThisThreadState(struct _gilstate_runtime_state *gilstate)
1231{
1232 if (gilstate->autoInterpreterState == NULL)
1233 return NULL;
1234 return (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
1235}
1236
Tim Peters19717fa2004-10-09 17:38:29 +00001237PyThreadState *
1238PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001239{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001240 return _PyGILState_GetThisThreadState(&_PyRuntime.gilstate);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001241}
1242
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001243int
1244PyGILState_Check(void)
1245{
Victor Stinner8a1be612016-03-14 22:07:55 +01001246
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001247 if (!_PyGILState_check_enabled) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001248 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001249 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001250
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001251 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1252 if (!PyThread_tss_is_created(&gilstate->autoTSSkey)) {
1253 return 1;
1254 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001255
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001256 PyThreadState *tstate = _PyRuntimeGILState_GetThreadState(gilstate);
1257 if (tstate == NULL) {
1258 return 0;
1259 }
1260
1261 return (tstate == _PyGILState_GetThisThreadState(gilstate));
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001262}
1263
Tim Peters19717fa2004-10-09 17:38:29 +00001264PyGILState_STATE
1265PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001266{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001267 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 int current;
1269 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001270 int need_init_threads = 0;
1271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 /* Note that we do not auto-init Python here - apart from
1273 potential races with 2 threads auto-initializing, pep-311
1274 spells out other issues. Embedders are expected to have
1275 called Py_Initialize() and usually PyEval_InitThreads().
1276 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001277 /* Py_Initialize() hasn't been called! */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001278 assert(gilstate->autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001279
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001280 tcur = (PyThreadState *)PyThread_tss_get(&gilstate->autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001282 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 /* Create a new thread state for this thread */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001285 tcur = PyThreadState_New(gilstate->autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 if (tcur == NULL)
1287 Py_FatalError("Couldn't create thread-state for new thread");
1288 /* This is our thread state! We'll need to delete it in the
1289 matching call to PyGILState_Release(). */
1290 tcur->gilstate_counter = 0;
1291 current = 0; /* new thread state is never current */
1292 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001293 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001295 }
1296
1297 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001299 }
1300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 /* Update our counter in the thread-state - no need for locks:
1302 - tcur will remain valid as we hold the GIL.
1303 - the counter is safe as we are the only thread "allowed"
1304 to modify this value
1305 */
1306 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001307
1308 if (need_init_threads) {
1309 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1310 called from a new thread for the first time, we need the create the
1311 GIL. */
1312 PyEval_InitThreads();
1313 }
1314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001316}
1317
Tim Peters19717fa2004-10-09 17:38:29 +00001318void
1319PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001320{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001321 _PyRuntimeState *runtime = &_PyRuntime;
1322 PyThreadState *tcur = PyThread_tss_get(&runtime->gilstate.autoTSSkey);
1323 if (tcur == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 Py_FatalError("auto-releasing thread-state, "
1325 "but no thread-state for this thread");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001326 }
1327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 /* We must hold the GIL and have our thread state current */
1329 /* XXX - remove the check - the assert should be fine,
1330 but while this is very new (April 2003), the extra check
1331 by release-only users can't hurt.
1332 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001333 if (!PyThreadState_IsCurrent(tcur)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 Py_FatalError("This thread state must be current when releasing");
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001335 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 assert(PyThreadState_IsCurrent(tcur));
1337 --tcur->gilstate_counter;
1338 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001339
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 /* If we're going to destroy this thread-state, we must
1341 * clear it while the GIL is held, as destructors may run.
1342 */
1343 if (tcur->gilstate_counter == 0) {
1344 /* can't have been locked when we created it */
1345 assert(oldstate == PyGILState_UNLOCKED);
1346 PyThreadState_Clear(tcur);
1347 /* Delete the thread-state. Note this releases the GIL too!
1348 * It's vital that the GIL be held here, to avoid shutdown
1349 * races; see bugs 225673 and 1061968 (that nasty bug has a
1350 * habit of coming back).
1351 */
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001352 _PyThreadState_DeleteCurrent(runtime);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 }
1354 /* Release the lock if necessary */
1355 else if (oldstate == PyGILState_UNLOCKED)
1356 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001357}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001358
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001359
Eric Snow7f8bfc92018-01-29 18:23:44 -07001360/**************************/
1361/* cross-interpreter data */
1362/**************************/
1363
1364/* cross-interpreter data */
1365
1366crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1367
1368/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1369 to keep the registry code separate. */
1370static crossinterpdatafunc
1371_lookup_getdata(PyObject *obj)
1372{
1373 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1374 if (getdata == NULL && PyErr_Occurred() == 0)
1375 PyErr_Format(PyExc_ValueError,
1376 "%S does not support cross-interpreter data", obj);
1377 return getdata;
1378}
1379
1380int
1381_PyObject_CheckCrossInterpreterData(PyObject *obj)
1382{
1383 crossinterpdatafunc getdata = _lookup_getdata(obj);
1384 if (getdata == NULL) {
1385 return -1;
1386 }
1387 return 0;
1388}
1389
1390static int
1391_check_xidata(_PyCrossInterpreterData *data)
1392{
1393 // data->data can be anything, including NULL, so we don't check it.
1394
1395 // data->obj may be NULL, so we don't check it.
1396
1397 if (data->interp < 0) {
1398 PyErr_SetString(PyExc_SystemError, "missing interp");
1399 return -1;
1400 }
1401
1402 if (data->new_object == NULL) {
1403 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1404 return -1;
1405 }
1406
1407 // data->free may be NULL, so we don't check it.
1408
1409 return 0;
1410}
1411
1412int
1413_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1414{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001415 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001416 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001417 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001418
1419 // Reset data before re-populating.
1420 *data = (_PyCrossInterpreterData){0};
1421 data->free = PyMem_RawFree; // Set a default that may be overridden.
1422
1423 // Call the "getdata" func for the object.
1424 Py_INCREF(obj);
1425 crossinterpdatafunc getdata = _lookup_getdata(obj);
1426 if (getdata == NULL) {
1427 Py_DECREF(obj);
1428 return -1;
1429 }
1430 int res = getdata(obj, data);
1431 Py_DECREF(obj);
1432 if (res != 0) {
1433 return -1;
1434 }
1435
1436 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001437 data->interp = interp->id;
1438 if (_check_xidata(data) != 0) {
1439 _PyCrossInterpreterData_Release(data);
1440 return -1;
1441 }
1442
1443 return 0;
1444}
1445
Victor Stinnere225beb2019-06-03 18:14:24 +02001446static void
Eric Snow63799132018-06-01 18:45:20 -06001447_release_xidata(void *arg)
1448{
1449 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1450 if (data->free != NULL) {
1451 data->free(data->data);
1452 }
1453 Py_XDECREF(data->obj);
Victor Stinnere225beb2019-06-03 18:14:24 +02001454}
1455
1456static void
1457_call_in_interpreter(struct _gilstate_runtime_state *gilstate,
1458 PyInterpreterState *interp,
1459 void (*func)(void *), void *arg)
1460{
1461 /* We would use Py_AddPendingCall() if it weren't specific to the
1462 * main interpreter (see bpo-33608). In the meantime we take a
1463 * naive approach.
1464 */
1465 PyThreadState *save_tstate = NULL;
1466 if (interp != _PyRuntimeGILState_GetThreadState(gilstate)->interp) {
1467 // XXX Using the "head" thread isn't strictly correct.
1468 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1469 // XXX Possible GILState issues?
1470 save_tstate = _PyThreadState_Swap(gilstate, tstate);
1471 }
1472
1473 func(arg);
1474
1475 // Switch back.
1476 if (save_tstate != NULL) {
1477 _PyThreadState_Swap(gilstate, save_tstate);
1478 }
Eric Snow63799132018-06-01 18:45:20 -06001479}
1480
Eric Snow7f8bfc92018-01-29 18:23:44 -07001481void
1482_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1483{
1484 if (data->data == NULL && data->obj == NULL) {
1485 // Nothing to release!
1486 return;
1487 }
1488
Victor Stinnere225beb2019-06-03 18:14:24 +02001489 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001490 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1491 if (interp == NULL) {
1492 // The intepreter was already destroyed.
1493 if (data->free != NULL) {
1494 // XXX Someone leaked some memory...
1495 }
1496 return;
1497 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001498
Eric Snow7f8bfc92018-01-29 18:23:44 -07001499 // "Release" the data and/or the object.
Victor Stinnere225beb2019-06-03 18:14:24 +02001500 struct _gilstate_runtime_state *gilstate = &_PyRuntime.gilstate;
1501 _call_in_interpreter(gilstate, interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001502}
1503
1504PyObject *
1505_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1506{
1507 return data->new_object(data);
1508}
1509
1510/* registry of {type -> crossinterpdatafunc} */
1511
1512/* For now we use a global registry of shareable classes. An
1513 alternative would be to add a tp_* slot for a class's
1514 crossinterpdatafunc. It would be simpler and more efficient. */
1515
1516static int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001517_register_xidata(struct _xidregistry *xidregistry, PyTypeObject *cls,
1518 crossinterpdatafunc getdata)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001519{
1520 // Note that we effectively replace already registered classes
1521 // rather than failing.
1522 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1523 if (newhead == NULL)
1524 return -1;
1525 newhead->cls = cls;
1526 newhead->getdata = getdata;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001527 newhead->next = xidregistry->head;
1528 xidregistry->head = newhead;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001529 return 0;
1530}
1531
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001532static void _register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001533
1534int
Eric Snowc11183c2019-03-15 16:35:46 -06001535_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001536 crossinterpdatafunc getdata)
1537{
1538 if (!PyType_Check(cls)) {
1539 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1540 return -1;
1541 }
1542 if (getdata == NULL) {
1543 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1544 return -1;
1545 }
1546
1547 // Make sure the class isn't ever deallocated.
1548 Py_INCREF((PyObject *)cls);
1549
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001550 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
1551 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1552 if (xidregistry->head == NULL) {
1553 _register_builtins_for_crossinterpreter_data(xidregistry);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001554 }
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001555 int res = _register_xidata(xidregistry, cls, getdata);
1556 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001557 return res;
1558}
1559
Eric Snow6d2cd902018-05-16 15:04:57 -04001560/* Cross-interpreter objects are looked up by exact match on the class.
1561 We can reassess this policy when we move from a global registry to a
1562 tp_* slot. */
1563
Eric Snow7f8bfc92018-01-29 18:23:44 -07001564crossinterpdatafunc
1565_PyCrossInterpreterData_Lookup(PyObject *obj)
1566{
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001567 struct _xidregistry *xidregistry = &_PyRuntime.xidregistry ;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001568 PyObject *cls = PyObject_Type(obj);
1569 crossinterpdatafunc getdata = NULL;
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001570 PyThread_acquire_lock(xidregistry->mutex, WAIT_LOCK);
1571 struct _xidregitem *cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001572 if (cur == NULL) {
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001573 _register_builtins_for_crossinterpreter_data(xidregistry);
1574 cur = xidregistry->head;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001575 }
1576 for(; cur != NULL; cur = cur->next) {
1577 if (cur->cls == (PyTypeObject *)cls) {
1578 getdata = cur->getdata;
1579 break;
1580 }
1581 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001582 Py_DECREF(cls);
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001583 PyThread_release_lock(xidregistry->mutex);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001584 return getdata;
1585}
1586
1587/* cross-interpreter data for builtin types */
1588
Eric Snow6d2cd902018-05-16 15:04:57 -04001589struct _shared_bytes_data {
1590 char *bytes;
1591 Py_ssize_t len;
1592};
1593
Eric Snow7f8bfc92018-01-29 18:23:44 -07001594static PyObject *
1595_new_bytes_object(_PyCrossInterpreterData *data)
1596{
Eric Snow6d2cd902018-05-16 15:04:57 -04001597 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1598 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001599}
1600
1601static int
1602_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1603{
Eric Snow6d2cd902018-05-16 15:04:57 -04001604 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1605 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1606 return -1;
1607 }
1608 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001609 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001610 data->obj = obj; // Will be "released" (decref'ed) when data released.
1611 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001612 data->free = PyMem_Free;
1613 return 0;
1614}
1615
1616struct _shared_str_data {
1617 int kind;
1618 const void *buffer;
1619 Py_ssize_t len;
1620};
1621
1622static PyObject *
1623_new_str_object(_PyCrossInterpreterData *data)
1624{
1625 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1626 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1627}
1628
1629static int
1630_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1631{
1632 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1633 shared->kind = PyUnicode_KIND(obj);
1634 shared->buffer = PyUnicode_DATA(obj);
1635 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1636 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001637 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001638 data->obj = obj; // Will be "released" (decref'ed) when data released.
1639 data->new_object = _new_str_object;
1640 data->free = PyMem_Free;
1641 return 0;
1642}
1643
1644static PyObject *
1645_new_long_object(_PyCrossInterpreterData *data)
1646{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001647 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001648}
1649
1650static int
1651_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1652{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001653 /* Note that this means the size of shareable ints is bounded by
1654 * sys.maxsize. Hence on 32-bit architectures that is half the
1655 * size of maximum shareable ints on 64-bit.
1656 */
1657 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001658 if (value == -1 && PyErr_Occurred()) {
1659 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1660 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1661 }
1662 return -1;
1663 }
1664 data->data = (void *)value;
1665 data->obj = NULL;
1666 data->new_object = _new_long_object;
1667 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001668 return 0;
1669}
1670
1671static PyObject *
1672_new_none_object(_PyCrossInterpreterData *data)
1673{
1674 // XXX Singleton refcounts are problematic across interpreters...
1675 Py_INCREF(Py_None);
1676 return Py_None;
1677}
1678
1679static int
1680_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1681{
1682 data->data = NULL;
1683 // data->obj remains NULL
1684 data->new_object = _new_none_object;
1685 data->free = NULL; // There is nothing to free.
1686 return 0;
1687}
1688
1689static void
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001690_register_builtins_for_crossinterpreter_data(struct _xidregistry *xidregistry)
Eric Snow7f8bfc92018-01-29 18:23:44 -07001691{
1692 // None
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001693 if (_register_xidata(xidregistry, (PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001694 Py_FatalError("could not register None for cross-interpreter sharing");
1695 }
1696
Eric Snow6d2cd902018-05-16 15:04:57 -04001697 // int
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001698 if (_register_xidata(xidregistry, &PyLong_Type, _long_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001699 Py_FatalError("could not register int for cross-interpreter sharing");
1700 }
1701
Eric Snow7f8bfc92018-01-29 18:23:44 -07001702 // bytes
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001703 if (_register_xidata(xidregistry, &PyBytes_Type, _bytes_shared) != 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001704 Py_FatalError("could not register bytes for cross-interpreter sharing");
1705 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001706
1707 // str
Victor Stinner10c8e6a2019-04-26 01:53:18 +02001708 if (_register_xidata(xidregistry, &PyUnicode_Type, _str_shared) != 0) {
Eric Snow6d2cd902018-05-16 15:04:57 -04001709 Py_FatalError("could not register str for cross-interpreter sharing");
1710 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001711}
1712
1713
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001714#ifdef __cplusplus
1715}
1716#endif