blob: acb672bdd9b8e01343acb90f333e3532ba53ecec [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 Stinner621cebe2018-11-12 16:53:38 +01005#include "pycore_pymem.h"
6#include "pycore_pystate.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +00007
Victor Stinner9204fb82018-10-30 15:13:17 +01008#define _PyThreadState_SET(value) \
9 _Py_atomic_store_relaxed(&_PyRuntime.gilstate.tstate_current, \
10 (uintptr_t)(value))
Victor Stinnerb02ef712016-01-22 14:09:55 +010011
Victor Stinnerbfd316e2016-01-20 11:12:38 +010012
Tim Peters84705582004-10-10 02:47:33 +000013/* --------------------------------------------------------------------------
14CAUTION
15
Victor Stinner1a7425f2013-07-07 16:25:15 +020016Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
17number of these functions are advertised as safe to call when the GIL isn't
18held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
19debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
20to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000021-------------------------------------------------------------------------- */
22
Martin v. Löwisf0473d52001-07-18 16:17:16 +000023#ifdef HAVE_DLOPEN
24#ifdef HAVE_DLFCN_H
25#include <dlfcn.h>
26#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030027#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000028#define RTLD_LAZY 1
29#endif
30#endif
31
Benjamin Peterson43162b82012-04-13 11:58:27 -040032#ifdef __cplusplus
33extern "C" {
34#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000035
Victor Stinner5d39e042017-11-29 17:20:38 +010036static _PyInitError
37_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060038{
39 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010040
Eric Snow2ebc5ce2017-09-07 23:51:28 -060041 _PyGC_Initialize(&runtime->gc);
42 _PyEval_Initialize(&runtime->ceval);
Michael W. Hudson188d4362005-06-20 16:52:57 +000043
Eric Snow2ebc5ce2017-09-07 23:51:28 -060044 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080045
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090046 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
47 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080048 Py_tss_t initial = Py_tss_NEEDS_INIT;
49 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000050
Eric Snow2ebc5ce2017-09-07 23:51:28 -060051 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080052 if (runtime->interpreters.mutex == NULL) {
53 return _Py_INIT_ERR("Can't initialize threads for interpreter");
54 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060055 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070056
57 runtime->xidregistry.mutex = PyThread_allocate_lock();
58 if (runtime->xidregistry.mutex == NULL) {
59 return _Py_INIT_ERR("Can't initialize threads for cross-interpreter data registry");
60 }
61
Victor Stinnerf7e5b562017-11-15 15:48:08 -080062 return _Py_INIT_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060063}
Eric Snow05351c12017-09-05 21:43:08 -070064
Victor Stinner5d39e042017-11-29 17:20:38 +010065_PyInitError
66_PyRuntimeState_Init(_PyRuntimeState *runtime)
67{
68 /* Force default allocator, since _PyRuntimeState_Fini() must
69 use the same allocator than this function. */
70 PyMemAllocatorEx old_alloc;
71 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
72
73 _PyInitError err = _PyRuntimeState_Init_impl(runtime);
74
75 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
76 return err;
77}
78
Eric Snow2ebc5ce2017-09-07 23:51:28 -060079void
80_PyRuntimeState_Fini(_PyRuntimeState *runtime)
81{
Victor Stinner5d39e042017-11-29 17:20:38 +010082 /* Force the allocator used by _PyRuntimeState_Init(). */
83 PyMemAllocatorEx old_alloc;
84 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -080085
Eric Snow2ebc5ce2017-09-07 23:51:28 -060086 if (runtime->interpreters.mutex != NULL) {
87 PyThread_free_lock(runtime->interpreters.mutex);
88 runtime->interpreters.mutex = NULL;
89 }
Victor Stinnerccb04422017-11-16 03:20:31 -080090
91 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060092}
93
94#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
95 WAIT_LOCK)
96#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -070097
Michael W. Hudson188d4362005-06-20 16:52:57 +000098static void _PyGILState_NoteThreadState(PyThreadState* tstate);
99
Victor Stinnera7368ac2017-11-15 18:11:45 -0800100_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600101_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700102{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600103 runtime->interpreters.next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100104
105 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
106 Create a new mutex if needed. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600107 if (runtime->interpreters.mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100108 /* Force default allocator, since _PyRuntimeState_Fini() must
109 use the same allocator than this function. */
110 PyMemAllocatorEx old_alloc;
111 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
112
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600113 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100114
115 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
116
Victor Stinnera7368ac2017-11-15 18:11:45 -0800117 if (runtime->interpreters.mutex == NULL) {
118 return _Py_INIT_ERR("Can't initialize threads for interpreter");
119 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600120 }
Victor Stinner5d926472018-03-06 14:31:37 +0100121
Victor Stinnera7368ac2017-11-15 18:11:45 -0800122 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700123}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000124
125PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000126PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200129 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000130
Victor Stinnerd4341102017-11-23 00:12:09 +0100131 if (interp == NULL) {
132 return NULL;
133 }
134
Eric Snow4c6955e2018-02-16 18:53:40 -0700135 interp->id_refcount = -1;
136 interp->id_mutex = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100137 interp->modules = NULL;
138 interp->modules_by_index = NULL;
139 interp->sysdict = NULL;
140 interp->builtins = NULL;
141 interp->builtins_copy = NULL;
142 interp->tstate_head = NULL;
143 interp->check_interval = 100;
144 interp->num_threads = 0;
145 interp->pythread_stacksize = 0;
146 interp->codec_search_path = NULL;
147 interp->codec_search_cache = NULL;
148 interp->codec_error_registry = NULL;
149 interp->codecs_initialized = 0;
150 interp->fscodec_initialized = 0;
151 interp->core_config = _PyCoreConfig_INIT;
152 interp->config = _PyMainInterpreterConfig_INIT;
153 interp->importlib = NULL;
154 interp->import_func = NULL;
155 interp->eval_frame = _PyEval_EvalFrameDefault;
156 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000157#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300158#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100159 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000160#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100161 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000162#endif
163#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200164#ifdef HAVE_FORK
Victor Stinnerd4341102017-11-23 00:12:09 +0100165 interp->before_forkers = NULL;
166 interp->after_forkers_parent = NULL;
167 interp->after_forkers_child = NULL;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200168#endif
Marcel Plch776407f2017-12-20 11:17:58 +0100169 interp->pyexitfunc = NULL;
170 interp->pyexitmodule = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000171
Victor Stinnerd4341102017-11-23 00:12:09 +0100172 HEAD_LOCK();
Victor Stinnerd4341102017-11-23 00:12:09 +0100173 if (_PyRuntime.interpreters.next_id < 0) {
174 /* overflow or Py_Initialize() not called! */
175 PyErr_SetString(PyExc_RuntimeError,
176 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100177 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100178 interp = NULL;
179 } else {
180 interp->id = _PyRuntime.interpreters.next_id;
181 _PyRuntime.interpreters.next_id += 1;
Pablo Galindo95d630e2018-08-31 22:49:29 +0100182 interp->next = _PyRuntime.interpreters.head;
183 if (_PyRuntime.interpreters.main == NULL) {
184 _PyRuntime.interpreters.main = interp;
185 }
186 _PyRuntime.interpreters.head = interp;
Victor Stinnerd4341102017-11-23 00:12:09 +0100187 }
188 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000189
Pablo Galindo95d630e2018-08-31 22:49:29 +0100190 if (interp == NULL) {
191 return NULL;
192 }
193
Yury Selivanovf23746a2018-01-22 19:11:18 -0500194 interp->tstate_next_unique_id = 0;
195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000197}
198
199
200void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000201PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 PyThreadState *p;
204 HEAD_LOCK();
205 for (p = interp->tstate_head; p != NULL; p = p->next)
206 PyThreadState_Clear(p);
207 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100208 _PyCoreConfig_Clear(&interp->core_config);
209 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 Py_CLEAR(interp->codec_search_path);
211 Py_CLEAR(interp->codec_search_cache);
212 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700213 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 Py_CLEAR(interp->sysdict);
216 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200217 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400218 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300219 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200220#ifdef HAVE_FORK
221 Py_CLEAR(interp->before_forkers);
222 Py_CLEAR(interp->after_forkers_parent);
223 Py_CLEAR(interp->after_forkers_child);
224#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000225}
226
227
228static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000229zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 PyThreadState *p;
232 /* No need to lock the mutex here because this should only happen
233 when the threads are all really dead (XXX famous last words). */
234 while ((p = interp->tstate_head) != NULL) {
235 PyThreadState_Delete(p);
236 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000237}
238
239
240void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000241PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 PyInterpreterState **p;
244 zapthreads(interp);
245 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600246 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 if (*p == NULL)
248 Py_FatalError(
249 "PyInterpreterState_Delete: invalid interp");
250 if (*p == interp)
251 break;
252 }
253 if (interp->tstate_head != NULL)
254 Py_FatalError("PyInterpreterState_Delete: remaining threads");
255 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600256 if (_PyRuntime.interpreters.main == interp) {
257 _PyRuntime.interpreters.main = NULL;
258 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700259 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
260 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 HEAD_UNLOCK();
Eric Snow4c6955e2018-02-16 18:53:40 -0700262 if (interp->id_mutex != NULL) {
263 PyThread_free_lock(interp->id_mutex);
264 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200265 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000266}
267
268
Eric Snow59032962018-09-14 14:17:20 -0700269/*
270 * Delete all interpreter states except the main interpreter. If there
271 * is a current interpreter state, it *must* be the main interpreter.
272 */
273void
274_PyInterpreterState_DeleteExceptMain()
275{
276 PyThreadState *tstate = PyThreadState_Swap(NULL);
277 if (tstate != NULL && tstate->interp != _PyRuntime.interpreters.main) {
278 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
279 }
280
281 HEAD_LOCK();
282 PyInterpreterState *interp = _PyRuntime.interpreters.head;
283 _PyRuntime.interpreters.head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100284 while (interp != NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700285 if (interp == _PyRuntime.interpreters.main) {
286 _PyRuntime.interpreters.main->next = NULL;
287 _PyRuntime.interpreters.head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100288 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700289 continue;
290 }
291
292 PyInterpreterState_Clear(interp); // XXX must activate?
293 zapthreads(interp);
294 if (interp->id_mutex != NULL) {
295 PyThread_free_lock(interp->id_mutex);
296 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100297 PyInterpreterState *prev_interp = interp;
298 interp = interp->next;
299 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700300 }
301 HEAD_UNLOCK();
302
303 if (_PyRuntime.interpreters.head == NULL) {
304 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
305 }
306 PyThreadState_Swap(tstate);
307}
308
309
Victor Stinnercaba55b2018-08-03 15:33:52 +0200310PyInterpreterState *
311_PyInterpreterState_Get(void)
312{
Victor Stinner50b48572018-11-01 01:51:40 +0100313 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200314 if (tstate == NULL) {
315 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
316 }
317 PyInterpreterState *interp = tstate->interp;
318 if (interp == NULL) {
319 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
320 }
321 return interp;
322}
323
324
Eric Snowe3774162017-05-22 19:46:40 -0700325int64_t
326PyInterpreterState_GetID(PyInterpreterState *interp)
327{
328 if (interp == NULL) {
329 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
330 return -1;
331 }
332 return interp->id;
333}
334
335
Eric Snow7f8bfc92018-01-29 18:23:44 -0700336PyInterpreterState *
337_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
338{
339 if (requested_id < 0)
340 goto error;
341
342 PyInterpreterState *interp = PyInterpreterState_Head();
343 while (interp != NULL) {
344 PY_INT64_T id = PyInterpreterState_GetID(interp);
345 if (id < 0)
346 return NULL;
347 if (requested_id == id)
348 return interp;
349 interp = PyInterpreterState_Next(interp);
350 }
351
352error:
353 PyErr_Format(PyExc_RuntimeError,
354 "unrecognized interpreter ID %lld", requested_id);
355 return NULL;
356}
357
Eric Snow4c6955e2018-02-16 18:53:40 -0700358
359int
360_PyInterpreterState_IDInitref(PyInterpreterState *interp)
361{
362 if (interp->id_mutex != NULL) {
363 return 0;
364 }
365 interp->id_mutex = PyThread_allocate_lock();
366 if (interp->id_mutex == NULL) {
367 PyErr_SetString(PyExc_RuntimeError,
368 "failed to create init interpreter ID mutex");
369 return -1;
370 }
371 interp->id_refcount = 0;
372 return 0;
373}
374
375
376void
377_PyInterpreterState_IDIncref(PyInterpreterState *interp)
378{
379 if (interp->id_mutex == NULL) {
380 return;
381 }
382 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
383 interp->id_refcount += 1;
384 PyThread_release_lock(interp->id_mutex);
385}
386
387
388void
389_PyInterpreterState_IDDecref(PyInterpreterState *interp)
390{
391 if (interp->id_mutex == NULL) {
392 return;
393 }
394 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
395 assert(interp->id_refcount != 0);
396 interp->id_refcount -= 1;
397 int64_t refcount = interp->id_refcount;
398 PyThread_release_lock(interp->id_mutex);
399
400 if (refcount == 0) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700401 // XXX Using the "head" thread isn't strictly correct.
402 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
403 // XXX Possible GILState issues?
404 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700405 Py_EndInterpreter(tstate);
406 PyThreadState_Swap(save_tstate);
407 }
408}
409
410
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000411/* Default implementation for _PyThreadState_GetFrame */
412static struct _frame *
413threadstate_getframe(PyThreadState *self)
414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000416}
417
Victor Stinner45b9be52010-03-03 23:28:07 +0000418static PyThreadState *
419new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000420{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200421 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 if (_PyThreadState_GetFrame == NULL)
424 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 if (tstate != NULL) {
427 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 tstate->frame = NULL;
430 tstate->recursion_depth = 0;
431 tstate->overflowed = 0;
432 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700433 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 tstate->tracing = 0;
435 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 tstate->gilstate_counter = 0;
437 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 tstate->curexc_type = NULL;
443 tstate->curexc_value = NULL;
444 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000445
Mark Shannonae3087c2017-10-22 22:41:51 +0100446 tstate->exc_state.exc_type = NULL;
447 tstate->exc_state.exc_value = NULL;
448 tstate->exc_state.exc_traceback = NULL;
449 tstate->exc_state.previous_item = NULL;
450 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 tstate->c_profilefunc = NULL;
453 tstate->c_tracefunc = NULL;
454 tstate->c_profileobj = NULL;
455 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000456
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200457 tstate->trash_delete_nesting = 0;
458 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200459 tstate->on_delete = NULL;
460 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200461
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800462 tstate->coroutine_origin_tracking_depth = 0;
463
Yury Selivanov75445082015-05-11 22:57:16 -0400464 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400465 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400466
Yury Selivanoveb636452016-09-08 22:01:51 -0700467 tstate->async_gen_firstiter = NULL;
468 tstate->async_gen_finalizer = NULL;
469
Yury Selivanovf23746a2018-01-22 19:11:18 -0500470 tstate->context = NULL;
471 tstate->context_ver = 1;
472
473 tstate->id = ++interp->tstate_next_unique_id;
474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 if (init)
476 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200479 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200481 if (tstate->next)
482 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 interp->tstate_head = tstate;
484 HEAD_UNLOCK();
485 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000488}
489
Victor Stinner45b9be52010-03-03 23:28:07 +0000490PyThreadState *
491PyThreadState_New(PyInterpreterState *interp)
492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000494}
495
496PyThreadState *
497_PyThreadState_Prealloc(PyInterpreterState *interp)
498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000500}
501
502void
503_PyThreadState_Init(PyThreadState *tstate)
504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000506}
507
Martin v. Löwis1a214512008-06-11 05:26:20 +0000508PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200509PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000510{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200511 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100512 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000514 if (module->m_slots) {
515 return NULL;
516 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 if (index == 0)
518 return NULL;
519 if (state->modules_by_index == NULL)
520 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200521 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 return NULL;
523 res = PyList_GET_ITEM(state->modules_by_index, index);
524 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000525}
526
527int
528_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
529{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000530 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300531 if (!def) {
532 assert(PyErr_Occurred());
533 return -1;
534 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000535 if (def->m_slots) {
536 PyErr_SetString(PyExc_SystemError,
537 "PyState_AddModule called on module with slots");
538 return -1;
539 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100540 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 if (!state->modules_by_index) {
542 state->modules_by_index = PyList_New(0);
543 if (!state->modules_by_index)
544 return -1;
545 }
546 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
547 if (PyList_Append(state->modules_by_index, Py_None) < 0)
548 return -1;
549 Py_INCREF(module);
550 return PyList_SetItem(state->modules_by_index,
551 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000552}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000553
Martin v. Löwis7800f752012-06-22 12:20:55 +0200554int
555PyState_AddModule(PyObject* module, struct PyModuleDef* def)
556{
557 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100558 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200559 if (!def) {
560 Py_FatalError("PyState_AddModule: Module Definition is NULL");
561 return -1;
562 }
563 index = def->m_base.m_index;
564 if (state->modules_by_index) {
565 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
566 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
567 Py_FatalError("PyState_AddModule: Module already added!");
568 return -1;
569 }
570 }
571 }
572 return _PyState_AddModule(module, def);
573}
574
575int
576PyState_RemoveModule(struct PyModuleDef* def)
577{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000578 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200579 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000580 if (def->m_slots) {
581 PyErr_SetString(PyExc_SystemError,
582 "PyState_RemoveModule called on module with slots");
583 return -1;
584 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100585 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200586 if (index == 0) {
587 Py_FatalError("PyState_RemoveModule: Module index invalid.");
588 return -1;
589 }
590 if (state->modules_by_index == NULL) {
591 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
592 return -1;
593 }
594 if (index > PyList_GET_SIZE(state->modules_by_index)) {
595 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
596 return -1;
597 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700598 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200599 return PyList_SetItem(state->modules_by_index, index, Py_None);
600}
601
Antoine Pitrou40322e62013-08-11 00:30:09 +0200602/* used by import.c:PyImport_Cleanup */
603void
604_PyState_ClearModules(void)
605{
Victor Stinner9204fb82018-10-30 15:13:17 +0100606 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200607 if (state->modules_by_index) {
608 Py_ssize_t i;
609 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
610 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
611 if (PyModule_Check(m)) {
612 /* cleanup the saved copy of module dicts */
613 PyModuleDef *md = PyModule_GetDef(m);
614 if (md)
615 Py_CLEAR(md->m_base.m_copy);
616 }
617 }
618 /* Setting modules_by_index to NULL could be dangerous, so we
619 clear the list instead. */
620 if (PyList_SetSlice(state->modules_by_index,
621 0, PyList_GET_SIZE(state->modules_by_index),
622 NULL))
623 PyErr_WriteUnraisable(state->modules_by_index);
624 }
625}
626
Guido van Rossuma027efa1997-05-05 20:56:21 +0000627void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000628PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000629{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200630 int verbose = tstate->interp->core_config.verbose;
631
632 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 fprintf(stderr,
634 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 Py_CLEAR(tstate->dict);
639 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 Py_CLEAR(tstate->curexc_type);
642 Py_CLEAR(tstate->curexc_value);
643 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000644
Mark Shannonae3087c2017-10-22 22:41:51 +0100645 Py_CLEAR(tstate->exc_state.exc_type);
646 Py_CLEAR(tstate->exc_state.exc_value);
647 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300648
Mark Shannonae3087c2017-10-22 22:41:51 +0100649 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200650 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100651 fprintf(stderr,
652 "PyThreadState_Clear: warning: thread still has a generator\n");
653 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 tstate->c_profilefunc = NULL;
656 tstate->c_tracefunc = NULL;
657 Py_CLEAR(tstate->c_profileobj);
658 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400659
660 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700661 Py_CLEAR(tstate->async_gen_firstiter);
662 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500663
664 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000665}
666
667
Guido van Rossum29757862001-01-23 01:46:06 +0000668/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
669static void
670tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 if (tstate == NULL)
674 Py_FatalError("PyThreadState_Delete: NULL tstate");
675 interp = tstate->interp;
676 if (interp == NULL)
677 Py_FatalError("PyThreadState_Delete: NULL interp");
678 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200679 if (tstate->prev)
680 tstate->prev->next = tstate->next;
681 else
682 interp->tstate_head = tstate->next;
683 if (tstate->next)
684 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200686 if (tstate->on_delete != NULL) {
687 tstate->on_delete(tstate->on_delete_data);
688 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200689 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000690}
691
692
Guido van Rossum29757862001-01-23 01:46:06 +0000693void
694PyThreadState_Delete(PyThreadState *tstate)
695{
Victor Stinner50b48572018-11-01 01:51:40 +0100696 if (tstate == _PyThreadState_GET())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600698 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900699 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600700 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900701 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600702 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200703 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000704}
705
706
Guido van Rossum29757862001-01-23 01:46:06 +0000707void
708PyThreadState_DeleteCurrent()
709{
Victor Stinner50b48572018-11-01 01:51:40 +0100710 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 if (tstate == NULL)
712 Py_FatalError(
713 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100714 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600715 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900716 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600717 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900718 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600719 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100720 _PyThreadState_SET(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000722}
Guido van Rossum29757862001-01-23 01:46:06 +0000723
724
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200725/*
726 * Delete all thread states except the one passed as argument.
727 * Note that, if there is a current thread state, it *must* be the one
728 * passed as argument. Also, this won't touch any other interpreters
729 * than the current one, since we don't know which thread state should
730 * be kept in those other interpreteres.
731 */
732void
733_PyThreadState_DeleteExcept(PyThreadState *tstate)
734{
735 PyInterpreterState *interp = tstate->interp;
736 PyThreadState *p, *next, *garbage;
737 HEAD_LOCK();
738 /* Remove all thread states, except tstate, from the linked list of
739 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200740 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200741 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200742 if (garbage == tstate)
743 garbage = tstate->next;
744 if (tstate->prev)
745 tstate->prev->next = tstate->next;
746 if (tstate->next)
747 tstate->next->prev = tstate->prev;
748 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200749 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200750 HEAD_UNLOCK();
751 /* Clear and deallocate all stale thread states. Even if this
752 executes Python code, we should be safe since it executes
753 in the current thread, not one of the stale threads. */
754 for (p = garbage; p; p = next) {
755 next = p->next;
756 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200757 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200758 }
759}
760
761
Guido van Rossuma027efa1997-05-05 20:56:21 +0000762PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100763_PyThreadState_UncheckedGet(void)
764{
Victor Stinner50b48572018-11-01 01:51:40 +0100765 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100766}
767
768
769PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000770PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000771{
Victor Stinner50b48572018-11-01 01:51:40 +0100772 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 if (tstate == NULL)
774 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000777}
778
779
780PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000781PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000782{
Victor Stinner50b48572018-11-01 01:51:40 +0100783 PyThreadState *oldts = _PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000784
Victor Stinner9204fb82018-10-30 15:13:17 +0100785 _PyThreadState_SET(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 /* It should not be possible for more than one thread state
787 to be used for a thread. Check this the best we can in debug
788 builds.
789 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200790#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (newts) {
792 /* This can be called from PyEval_RestoreThread(). Similar
793 to it, we need to ensure errno doesn't change.
794 */
795 int err = errno;
796 PyThreadState *check = PyGILState_GetThisThreadState();
797 if (check && check->interp == newts->interp && check != newts)
798 Py_FatalError("Invalid thread state for this thread");
799 errno = err;
800 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000801#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000803}
Guido van Rossumede04391998-04-10 20:18:25 +0000804
805/* An extension mechanism to store arbitrary additional per-thread state.
806 PyThreadState_GetDict() returns a dictionary that can be used to hold such
807 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000808 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
809 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000810
811PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000812PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000813{
Victor Stinner50b48572018-11-01 01:51:40 +0100814 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 if (tstate == NULL)
816 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 if (tstate->dict == NULL) {
819 PyObject *d;
820 tstate->dict = d = PyDict_New();
821 if (d == NULL)
822 PyErr_Clear();
823 }
824 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000825}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000826
827
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000828/* Asynchronously raise an exception in a thread.
829 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000830 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000831 to call this, or use ctypes. Must be called with the GIL held.
832 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
833 match any known thread id). Can be called with exc=NULL to clear an
834 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000835
836int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200837PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
838{
Victor Stinner9204fb82018-10-30 15:13:17 +0100839 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 /* Although the GIL is held, a few C API functions can be called
843 * without the GIL held, and in particular some that create and
844 * destroy thread and interpreter states. Those can mutate the
845 * list of thread states we're traversing, so to prevent that we lock
846 * head_mutex for the duration.
847 */
848 HEAD_LOCK();
849 for (p = interp->tstate_head; p != NULL; p = p->next) {
850 if (p->thread_id == id) {
851 /* Tricky: we need to decref the current value
852 * (if any) in p->async_exc, but that can in turn
853 * allow arbitrary Python code to run, including
854 * perhaps calls to this function. To prevent
855 * deadlock, we need to release head_mutex before
856 * the decref.
857 */
858 PyObject *old_exc = p->async_exc;
859 Py_XINCREF(exc);
860 p->async_exc = exc;
861 HEAD_UNLOCK();
862 Py_XDECREF(old_exc);
863 _PyEval_SignalAsyncExc();
864 return 1;
865 }
866 }
867 HEAD_UNLOCK();
868 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000869}
870
871
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000872/* Routines for advanced debuggers, requested by David Beazley.
873 Don't use unless you know what you are doing! */
874
875PyInterpreterState *
876PyInterpreterState_Head(void)
877{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600878 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000879}
880
881PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700882PyInterpreterState_Main(void)
883{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600884 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700885}
886
887PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000888PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000890}
891
892PyThreadState *
893PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000895}
896
897PyThreadState *
898PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000900}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000901
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000902/* The implementation of sys._current_frames(). This is intended to be
903 called with the GIL held, as it will be when called via
904 sys._current_frames(). It's possible it would work fine even without
905 the GIL held, but haven't thought enough about that.
906*/
907PyObject *
908_PyThread_CurrentFrames(void)
909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 PyObject *result;
911 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 result = PyDict_New();
914 if (result == NULL)
915 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 /* for i in all interpreters:
918 * for t in all of i's thread states:
919 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200920 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 * need to grab head_mutex for the duration.
922 */
923 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600924 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 PyThreadState *t;
926 for (t = i->tstate_head; t != NULL; t = t->next) {
927 PyObject *id;
928 int stat;
929 struct _frame *frame = t->frame;
930 if (frame == NULL)
931 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200932 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 if (id == NULL)
934 goto Fail;
935 stat = PyDict_SetItem(result, id, (PyObject *)frame);
936 Py_DECREF(id);
937 if (stat < 0)
938 goto Fail;
939 }
940 }
941 HEAD_UNLOCK();
942 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000943
944 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 HEAD_UNLOCK();
946 Py_DECREF(result);
947 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000948}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000949
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000950/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000951
952/* Keep this as a static, as it is not reliable! It can only
953 ever be compared to the state for the *current* thread.
954 * If not equal, then it doesn't matter that the actual
955 value may change immediately after comparison, as it can't
956 possibly change to the current thread's state.
957 * If equal, then the current thread holds the lock, so the value can't
958 change until we yield the lock.
959*/
960static int
961PyThreadState_IsCurrent(PyThreadState *tstate)
962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 /* Must be the tstate for this thread */
964 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinner50b48572018-11-01 01:51:40 +0100965 return tstate == _PyThreadState_GET();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000966}
967
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000968/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000969 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000970*/
Tim Peters19717fa2004-10-09 17:38:29 +0000971void
972_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900975 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
976 Py_FatalError("Could not allocate TSS entry");
977 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600978 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900979 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000983}
984
Victor Stinner861d9ab2016-03-16 22:45:24 +0100985PyInterpreterState *
986_PyGILState_GetInterpreterStateUnsafe(void)
987{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600988 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100989}
990
Tim Peters19717fa2004-10-09 17:38:29 +0000991void
992_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000993{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900994 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600995 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000996}
997
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900998/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200999 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001000 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001001 */
1002void
1003_PyGILState_Reinit(void)
1004{
Victor Stinner5d926472018-03-06 14:31:37 +01001005 /* Force default allocator, since _PyRuntimeState_Fini() must
1006 use the same allocator than this function. */
1007 PyMemAllocatorEx old_alloc;
1008 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1009
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001010 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +01001011
1012 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1013
1014 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001015 Py_FatalError("Can't initialize threads for interpreter");
Victor Stinner5d926472018-03-06 14:31:37 +01001016 }
1017
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001018 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001019 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
1020 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1021 Py_FatalError("Could not allocate TSS entry");
1022 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001023
Charles-François Natalia233df82011-11-22 19:49:51 +01001024 /* If the thread had an associated auto thread state, reassociate it with
1025 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001026 if (tstate &&
1027 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
1028 {
1029 Py_FatalError("Couldn't create autoTSSkey mapping");
1030 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001031}
1032
Michael W. Hudson188d4362005-06-20 16:52:57 +00001033/* When a thread state is created for a thread by some mechanism other than
1034 PyGILState_Ensure, it's important that the GILState machinery knows about
1035 it so it doesn't try to create another thread state for the thread (this is
1036 a better fix for SF bug #1010677 than the first one attempted).
1037*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001038static void
Michael W. Hudson188d4362005-06-20 16:52:57 +00001039_PyGILState_NoteThreadState(PyThreadState* tstate)
1040{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001041 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001042 threadstate created in Py_Initialize(). Don't do anything for now
1043 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001044 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001046
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001047 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 The only situation where you can legitimately have more than one
1050 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001051 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001052
Victor Stinner590cebe2013-12-13 11:08:56 +01001053 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1054 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001055
Victor Stinner590cebe2013-12-13 11:08:56 +01001056 The first thread state created for that given OS level thread will
1057 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001059 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
1060 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1061 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001062 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001063 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001064 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001065 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 /* PyGILState_Release must not try to delete this thread state. */
1068 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001069}
1070
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001071/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001072PyThreadState *
1073PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001074{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001075 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001077 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001078}
1079
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001080int
1081PyGILState_Check(void)
1082{
Victor Stinner8a1be612016-03-14 22:07:55 +01001083 PyThreadState *tstate;
1084
1085 if (!_PyGILState_check_enabled)
1086 return 1;
1087
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001088 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001089 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001090 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001091
Victor Stinner50b48572018-11-01 01:51:40 +01001092 tstate = _PyThreadState_GET();
Victor Stinner8a1be612016-03-14 22:07:55 +01001093 if (tstate == NULL)
1094 return 0;
1095
1096 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001097}
1098
Tim Peters19717fa2004-10-09 17:38:29 +00001099PyGILState_STATE
1100PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 int current;
1103 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001104 int need_init_threads = 0;
1105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 /* Note that we do not auto-init Python here - apart from
1107 potential races with 2 threads auto-initializing, pep-311
1108 spells out other issues. Embedders are expected to have
1109 called Py_Initialize() and usually PyEval_InitThreads().
1110 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001111 /* Py_Initialize() hasn't been called! */
1112 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001113
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001114 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001116 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001119 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 if (tcur == NULL)
1121 Py_FatalError("Couldn't create thread-state for new thread");
1122 /* This is our thread state! We'll need to delete it in the
1123 matching call to PyGILState_Release(). */
1124 tcur->gilstate_counter = 0;
1125 current = 0; /* new thread state is never current */
1126 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001127 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001129 }
1130
1131 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001133 }
1134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 /* Update our counter in the thread-state - no need for locks:
1136 - tcur will remain valid as we hold the GIL.
1137 - the counter is safe as we are the only thread "allowed"
1138 to modify this value
1139 */
1140 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001141
1142 if (need_init_threads) {
1143 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1144 called from a new thread for the first time, we need the create the
1145 GIL. */
1146 PyEval_InitThreads();
1147 }
1148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001150}
1151
Tim Peters19717fa2004-10-09 17:38:29 +00001152void
1153PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001154{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001155 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1156 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 if (tcur == NULL)
1158 Py_FatalError("auto-releasing thread-state, "
1159 "but no thread-state for this thread");
1160 /* We must hold the GIL and have our thread state current */
1161 /* XXX - remove the check - the assert should be fine,
1162 but while this is very new (April 2003), the extra check
1163 by release-only users can't hurt.
1164 */
1165 if (! PyThreadState_IsCurrent(tcur))
1166 Py_FatalError("This thread state must be current when releasing");
1167 assert(PyThreadState_IsCurrent(tcur));
1168 --tcur->gilstate_counter;
1169 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 /* If we're going to destroy this thread-state, we must
1172 * clear it while the GIL is held, as destructors may run.
1173 */
1174 if (tcur->gilstate_counter == 0) {
1175 /* can't have been locked when we created it */
1176 assert(oldstate == PyGILState_UNLOCKED);
1177 PyThreadState_Clear(tcur);
1178 /* Delete the thread-state. Note this releases the GIL too!
1179 * It's vital that the GIL be held here, to avoid shutdown
1180 * races; see bugs 225673 and 1061968 (that nasty bug has a
1181 * habit of coming back).
1182 */
1183 PyThreadState_DeleteCurrent();
1184 }
1185 /* Release the lock if necessary */
1186 else if (oldstate == PyGILState_UNLOCKED)
1187 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001188}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001189
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001190
Eric Snow7f8bfc92018-01-29 18:23:44 -07001191/**************************/
1192/* cross-interpreter data */
1193/**************************/
1194
1195/* cross-interpreter data */
1196
1197crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1198
1199/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1200 to keep the registry code separate. */
1201static crossinterpdatafunc
1202_lookup_getdata(PyObject *obj)
1203{
1204 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1205 if (getdata == NULL && PyErr_Occurred() == 0)
1206 PyErr_Format(PyExc_ValueError,
1207 "%S does not support cross-interpreter data", obj);
1208 return getdata;
1209}
1210
1211int
1212_PyObject_CheckCrossInterpreterData(PyObject *obj)
1213{
1214 crossinterpdatafunc getdata = _lookup_getdata(obj);
1215 if (getdata == NULL) {
1216 return -1;
1217 }
1218 return 0;
1219}
1220
1221static int
1222_check_xidata(_PyCrossInterpreterData *data)
1223{
1224 // data->data can be anything, including NULL, so we don't check it.
1225
1226 // data->obj may be NULL, so we don't check it.
1227
1228 if (data->interp < 0) {
1229 PyErr_SetString(PyExc_SystemError, "missing interp");
1230 return -1;
1231 }
1232
1233 if (data->new_object == NULL) {
1234 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1235 return -1;
1236 }
1237
1238 // data->free may be NULL, so we don't check it.
1239
1240 return 0;
1241}
1242
1243int
1244_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1245{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001246 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001247 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001248 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001249
1250 // Reset data before re-populating.
1251 *data = (_PyCrossInterpreterData){0};
1252 data->free = PyMem_RawFree; // Set a default that may be overridden.
1253
1254 // Call the "getdata" func for the object.
1255 Py_INCREF(obj);
1256 crossinterpdatafunc getdata = _lookup_getdata(obj);
1257 if (getdata == NULL) {
1258 Py_DECREF(obj);
1259 return -1;
1260 }
1261 int res = getdata(obj, data);
1262 Py_DECREF(obj);
1263 if (res != 0) {
1264 return -1;
1265 }
1266
1267 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001268 data->interp = interp->id;
1269 if (_check_xidata(data) != 0) {
1270 _PyCrossInterpreterData_Release(data);
1271 return -1;
1272 }
1273
1274 return 0;
1275}
1276
Eric Snow63799132018-06-01 18:45:20 -06001277static void
1278_release_xidata(void *arg)
1279{
1280 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1281 if (data->free != NULL) {
1282 data->free(data->data);
1283 }
1284 Py_XDECREF(data->obj);
1285}
1286
1287static void
1288_call_in_interpreter(PyInterpreterState *interp,
1289 void (*func)(void *), void *arg)
1290{
1291 /* We would use Py_AddPendingCall() if it weren't specific to the
1292 * main interpreter (see bpo-33608). In the meantime we take a
1293 * naive approach.
1294 */
1295 PyThreadState *save_tstate = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001296 if (interp != _PyInterpreterState_Get()) {
Eric Snow63799132018-06-01 18:45:20 -06001297 // XXX Using the "head" thread isn't strictly correct.
1298 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1299 // XXX Possible GILState issues?
1300 save_tstate = PyThreadState_Swap(tstate);
1301 }
1302
1303 func(arg);
1304
1305 // Switch back.
1306 if (save_tstate != NULL) {
1307 PyThreadState_Swap(save_tstate);
1308 }
1309}
1310
Eric Snow7f8bfc92018-01-29 18:23:44 -07001311void
1312_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1313{
1314 if (data->data == NULL && data->obj == NULL) {
1315 // Nothing to release!
1316 return;
1317 }
1318
1319 // Switch to the original interpreter.
1320 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1321 if (interp == NULL) {
1322 // The intepreter was already destroyed.
1323 if (data->free != NULL) {
1324 // XXX Someone leaked some memory...
1325 }
1326 return;
1327 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001328
Eric Snow7f8bfc92018-01-29 18:23:44 -07001329 // "Release" the data and/or the object.
Eric Snow63799132018-06-01 18:45:20 -06001330 _call_in_interpreter(interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001331}
1332
1333PyObject *
1334_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1335{
1336 return data->new_object(data);
1337}
1338
1339/* registry of {type -> crossinterpdatafunc} */
1340
1341/* For now we use a global registry of shareable classes. An
1342 alternative would be to add a tp_* slot for a class's
1343 crossinterpdatafunc. It would be simpler and more efficient. */
1344
1345static int
1346_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1347{
1348 // Note that we effectively replace already registered classes
1349 // rather than failing.
1350 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1351 if (newhead == NULL)
1352 return -1;
1353 newhead->cls = cls;
1354 newhead->getdata = getdata;
1355 newhead->next = _PyRuntime.xidregistry.head;
1356 _PyRuntime.xidregistry.head = newhead;
1357 return 0;
1358}
1359
1360static void _register_builtins_for_crossinterpreter_data(void);
1361
1362int
1363_PyCrossInterpreterData_Register_Class(PyTypeObject *cls,
1364 crossinterpdatafunc getdata)
1365{
1366 if (!PyType_Check(cls)) {
1367 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1368 return -1;
1369 }
1370 if (getdata == NULL) {
1371 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1372 return -1;
1373 }
1374
1375 // Make sure the class isn't ever deallocated.
1376 Py_INCREF((PyObject *)cls);
1377
1378 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1379 if (_PyRuntime.xidregistry.head == NULL) {
1380 _register_builtins_for_crossinterpreter_data();
1381 }
1382 int res = _register_xidata(cls, getdata);
1383 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1384 return res;
1385}
1386
Eric Snow6d2cd902018-05-16 15:04:57 -04001387/* Cross-interpreter objects are looked up by exact match on the class.
1388 We can reassess this policy when we move from a global registry to a
1389 tp_* slot. */
1390
Eric Snow7f8bfc92018-01-29 18:23:44 -07001391crossinterpdatafunc
1392_PyCrossInterpreterData_Lookup(PyObject *obj)
1393{
1394 PyObject *cls = PyObject_Type(obj);
1395 crossinterpdatafunc getdata = NULL;
1396 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1397 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1398 if (cur == NULL) {
1399 _register_builtins_for_crossinterpreter_data();
1400 cur = _PyRuntime.xidregistry.head;
1401 }
1402 for(; cur != NULL; cur = cur->next) {
1403 if (cur->cls == (PyTypeObject *)cls) {
1404 getdata = cur->getdata;
1405 break;
1406 }
1407 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001408 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001409 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1410 return getdata;
1411}
1412
1413/* cross-interpreter data for builtin types */
1414
Eric Snow6d2cd902018-05-16 15:04:57 -04001415struct _shared_bytes_data {
1416 char *bytes;
1417 Py_ssize_t len;
1418};
1419
Eric Snow7f8bfc92018-01-29 18:23:44 -07001420static PyObject *
1421_new_bytes_object(_PyCrossInterpreterData *data)
1422{
Eric Snow6d2cd902018-05-16 15:04:57 -04001423 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1424 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001425}
1426
1427static int
1428_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1429{
Eric Snow6d2cd902018-05-16 15:04:57 -04001430 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1431 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1432 return -1;
1433 }
1434 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001435 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001436 data->obj = obj; // Will be "released" (decref'ed) when data released.
1437 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001438 data->free = PyMem_Free;
1439 return 0;
1440}
1441
1442struct _shared_str_data {
1443 int kind;
1444 const void *buffer;
1445 Py_ssize_t len;
1446};
1447
1448static PyObject *
1449_new_str_object(_PyCrossInterpreterData *data)
1450{
1451 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1452 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1453}
1454
1455static int
1456_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1457{
1458 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1459 shared->kind = PyUnicode_KIND(obj);
1460 shared->buffer = PyUnicode_DATA(obj);
1461 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1462 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001463 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001464 data->obj = obj; // Will be "released" (decref'ed) when data released.
1465 data->new_object = _new_str_object;
1466 data->free = PyMem_Free;
1467 return 0;
1468}
1469
1470static PyObject *
1471_new_long_object(_PyCrossInterpreterData *data)
1472{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001473 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001474}
1475
1476static int
1477_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1478{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001479 /* Note that this means the size of shareable ints is bounded by
1480 * sys.maxsize. Hence on 32-bit architectures that is half the
1481 * size of maximum shareable ints on 64-bit.
1482 */
1483 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001484 if (value == -1 && PyErr_Occurred()) {
1485 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1486 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1487 }
1488 return -1;
1489 }
1490 data->data = (void *)value;
1491 data->obj = NULL;
1492 data->new_object = _new_long_object;
1493 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001494 return 0;
1495}
1496
1497static PyObject *
1498_new_none_object(_PyCrossInterpreterData *data)
1499{
1500 // XXX Singleton refcounts are problematic across interpreters...
1501 Py_INCREF(Py_None);
1502 return Py_None;
1503}
1504
1505static int
1506_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1507{
1508 data->data = NULL;
1509 // data->obj remains NULL
1510 data->new_object = _new_none_object;
1511 data->free = NULL; // There is nothing to free.
1512 return 0;
1513}
1514
1515static void
1516_register_builtins_for_crossinterpreter_data(void)
1517{
1518 // None
1519 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1520 Py_FatalError("could not register None for cross-interpreter sharing");
1521 }
1522
Eric Snow6d2cd902018-05-16 15:04:57 -04001523 // int
1524 if (_register_xidata(&PyLong_Type, _long_shared) != 0) {
1525 Py_FatalError("could not register int for cross-interpreter sharing");
1526 }
1527
Eric Snow7f8bfc92018-01-29 18:23:44 -07001528 // bytes
1529 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1530 Py_FatalError("could not register bytes for cross-interpreter sharing");
1531 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001532
1533 // str
1534 if (_register_xidata(&PyUnicode_Type, _str_shared) != 0) {
1535 Py_FatalError("could not register str for cross-interpreter sharing");
1536 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001537}
1538
1539
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001540#ifdef __cplusplus
1541}
1542#endif