blob: d04981121c1ca47ab9c7d091f9038bd014425478 [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"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06005#include "internal/pystate.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +00006
Victor Stinner9204fb82018-10-30 15:13:17 +01007#define _PyThreadState_SET(value) \
8 _Py_atomic_store_relaxed(&_PyRuntime.gilstate.tstate_current, \
9 (uintptr_t)(value))
Victor Stinnerb02ef712016-01-22 14:09:55 +010010
Victor Stinnerbfd316e2016-01-20 11:12:38 +010011
Tim Peters84705582004-10-10 02:47:33 +000012/* --------------------------------------------------------------------------
13CAUTION
14
Victor Stinner1a7425f2013-07-07 16:25:15 +020015Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
16number of these functions are advertised as safe to call when the GIL isn't
17held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
18debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
19to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000020-------------------------------------------------------------------------- */
21
Martin v. Löwisf0473d52001-07-18 16:17:16 +000022#ifdef HAVE_DLOPEN
23#ifdef HAVE_DLFCN_H
24#include <dlfcn.h>
25#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030026#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000027#define RTLD_LAZY 1
28#endif
29#endif
30
Benjamin Peterson43162b82012-04-13 11:58:27 -040031#ifdef __cplusplus
32extern "C" {
33#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000034
Victor Stinner5d39e042017-11-29 17:20:38 +010035static _PyInitError
36_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060037{
38 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010039
Eric Snow2ebc5ce2017-09-07 23:51:28 -060040 _PyGC_Initialize(&runtime->gc);
41 _PyEval_Initialize(&runtime->ceval);
Michael W. Hudson188d4362005-06-20 16:52:57 +000042
Eric Snow2ebc5ce2017-09-07 23:51:28 -060043 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080044
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090045 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
46 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080047 Py_tss_t initial = Py_tss_NEEDS_INIT;
48 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000049
Eric Snow2ebc5ce2017-09-07 23:51:28 -060050 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080051 if (runtime->interpreters.mutex == NULL) {
52 return _Py_INIT_ERR("Can't initialize threads for interpreter");
53 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060054 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070055
56 runtime->xidregistry.mutex = PyThread_allocate_lock();
57 if (runtime->xidregistry.mutex == NULL) {
58 return _Py_INIT_ERR("Can't initialize threads for cross-interpreter data registry");
59 }
60
Victor Stinnerf7e5b562017-11-15 15:48:08 -080061 return _Py_INIT_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060062}
Eric Snow05351c12017-09-05 21:43:08 -070063
Victor Stinner5d39e042017-11-29 17:20:38 +010064_PyInitError
65_PyRuntimeState_Init(_PyRuntimeState *runtime)
66{
67 /* Force default allocator, since _PyRuntimeState_Fini() must
68 use the same allocator than this function. */
69 PyMemAllocatorEx old_alloc;
70 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
71
72 _PyInitError err = _PyRuntimeState_Init_impl(runtime);
73
74 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
75 return err;
76}
77
Eric Snow2ebc5ce2017-09-07 23:51:28 -060078void
79_PyRuntimeState_Fini(_PyRuntimeState *runtime)
80{
Victor Stinner5d39e042017-11-29 17:20:38 +010081 /* Force the allocator used by _PyRuntimeState_Init(). */
82 PyMemAllocatorEx old_alloc;
83 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -080084
Eric Snow2ebc5ce2017-09-07 23:51:28 -060085 if (runtime->interpreters.mutex != NULL) {
86 PyThread_free_lock(runtime->interpreters.mutex);
87 runtime->interpreters.mutex = NULL;
88 }
Victor Stinnerccb04422017-11-16 03:20:31 -080089
90 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060091}
92
93#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
94 WAIT_LOCK)
95#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -070096
Michael W. Hudson188d4362005-06-20 16:52:57 +000097static void _PyGILState_NoteThreadState(PyThreadState* tstate);
98
Victor Stinnera7368ac2017-11-15 18:11:45 -080099_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600100_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700101{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600102 runtime->interpreters.next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100103
104 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
105 Create a new mutex if needed. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600106 if (runtime->interpreters.mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100107 /* Force default allocator, since _PyRuntimeState_Fini() must
108 use the same allocator than this function. */
109 PyMemAllocatorEx old_alloc;
110 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
111
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600112 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100113
114 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
115
Victor Stinnera7368ac2017-11-15 18:11:45 -0800116 if (runtime->interpreters.mutex == NULL) {
117 return _Py_INIT_ERR("Can't initialize threads for interpreter");
118 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600119 }
Victor Stinner5d926472018-03-06 14:31:37 +0100120
Victor Stinnera7368ac2017-11-15 18:11:45 -0800121 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700122}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000123
124PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000125PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200128 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000129
Victor Stinnerd4341102017-11-23 00:12:09 +0100130 if (interp == NULL) {
131 return NULL;
132 }
133
Eric Snow4c6955e2018-02-16 18:53:40 -0700134 interp->id_refcount = -1;
135 interp->id_mutex = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100136 interp->modules = NULL;
137 interp->modules_by_index = NULL;
138 interp->sysdict = NULL;
139 interp->builtins = NULL;
140 interp->builtins_copy = NULL;
141 interp->tstate_head = NULL;
142 interp->check_interval = 100;
143 interp->num_threads = 0;
144 interp->pythread_stacksize = 0;
145 interp->codec_search_path = NULL;
146 interp->codec_search_cache = NULL;
147 interp->codec_error_registry = NULL;
148 interp->codecs_initialized = 0;
149 interp->fscodec_initialized = 0;
150 interp->core_config = _PyCoreConfig_INIT;
151 interp->config = _PyMainInterpreterConfig_INIT;
152 interp->importlib = NULL;
153 interp->import_func = NULL;
154 interp->eval_frame = _PyEval_EvalFrameDefault;
155 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000156#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300157#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100158 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000159#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100160 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000161#endif
162#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200163#ifdef HAVE_FORK
Victor Stinnerd4341102017-11-23 00:12:09 +0100164 interp->before_forkers = NULL;
165 interp->after_forkers_parent = NULL;
166 interp->after_forkers_child = NULL;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200167#endif
Marcel Plch776407f2017-12-20 11:17:58 +0100168 interp->pyexitfunc = NULL;
169 interp->pyexitmodule = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000170
Victor Stinnerd4341102017-11-23 00:12:09 +0100171 HEAD_LOCK();
Victor Stinnerd4341102017-11-23 00:12:09 +0100172 if (_PyRuntime.interpreters.next_id < 0) {
173 /* overflow or Py_Initialize() not called! */
174 PyErr_SetString(PyExc_RuntimeError,
175 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100176 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100177 interp = NULL;
178 } else {
179 interp->id = _PyRuntime.interpreters.next_id;
180 _PyRuntime.interpreters.next_id += 1;
Pablo Galindo95d630e2018-08-31 22:49:29 +0100181 interp->next = _PyRuntime.interpreters.head;
182 if (_PyRuntime.interpreters.main == NULL) {
183 _PyRuntime.interpreters.main = interp;
184 }
185 _PyRuntime.interpreters.head = interp;
Victor Stinnerd4341102017-11-23 00:12:09 +0100186 }
187 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000188
Pablo Galindo95d630e2018-08-31 22:49:29 +0100189 if (interp == NULL) {
190 return NULL;
191 }
192
Yury Selivanovf23746a2018-01-22 19:11:18 -0500193 interp->tstate_next_unique_id = 0;
194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000196}
197
198
199void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000200PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 PyThreadState *p;
203 HEAD_LOCK();
204 for (p = interp->tstate_head; p != NULL; p = p->next)
205 PyThreadState_Clear(p);
206 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100207 _PyCoreConfig_Clear(&interp->core_config);
208 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 Py_CLEAR(interp->codec_search_path);
210 Py_CLEAR(interp->codec_search_cache);
211 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700212 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 Py_CLEAR(interp->sysdict);
215 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200216 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400217 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300218 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200219#ifdef HAVE_FORK
220 Py_CLEAR(interp->before_forkers);
221 Py_CLEAR(interp->after_forkers_parent);
222 Py_CLEAR(interp->after_forkers_child);
223#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000224}
225
226
227static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000228zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 PyThreadState *p;
231 /* No need to lock the mutex here because this should only happen
232 when the threads are all really dead (XXX famous last words). */
233 while ((p = interp->tstate_head) != NULL) {
234 PyThreadState_Delete(p);
235 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000236}
237
238
239void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000240PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 PyInterpreterState **p;
243 zapthreads(interp);
244 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600245 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 if (*p == NULL)
247 Py_FatalError(
248 "PyInterpreterState_Delete: invalid interp");
249 if (*p == interp)
250 break;
251 }
252 if (interp->tstate_head != NULL)
253 Py_FatalError("PyInterpreterState_Delete: remaining threads");
254 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600255 if (_PyRuntime.interpreters.main == interp) {
256 _PyRuntime.interpreters.main = NULL;
257 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700258 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
259 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 HEAD_UNLOCK();
Eric Snow4c6955e2018-02-16 18:53:40 -0700261 if (interp->id_mutex != NULL) {
262 PyThread_free_lock(interp->id_mutex);
263 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200264 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000265}
266
267
Eric Snow59032962018-09-14 14:17:20 -0700268/*
269 * Delete all interpreter states except the main interpreter. If there
270 * is a current interpreter state, it *must* be the main interpreter.
271 */
272void
273_PyInterpreterState_DeleteExceptMain()
274{
275 PyThreadState *tstate = PyThreadState_Swap(NULL);
276 if (tstate != NULL && tstate->interp != _PyRuntime.interpreters.main) {
277 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
278 }
279
280 HEAD_LOCK();
281 PyInterpreterState *interp = _PyRuntime.interpreters.head;
282 _PyRuntime.interpreters.head = NULL;
283 for (; interp != NULL; interp = interp->next) {
284 if (interp == _PyRuntime.interpreters.main) {
285 _PyRuntime.interpreters.main->next = NULL;
286 _PyRuntime.interpreters.head = interp;
287 continue;
288 }
289
290 PyInterpreterState_Clear(interp); // XXX must activate?
291 zapthreads(interp);
292 if (interp->id_mutex != NULL) {
293 PyThread_free_lock(interp->id_mutex);
294 }
295 PyMem_RawFree(interp);
296 }
297 HEAD_UNLOCK();
298
299 if (_PyRuntime.interpreters.head == NULL) {
300 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
301 }
302 PyThreadState_Swap(tstate);
303}
304
305
Victor Stinnercaba55b2018-08-03 15:33:52 +0200306PyInterpreterState *
307_PyInterpreterState_Get(void)
308{
Victor Stinner9204fb82018-10-30 15:13:17 +0100309 PyThreadState *tstate = PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200310 if (tstate == NULL) {
311 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
312 }
313 PyInterpreterState *interp = tstate->interp;
314 if (interp == NULL) {
315 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
316 }
317 return interp;
318}
319
320
Eric Snowe3774162017-05-22 19:46:40 -0700321int64_t
322PyInterpreterState_GetID(PyInterpreterState *interp)
323{
324 if (interp == NULL) {
325 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
326 return -1;
327 }
328 return interp->id;
329}
330
331
Eric Snow7f8bfc92018-01-29 18:23:44 -0700332PyInterpreterState *
333_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
334{
335 if (requested_id < 0)
336 goto error;
337
338 PyInterpreterState *interp = PyInterpreterState_Head();
339 while (interp != NULL) {
340 PY_INT64_T id = PyInterpreterState_GetID(interp);
341 if (id < 0)
342 return NULL;
343 if (requested_id == id)
344 return interp;
345 interp = PyInterpreterState_Next(interp);
346 }
347
348error:
349 PyErr_Format(PyExc_RuntimeError,
350 "unrecognized interpreter ID %lld", requested_id);
351 return NULL;
352}
353
Eric Snow4c6955e2018-02-16 18:53:40 -0700354
355int
356_PyInterpreterState_IDInitref(PyInterpreterState *interp)
357{
358 if (interp->id_mutex != NULL) {
359 return 0;
360 }
361 interp->id_mutex = PyThread_allocate_lock();
362 if (interp->id_mutex == NULL) {
363 PyErr_SetString(PyExc_RuntimeError,
364 "failed to create init interpreter ID mutex");
365 return -1;
366 }
367 interp->id_refcount = 0;
368 return 0;
369}
370
371
372void
373_PyInterpreterState_IDIncref(PyInterpreterState *interp)
374{
375 if (interp->id_mutex == NULL) {
376 return;
377 }
378 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
379 interp->id_refcount += 1;
380 PyThread_release_lock(interp->id_mutex);
381}
382
383
384void
385_PyInterpreterState_IDDecref(PyInterpreterState *interp)
386{
387 if (interp->id_mutex == NULL) {
388 return;
389 }
390 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
391 assert(interp->id_refcount != 0);
392 interp->id_refcount -= 1;
393 int64_t refcount = interp->id_refcount;
394 PyThread_release_lock(interp->id_mutex);
395
396 if (refcount == 0) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700397 // XXX Using the "head" thread isn't strictly correct.
398 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
399 // XXX Possible GILState issues?
400 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700401 Py_EndInterpreter(tstate);
402 PyThreadState_Swap(save_tstate);
403 }
404}
405
406
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000407/* Default implementation for _PyThreadState_GetFrame */
408static struct _frame *
409threadstate_getframe(PyThreadState *self)
410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000412}
413
Victor Stinner45b9be52010-03-03 23:28:07 +0000414static PyThreadState *
415new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000416{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200417 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (_PyThreadState_GetFrame == NULL)
420 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 if (tstate != NULL) {
423 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 tstate->frame = NULL;
426 tstate->recursion_depth = 0;
427 tstate->overflowed = 0;
428 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700429 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 tstate->tracing = 0;
431 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 tstate->gilstate_counter = 0;
433 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 tstate->curexc_type = NULL;
439 tstate->curexc_value = NULL;
440 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000441
Mark Shannonae3087c2017-10-22 22:41:51 +0100442 tstate->exc_state.exc_type = NULL;
443 tstate->exc_state.exc_value = NULL;
444 tstate->exc_state.exc_traceback = NULL;
445 tstate->exc_state.previous_item = NULL;
446 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 tstate->c_profilefunc = NULL;
449 tstate->c_tracefunc = NULL;
450 tstate->c_profileobj = NULL;
451 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000452
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200453 tstate->trash_delete_nesting = 0;
454 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200455 tstate->on_delete = NULL;
456 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200457
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800458 tstate->coroutine_origin_tracking_depth = 0;
459
Yury Selivanov75445082015-05-11 22:57:16 -0400460 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400461 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400462
Yury Selivanoveb636452016-09-08 22:01:51 -0700463 tstate->async_gen_firstiter = NULL;
464 tstate->async_gen_finalizer = NULL;
465
Yury Selivanovf23746a2018-01-22 19:11:18 -0500466 tstate->context = NULL;
467 tstate->context_ver = 1;
468
469 tstate->id = ++interp->tstate_next_unique_id;
470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (init)
472 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200475 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200477 if (tstate->next)
478 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 interp->tstate_head = tstate;
480 HEAD_UNLOCK();
481 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000484}
485
Victor Stinner45b9be52010-03-03 23:28:07 +0000486PyThreadState *
487PyThreadState_New(PyInterpreterState *interp)
488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000490}
491
492PyThreadState *
493_PyThreadState_Prealloc(PyInterpreterState *interp)
494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000496}
497
498void
499_PyThreadState_Init(PyThreadState *tstate)
500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000502}
503
Martin v. Löwis1a214512008-06-11 05:26:20 +0000504PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200505PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000506{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200507 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100508 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000510 if (module->m_slots) {
511 return NULL;
512 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 if (index == 0)
514 return NULL;
515 if (state->modules_by_index == NULL)
516 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200517 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 return NULL;
519 res = PyList_GET_ITEM(state->modules_by_index, index);
520 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000521}
522
523int
524_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
525{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000526 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300527 if (!def) {
528 assert(PyErr_Occurred());
529 return -1;
530 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000531 if (def->m_slots) {
532 PyErr_SetString(PyExc_SystemError,
533 "PyState_AddModule called on module with slots");
534 return -1;
535 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100536 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 if (!state->modules_by_index) {
538 state->modules_by_index = PyList_New(0);
539 if (!state->modules_by_index)
540 return -1;
541 }
542 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
543 if (PyList_Append(state->modules_by_index, Py_None) < 0)
544 return -1;
545 Py_INCREF(module);
546 return PyList_SetItem(state->modules_by_index,
547 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000548}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000549
Martin v. Löwis7800f752012-06-22 12:20:55 +0200550int
551PyState_AddModule(PyObject* module, struct PyModuleDef* def)
552{
553 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100554 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200555 if (!def) {
556 Py_FatalError("PyState_AddModule: Module Definition is NULL");
557 return -1;
558 }
559 index = def->m_base.m_index;
560 if (state->modules_by_index) {
561 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
562 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
563 Py_FatalError("PyState_AddModule: Module already added!");
564 return -1;
565 }
566 }
567 }
568 return _PyState_AddModule(module, def);
569}
570
571int
572PyState_RemoveModule(struct PyModuleDef* def)
573{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000574 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200575 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000576 if (def->m_slots) {
577 PyErr_SetString(PyExc_SystemError,
578 "PyState_RemoveModule called on module with slots");
579 return -1;
580 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100581 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200582 if (index == 0) {
583 Py_FatalError("PyState_RemoveModule: Module index invalid.");
584 return -1;
585 }
586 if (state->modules_by_index == NULL) {
587 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
588 return -1;
589 }
590 if (index > PyList_GET_SIZE(state->modules_by_index)) {
591 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
592 return -1;
593 }
594 return PyList_SetItem(state->modules_by_index, index, Py_None);
595}
596
Antoine Pitrou40322e62013-08-11 00:30:09 +0200597/* used by import.c:PyImport_Cleanup */
598void
599_PyState_ClearModules(void)
600{
Victor Stinner9204fb82018-10-30 15:13:17 +0100601 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200602 if (state->modules_by_index) {
603 Py_ssize_t i;
604 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
605 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
606 if (PyModule_Check(m)) {
607 /* cleanup the saved copy of module dicts */
608 PyModuleDef *md = PyModule_GetDef(m);
609 if (md)
610 Py_CLEAR(md->m_base.m_copy);
611 }
612 }
613 /* Setting modules_by_index to NULL could be dangerous, so we
614 clear the list instead. */
615 if (PyList_SetSlice(state->modules_by_index,
616 0, PyList_GET_SIZE(state->modules_by_index),
617 NULL))
618 PyErr_WriteUnraisable(state->modules_by_index);
619 }
620}
621
Guido van Rossuma027efa1997-05-05 20:56:21 +0000622void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000623PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000624{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200625 int verbose = tstate->interp->core_config.verbose;
626
627 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 fprintf(stderr,
629 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 Py_CLEAR(tstate->dict);
634 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 Py_CLEAR(tstate->curexc_type);
637 Py_CLEAR(tstate->curexc_value);
638 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000639
Mark Shannonae3087c2017-10-22 22:41:51 +0100640 Py_CLEAR(tstate->exc_state.exc_type);
641 Py_CLEAR(tstate->exc_state.exc_value);
642 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300643
Mark Shannonae3087c2017-10-22 22:41:51 +0100644 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200645 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100646 fprintf(stderr,
647 "PyThreadState_Clear: warning: thread still has a generator\n");
648 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 tstate->c_profilefunc = NULL;
651 tstate->c_tracefunc = NULL;
652 Py_CLEAR(tstate->c_profileobj);
653 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400654
655 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700656 Py_CLEAR(tstate->async_gen_firstiter);
657 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500658
659 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000660}
661
662
Guido van Rossum29757862001-01-23 01:46:06 +0000663/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
664static void
665tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 if (tstate == NULL)
669 Py_FatalError("PyThreadState_Delete: NULL tstate");
670 interp = tstate->interp;
671 if (interp == NULL)
672 Py_FatalError("PyThreadState_Delete: NULL interp");
673 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200674 if (tstate->prev)
675 tstate->prev->next = tstate->next;
676 else
677 interp->tstate_head = tstate->next;
678 if (tstate->next)
679 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200681 if (tstate->on_delete != NULL) {
682 tstate->on_delete(tstate->on_delete_data);
683 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200684 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000685}
686
687
Guido van Rossum29757862001-01-23 01:46:06 +0000688void
689PyThreadState_Delete(PyThreadState *tstate)
690{
Victor Stinner9204fb82018-10-30 15:13:17 +0100691 if (tstate == PyThreadState_GET())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600693 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900694 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600695 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900696 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600697 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200698 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000699}
700
701
Guido van Rossum29757862001-01-23 01:46:06 +0000702void
703PyThreadState_DeleteCurrent()
704{
Victor Stinner9204fb82018-10-30 15:13:17 +0100705 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (tstate == NULL)
707 Py_FatalError(
708 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100709 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600710 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900711 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600712 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900713 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600714 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100715 _PyThreadState_SET(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000717}
Guido van Rossum29757862001-01-23 01:46:06 +0000718
719
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200720/*
721 * Delete all thread states except the one passed as argument.
722 * Note that, if there is a current thread state, it *must* be the one
723 * passed as argument. Also, this won't touch any other interpreters
724 * than the current one, since we don't know which thread state should
725 * be kept in those other interpreteres.
726 */
727void
728_PyThreadState_DeleteExcept(PyThreadState *tstate)
729{
730 PyInterpreterState *interp = tstate->interp;
731 PyThreadState *p, *next, *garbage;
732 HEAD_LOCK();
733 /* Remove all thread states, except tstate, from the linked list of
734 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200735 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200736 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200737 if (garbage == tstate)
738 garbage = tstate->next;
739 if (tstate->prev)
740 tstate->prev->next = tstate->next;
741 if (tstate->next)
742 tstate->next->prev = tstate->prev;
743 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200744 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200745 HEAD_UNLOCK();
746 /* Clear and deallocate all stale thread states. Even if this
747 executes Python code, we should be safe since it executes
748 in the current thread, not one of the stale threads. */
749 for (p = garbage; p; p = next) {
750 next = p->next;
751 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200752 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200753 }
754}
755
756
Guido van Rossuma027efa1997-05-05 20:56:21 +0000757PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100758_PyThreadState_UncheckedGet(void)
759{
Victor Stinner9204fb82018-10-30 15:13:17 +0100760 return PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100761}
762
763
764PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000765PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000766{
Victor Stinner9204fb82018-10-30 15:13:17 +0100767 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 if (tstate == NULL)
769 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000772}
773
774
775PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000776PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000777{
Victor Stinner9204fb82018-10-30 15:13:17 +0100778 PyThreadState *oldts = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000779
Victor Stinner9204fb82018-10-30 15:13:17 +0100780 _PyThreadState_SET(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 /* It should not be possible for more than one thread state
782 to be used for a thread. Check this the best we can in debug
783 builds.
784 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200785#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 if (newts) {
787 /* This can be called from PyEval_RestoreThread(). Similar
788 to it, we need to ensure errno doesn't change.
789 */
790 int err = errno;
791 PyThreadState *check = PyGILState_GetThisThreadState();
792 if (check && check->interp == newts->interp && check != newts)
793 Py_FatalError("Invalid thread state for this thread");
794 errno = err;
795 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000796#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000798}
Guido van Rossumede04391998-04-10 20:18:25 +0000799
800/* An extension mechanism to store arbitrary additional per-thread state.
801 PyThreadState_GetDict() returns a dictionary that can be used to hold such
802 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000803 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
804 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000805
806PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000807PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000808{
Victor Stinner9204fb82018-10-30 15:13:17 +0100809 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000810 if (tstate == NULL)
811 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 if (tstate->dict == NULL) {
814 PyObject *d;
815 tstate->dict = d = PyDict_New();
816 if (d == NULL)
817 PyErr_Clear();
818 }
819 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000820}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000821
822
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000823/* Asynchronously raise an exception in a thread.
824 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000825 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000826 to call this, or use ctypes. Must be called with the GIL held.
827 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
828 match any known thread id). Can be called with exc=NULL to clear an
829 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000830
831int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200832PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
833{
Victor Stinner9204fb82018-10-30 15:13:17 +0100834 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 /* Although the GIL is held, a few C API functions can be called
838 * without the GIL held, and in particular some that create and
839 * destroy thread and interpreter states. Those can mutate the
840 * list of thread states we're traversing, so to prevent that we lock
841 * head_mutex for the duration.
842 */
843 HEAD_LOCK();
844 for (p = interp->tstate_head; p != NULL; p = p->next) {
845 if (p->thread_id == id) {
846 /* Tricky: we need to decref the current value
847 * (if any) in p->async_exc, but that can in turn
848 * allow arbitrary Python code to run, including
849 * perhaps calls to this function. To prevent
850 * deadlock, we need to release head_mutex before
851 * the decref.
852 */
853 PyObject *old_exc = p->async_exc;
854 Py_XINCREF(exc);
855 p->async_exc = exc;
856 HEAD_UNLOCK();
857 Py_XDECREF(old_exc);
858 _PyEval_SignalAsyncExc();
859 return 1;
860 }
861 }
862 HEAD_UNLOCK();
863 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000864}
865
866
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000867/* Routines for advanced debuggers, requested by David Beazley.
868 Don't use unless you know what you are doing! */
869
870PyInterpreterState *
871PyInterpreterState_Head(void)
872{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600873 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000874}
875
876PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700877PyInterpreterState_Main(void)
878{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600879 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700880}
881
882PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000883PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000885}
886
887PyThreadState *
888PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000890}
891
892PyThreadState *
893PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000895}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000896
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000897/* The implementation of sys._current_frames(). This is intended to be
898 called with the GIL held, as it will be when called via
899 sys._current_frames(). It's possible it would work fine even without
900 the GIL held, but haven't thought enough about that.
901*/
902PyObject *
903_PyThread_CurrentFrames(void)
904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 PyObject *result;
906 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 result = PyDict_New();
909 if (result == NULL)
910 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 /* for i in all interpreters:
913 * for t in all of i's thread states:
914 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200915 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 * need to grab head_mutex for the duration.
917 */
918 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600919 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 PyThreadState *t;
921 for (t = i->tstate_head; t != NULL; t = t->next) {
922 PyObject *id;
923 int stat;
924 struct _frame *frame = t->frame;
925 if (frame == NULL)
926 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200927 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 if (id == NULL)
929 goto Fail;
930 stat = PyDict_SetItem(result, id, (PyObject *)frame);
931 Py_DECREF(id);
932 if (stat < 0)
933 goto Fail;
934 }
935 }
936 HEAD_UNLOCK();
937 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000938
939 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 HEAD_UNLOCK();
941 Py_DECREF(result);
942 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000943}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000944
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000945/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000946
947/* Keep this as a static, as it is not reliable! It can only
948 ever be compared to the state for the *current* thread.
949 * If not equal, then it doesn't matter that the actual
950 value may change immediately after comparison, as it can't
951 possibly change to the current thread's state.
952 * If equal, then the current thread holds the lock, so the value can't
953 change until we yield the lock.
954*/
955static int
956PyThreadState_IsCurrent(PyThreadState *tstate)
957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 /* Must be the tstate for this thread */
959 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinner9204fb82018-10-30 15:13:17 +0100960 return tstate == PyThreadState_GET();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000961}
962
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000963/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000964 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000965*/
Tim Peters19717fa2004-10-09 17:38:29 +0000966void
967_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900970 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
971 Py_FatalError("Could not allocate TSS entry");
972 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600973 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900974 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000978}
979
Victor Stinner861d9ab2016-03-16 22:45:24 +0100980PyInterpreterState *
981_PyGILState_GetInterpreterStateUnsafe(void)
982{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600983 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100984}
985
Tim Peters19717fa2004-10-09 17:38:29 +0000986void
987_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000988{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900989 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600990 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000991}
992
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900993/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200994 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900995 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200996 */
997void
998_PyGILState_Reinit(void)
999{
Victor Stinner5d926472018-03-06 14:31:37 +01001000 /* Force default allocator, since _PyRuntimeState_Fini() must
1001 use the same allocator than this function. */
1002 PyMemAllocatorEx old_alloc;
1003 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1004
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001005 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +01001006
1007 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1008
1009 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001010 Py_FatalError("Can't initialize threads for interpreter");
Victor Stinner5d926472018-03-06 14:31:37 +01001011 }
1012
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001013 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001014 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
1015 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1016 Py_FatalError("Could not allocate TSS entry");
1017 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001018
Charles-François Natalia233df82011-11-22 19:49:51 +01001019 /* If the thread had an associated auto thread state, reassociate it with
1020 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001021 if (tstate &&
1022 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
1023 {
1024 Py_FatalError("Couldn't create autoTSSkey mapping");
1025 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001026}
1027
Michael W. Hudson188d4362005-06-20 16:52:57 +00001028/* When a thread state is created for a thread by some mechanism other than
1029 PyGILState_Ensure, it's important that the GILState machinery knows about
1030 it so it doesn't try to create another thread state for the thread (this is
1031 a better fix for SF bug #1010677 than the first one attempted).
1032*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001033static void
Michael W. Hudson188d4362005-06-20 16:52:57 +00001034_PyGILState_NoteThreadState(PyThreadState* tstate)
1035{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001036 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001037 threadstate created in Py_Initialize(). Don't do anything for now
1038 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001039 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001041
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001042 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 The only situation where you can legitimately have more than one
1045 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001046 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001047
Victor Stinner590cebe2013-12-13 11:08:56 +01001048 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1049 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001050
Victor Stinner590cebe2013-12-13 11:08:56 +01001051 The first thread state created for that given OS level thread will
1052 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001054 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
1055 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1056 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001057 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001058 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001059 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001060 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 /* PyGILState_Release must not try to delete this thread state. */
1063 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001064}
1065
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001066/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001067PyThreadState *
1068PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001069{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001070 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001072 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001073}
1074
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001075int
1076PyGILState_Check(void)
1077{
Victor Stinner8a1be612016-03-14 22:07:55 +01001078 PyThreadState *tstate;
1079
1080 if (!_PyGILState_check_enabled)
1081 return 1;
1082
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001083 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001084 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001085 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001086
Victor Stinner9204fb82018-10-30 15:13:17 +01001087 tstate = PyThreadState_GET();
Victor Stinner8a1be612016-03-14 22:07:55 +01001088 if (tstate == NULL)
1089 return 0;
1090
1091 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001092}
1093
Tim Peters19717fa2004-10-09 17:38:29 +00001094PyGILState_STATE
1095PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001096{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 int current;
1098 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001099 int need_init_threads = 0;
1100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 /* Note that we do not auto-init Python here - apart from
1102 potential races with 2 threads auto-initializing, pep-311
1103 spells out other issues. Embedders are expected to have
1104 called Py_Initialize() and usually PyEval_InitThreads().
1105 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001106 /* Py_Initialize() hasn't been called! */
1107 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001108
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001109 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001111 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001114 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 if (tcur == NULL)
1116 Py_FatalError("Couldn't create thread-state for new thread");
1117 /* This is our thread state! We'll need to delete it in the
1118 matching call to PyGILState_Release(). */
1119 tcur->gilstate_counter = 0;
1120 current = 0; /* new thread state is never current */
1121 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001122 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001124 }
1125
1126 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001128 }
1129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 /* Update our counter in the thread-state - no need for locks:
1131 - tcur will remain valid as we hold the GIL.
1132 - the counter is safe as we are the only thread "allowed"
1133 to modify this value
1134 */
1135 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001136
1137 if (need_init_threads) {
1138 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1139 called from a new thread for the first time, we need the create the
1140 GIL. */
1141 PyEval_InitThreads();
1142 }
1143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001145}
1146
Tim Peters19717fa2004-10-09 17:38:29 +00001147void
1148PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001149{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001150 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1151 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 if (tcur == NULL)
1153 Py_FatalError("auto-releasing thread-state, "
1154 "but no thread-state for this thread");
1155 /* We must hold the GIL and have our thread state current */
1156 /* XXX - remove the check - the assert should be fine,
1157 but while this is very new (April 2003), the extra check
1158 by release-only users can't hurt.
1159 */
1160 if (! PyThreadState_IsCurrent(tcur))
1161 Py_FatalError("This thread state must be current when releasing");
1162 assert(PyThreadState_IsCurrent(tcur));
1163 --tcur->gilstate_counter;
1164 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 /* If we're going to destroy this thread-state, we must
1167 * clear it while the GIL is held, as destructors may run.
1168 */
1169 if (tcur->gilstate_counter == 0) {
1170 /* can't have been locked when we created it */
1171 assert(oldstate == PyGILState_UNLOCKED);
1172 PyThreadState_Clear(tcur);
1173 /* Delete the thread-state. Note this releases the GIL too!
1174 * It's vital that the GIL be held here, to avoid shutdown
1175 * races; see bugs 225673 and 1061968 (that nasty bug has a
1176 * habit of coming back).
1177 */
1178 PyThreadState_DeleteCurrent();
1179 }
1180 /* Release the lock if necessary */
1181 else if (oldstate == PyGILState_UNLOCKED)
1182 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001183}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001184
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001185
Eric Snow7f8bfc92018-01-29 18:23:44 -07001186/**************************/
1187/* cross-interpreter data */
1188/**************************/
1189
1190/* cross-interpreter data */
1191
1192crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1193
1194/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1195 to keep the registry code separate. */
1196static crossinterpdatafunc
1197_lookup_getdata(PyObject *obj)
1198{
1199 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1200 if (getdata == NULL && PyErr_Occurred() == 0)
1201 PyErr_Format(PyExc_ValueError,
1202 "%S does not support cross-interpreter data", obj);
1203 return getdata;
1204}
1205
1206int
1207_PyObject_CheckCrossInterpreterData(PyObject *obj)
1208{
1209 crossinterpdatafunc getdata = _lookup_getdata(obj);
1210 if (getdata == NULL) {
1211 return -1;
1212 }
1213 return 0;
1214}
1215
1216static int
1217_check_xidata(_PyCrossInterpreterData *data)
1218{
1219 // data->data can be anything, including NULL, so we don't check it.
1220
1221 // data->obj may be NULL, so we don't check it.
1222
1223 if (data->interp < 0) {
1224 PyErr_SetString(PyExc_SystemError, "missing interp");
1225 return -1;
1226 }
1227
1228 if (data->new_object == NULL) {
1229 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1230 return -1;
1231 }
1232
1233 // data->free may be NULL, so we don't check it.
1234
1235 return 0;
1236}
1237
1238int
1239_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1240{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001241 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001242 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001243 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001244
1245 // Reset data before re-populating.
1246 *data = (_PyCrossInterpreterData){0};
1247 data->free = PyMem_RawFree; // Set a default that may be overridden.
1248
1249 // Call the "getdata" func for the object.
1250 Py_INCREF(obj);
1251 crossinterpdatafunc getdata = _lookup_getdata(obj);
1252 if (getdata == NULL) {
1253 Py_DECREF(obj);
1254 return -1;
1255 }
1256 int res = getdata(obj, data);
1257 Py_DECREF(obj);
1258 if (res != 0) {
1259 return -1;
1260 }
1261
1262 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001263 data->interp = interp->id;
1264 if (_check_xidata(data) != 0) {
1265 _PyCrossInterpreterData_Release(data);
1266 return -1;
1267 }
1268
1269 return 0;
1270}
1271
Eric Snow63799132018-06-01 18:45:20 -06001272static void
1273_release_xidata(void *arg)
1274{
1275 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1276 if (data->free != NULL) {
1277 data->free(data->data);
1278 }
1279 Py_XDECREF(data->obj);
1280}
1281
1282static void
1283_call_in_interpreter(PyInterpreterState *interp,
1284 void (*func)(void *), void *arg)
1285{
1286 /* We would use Py_AddPendingCall() if it weren't specific to the
1287 * main interpreter (see bpo-33608). In the meantime we take a
1288 * naive approach.
1289 */
1290 PyThreadState *save_tstate = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001291 if (interp != _PyInterpreterState_Get()) {
Eric Snow63799132018-06-01 18:45:20 -06001292 // XXX Using the "head" thread isn't strictly correct.
1293 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1294 // XXX Possible GILState issues?
1295 save_tstate = PyThreadState_Swap(tstate);
1296 }
1297
1298 func(arg);
1299
1300 // Switch back.
1301 if (save_tstate != NULL) {
1302 PyThreadState_Swap(save_tstate);
1303 }
1304}
1305
Eric Snow7f8bfc92018-01-29 18:23:44 -07001306void
1307_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1308{
1309 if (data->data == NULL && data->obj == NULL) {
1310 // Nothing to release!
1311 return;
1312 }
1313
1314 // Switch to the original interpreter.
1315 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1316 if (interp == NULL) {
1317 // The intepreter was already destroyed.
1318 if (data->free != NULL) {
1319 // XXX Someone leaked some memory...
1320 }
1321 return;
1322 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001323
Eric Snow7f8bfc92018-01-29 18:23:44 -07001324 // "Release" the data and/or the object.
Eric Snow63799132018-06-01 18:45:20 -06001325 _call_in_interpreter(interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001326}
1327
1328PyObject *
1329_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1330{
1331 return data->new_object(data);
1332}
1333
1334/* registry of {type -> crossinterpdatafunc} */
1335
1336/* For now we use a global registry of shareable classes. An
1337 alternative would be to add a tp_* slot for a class's
1338 crossinterpdatafunc. It would be simpler and more efficient. */
1339
1340static int
1341_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1342{
1343 // Note that we effectively replace already registered classes
1344 // rather than failing.
1345 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1346 if (newhead == NULL)
1347 return -1;
1348 newhead->cls = cls;
1349 newhead->getdata = getdata;
1350 newhead->next = _PyRuntime.xidregistry.head;
1351 _PyRuntime.xidregistry.head = newhead;
1352 return 0;
1353}
1354
1355static void _register_builtins_for_crossinterpreter_data(void);
1356
1357int
1358_PyCrossInterpreterData_Register_Class(PyTypeObject *cls,
1359 crossinterpdatafunc getdata)
1360{
1361 if (!PyType_Check(cls)) {
1362 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1363 return -1;
1364 }
1365 if (getdata == NULL) {
1366 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1367 return -1;
1368 }
1369
1370 // Make sure the class isn't ever deallocated.
1371 Py_INCREF((PyObject *)cls);
1372
1373 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1374 if (_PyRuntime.xidregistry.head == NULL) {
1375 _register_builtins_for_crossinterpreter_data();
1376 }
1377 int res = _register_xidata(cls, getdata);
1378 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1379 return res;
1380}
1381
Eric Snow6d2cd902018-05-16 15:04:57 -04001382/* Cross-interpreter objects are looked up by exact match on the class.
1383 We can reassess this policy when we move from a global registry to a
1384 tp_* slot. */
1385
Eric Snow7f8bfc92018-01-29 18:23:44 -07001386crossinterpdatafunc
1387_PyCrossInterpreterData_Lookup(PyObject *obj)
1388{
1389 PyObject *cls = PyObject_Type(obj);
1390 crossinterpdatafunc getdata = NULL;
1391 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1392 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1393 if (cur == NULL) {
1394 _register_builtins_for_crossinterpreter_data();
1395 cur = _PyRuntime.xidregistry.head;
1396 }
1397 for(; cur != NULL; cur = cur->next) {
1398 if (cur->cls == (PyTypeObject *)cls) {
1399 getdata = cur->getdata;
1400 break;
1401 }
1402 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001403 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001404 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1405 return getdata;
1406}
1407
1408/* cross-interpreter data for builtin types */
1409
Eric Snow6d2cd902018-05-16 15:04:57 -04001410struct _shared_bytes_data {
1411 char *bytes;
1412 Py_ssize_t len;
1413};
1414
Eric Snow7f8bfc92018-01-29 18:23:44 -07001415static PyObject *
1416_new_bytes_object(_PyCrossInterpreterData *data)
1417{
Eric Snow6d2cd902018-05-16 15:04:57 -04001418 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1419 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001420}
1421
1422static int
1423_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1424{
Eric Snow6d2cd902018-05-16 15:04:57 -04001425 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1426 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1427 return -1;
1428 }
1429 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001430 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001431 data->obj = obj; // Will be "released" (decref'ed) when data released.
1432 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001433 data->free = PyMem_Free;
1434 return 0;
1435}
1436
1437struct _shared_str_data {
1438 int kind;
1439 const void *buffer;
1440 Py_ssize_t len;
1441};
1442
1443static PyObject *
1444_new_str_object(_PyCrossInterpreterData *data)
1445{
1446 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1447 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1448}
1449
1450static int
1451_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1452{
1453 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1454 shared->kind = PyUnicode_KIND(obj);
1455 shared->buffer = PyUnicode_DATA(obj);
1456 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1457 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001458 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001459 data->obj = obj; // Will be "released" (decref'ed) when data released.
1460 data->new_object = _new_str_object;
1461 data->free = PyMem_Free;
1462 return 0;
1463}
1464
1465static PyObject *
1466_new_long_object(_PyCrossInterpreterData *data)
1467{
1468 return PyLong_FromLongLong((int64_t)(data->data));
1469}
1470
1471static int
1472_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1473{
1474 int64_t value = PyLong_AsLongLong(obj);
1475 if (value == -1 && PyErr_Occurred()) {
1476 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1477 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1478 }
1479 return -1;
1480 }
1481 data->data = (void *)value;
1482 data->obj = NULL;
1483 data->new_object = _new_long_object;
1484 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001485 return 0;
1486}
1487
1488static PyObject *
1489_new_none_object(_PyCrossInterpreterData *data)
1490{
1491 // XXX Singleton refcounts are problematic across interpreters...
1492 Py_INCREF(Py_None);
1493 return Py_None;
1494}
1495
1496static int
1497_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1498{
1499 data->data = NULL;
1500 // data->obj remains NULL
1501 data->new_object = _new_none_object;
1502 data->free = NULL; // There is nothing to free.
1503 return 0;
1504}
1505
1506static void
1507_register_builtins_for_crossinterpreter_data(void)
1508{
1509 // None
1510 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1511 Py_FatalError("could not register None for cross-interpreter sharing");
1512 }
1513
Eric Snow6d2cd902018-05-16 15:04:57 -04001514 // int
1515 if (_register_xidata(&PyLong_Type, _long_shared) != 0) {
1516 Py_FatalError("could not register int for cross-interpreter sharing");
1517 }
1518
Eric Snow7f8bfc92018-01-29 18:23:44 -07001519 // bytes
1520 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1521 Py_FatalError("could not register bytes for cross-interpreter sharing");
1522 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001523
1524 // str
1525 if (_register_xidata(&PyUnicode_Type, _str_shared) != 0) {
1526 Py_FatalError("could not register str for cross-interpreter sharing");
1527 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001528}
1529
1530
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001531#ifdef __cplusplus
1532}
1533#endif