blob: cdb881364d7a7b619dbf84e25eb740e47b6a7ffa [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
Eric Snowbe3b2952019-02-23 11:35:52 -0700410_PyCoreConfig *
411_PyInterpreterState_GetCoreConfig(PyInterpreterState *interp)
412{
413 return &interp->core_config;
414}
415
416_PyMainInterpreterConfig *
417_PyInterpreterState_GetMainConfig(PyInterpreterState *interp)
418{
419 return &interp->config;
420}
Eric Snow4c6955e2018-02-16 18:53:40 -0700421
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000422/* Default implementation for _PyThreadState_GetFrame */
423static struct _frame *
424threadstate_getframe(PyThreadState *self)
425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000427}
428
Victor Stinner45b9be52010-03-03 23:28:07 +0000429static PyThreadState *
430new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000431{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200432 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 if (_PyThreadState_GetFrame == NULL)
435 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 if (tstate != NULL) {
438 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 tstate->frame = NULL;
441 tstate->recursion_depth = 0;
442 tstate->overflowed = 0;
443 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700444 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 tstate->tracing = 0;
446 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 tstate->gilstate_counter = 0;
448 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 tstate->curexc_type = NULL;
454 tstate->curexc_value = NULL;
455 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000456
Mark Shannonae3087c2017-10-22 22:41:51 +0100457 tstate->exc_state.exc_type = NULL;
458 tstate->exc_state.exc_value = NULL;
459 tstate->exc_state.exc_traceback = NULL;
460 tstate->exc_state.previous_item = NULL;
461 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 tstate->c_profilefunc = NULL;
464 tstate->c_tracefunc = NULL;
465 tstate->c_profileobj = NULL;
466 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000467
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200468 tstate->trash_delete_nesting = 0;
469 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200470 tstate->on_delete = NULL;
471 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200472
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800473 tstate->coroutine_origin_tracking_depth = 0;
474
Yury Selivanov75445082015-05-11 22:57:16 -0400475 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400476 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400477
Yury Selivanoveb636452016-09-08 22:01:51 -0700478 tstate->async_gen_firstiter = NULL;
479 tstate->async_gen_finalizer = NULL;
480
Yury Selivanovf23746a2018-01-22 19:11:18 -0500481 tstate->context = NULL;
482 tstate->context_ver = 1;
483
484 tstate->id = ++interp->tstate_next_unique_id;
485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 if (init)
487 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200490 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200492 if (tstate->next)
493 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 interp->tstate_head = tstate;
495 HEAD_UNLOCK();
496 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000499}
500
Victor Stinner45b9be52010-03-03 23:28:07 +0000501PyThreadState *
502PyThreadState_New(PyInterpreterState *interp)
503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000505}
506
507PyThreadState *
508_PyThreadState_Prealloc(PyInterpreterState *interp)
509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000511}
512
513void
514_PyThreadState_Init(PyThreadState *tstate)
515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000517}
518
Martin v. Löwis1a214512008-06-11 05:26:20 +0000519PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200520PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000521{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200522 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100523 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000525 if (module->m_slots) {
526 return NULL;
527 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 if (index == 0)
529 return NULL;
530 if (state->modules_by_index == NULL)
531 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200532 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 return NULL;
534 res = PyList_GET_ITEM(state->modules_by_index, index);
535 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000536}
537
538int
539_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
540{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000541 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300542 if (!def) {
543 assert(PyErr_Occurred());
544 return -1;
545 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000546 if (def->m_slots) {
547 PyErr_SetString(PyExc_SystemError,
548 "PyState_AddModule called on module with slots");
549 return -1;
550 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100551 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 if (!state->modules_by_index) {
553 state->modules_by_index = PyList_New(0);
554 if (!state->modules_by_index)
555 return -1;
556 }
557 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
558 if (PyList_Append(state->modules_by_index, Py_None) < 0)
559 return -1;
560 Py_INCREF(module);
561 return PyList_SetItem(state->modules_by_index,
562 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000563}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000564
Martin v. Löwis7800f752012-06-22 12:20:55 +0200565int
566PyState_AddModule(PyObject* module, struct PyModuleDef* def)
567{
568 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100569 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200570 if (!def) {
571 Py_FatalError("PyState_AddModule: Module Definition is NULL");
572 return -1;
573 }
574 index = def->m_base.m_index;
575 if (state->modules_by_index) {
576 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
577 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
578 Py_FatalError("PyState_AddModule: Module already added!");
579 return -1;
580 }
581 }
582 }
583 return _PyState_AddModule(module, def);
584}
585
586int
587PyState_RemoveModule(struct PyModuleDef* def)
588{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000589 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200590 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000591 if (def->m_slots) {
592 PyErr_SetString(PyExc_SystemError,
593 "PyState_RemoveModule called on module with slots");
594 return -1;
595 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100596 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200597 if (index == 0) {
598 Py_FatalError("PyState_RemoveModule: Module index invalid.");
599 return -1;
600 }
601 if (state->modules_by_index == NULL) {
602 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
603 return -1;
604 }
605 if (index > PyList_GET_SIZE(state->modules_by_index)) {
606 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
607 return -1;
608 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700609 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200610 return PyList_SetItem(state->modules_by_index, index, Py_None);
611}
612
Antoine Pitrou40322e62013-08-11 00:30:09 +0200613/* used by import.c:PyImport_Cleanup */
614void
615_PyState_ClearModules(void)
616{
Victor Stinner9204fb82018-10-30 15:13:17 +0100617 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200618 if (state->modules_by_index) {
619 Py_ssize_t i;
620 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
621 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
622 if (PyModule_Check(m)) {
623 /* cleanup the saved copy of module dicts */
624 PyModuleDef *md = PyModule_GetDef(m);
625 if (md)
626 Py_CLEAR(md->m_base.m_copy);
627 }
628 }
629 /* Setting modules_by_index to NULL could be dangerous, so we
630 clear the list instead. */
631 if (PyList_SetSlice(state->modules_by_index,
632 0, PyList_GET_SIZE(state->modules_by_index),
633 NULL))
634 PyErr_WriteUnraisable(state->modules_by_index);
635 }
636}
637
Guido van Rossuma027efa1997-05-05 20:56:21 +0000638void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000639PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000640{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200641 int verbose = tstate->interp->core_config.verbose;
642
643 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 fprintf(stderr,
645 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 Py_CLEAR(tstate->dict);
650 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 Py_CLEAR(tstate->curexc_type);
653 Py_CLEAR(tstate->curexc_value);
654 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000655
Mark Shannonae3087c2017-10-22 22:41:51 +0100656 Py_CLEAR(tstate->exc_state.exc_type);
657 Py_CLEAR(tstate->exc_state.exc_value);
658 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300659
Mark Shannonae3087c2017-10-22 22:41:51 +0100660 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200661 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100662 fprintf(stderr,
663 "PyThreadState_Clear: warning: thread still has a generator\n");
664 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 tstate->c_profilefunc = NULL;
667 tstate->c_tracefunc = NULL;
668 Py_CLEAR(tstate->c_profileobj);
669 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400670
671 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700672 Py_CLEAR(tstate->async_gen_firstiter);
673 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500674
675 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000676}
677
678
Guido van Rossum29757862001-01-23 01:46:06 +0000679/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
680static void
681tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000682{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 if (tstate == NULL)
685 Py_FatalError("PyThreadState_Delete: NULL tstate");
686 interp = tstate->interp;
687 if (interp == NULL)
688 Py_FatalError("PyThreadState_Delete: NULL interp");
689 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200690 if (tstate->prev)
691 tstate->prev->next = tstate->next;
692 else
693 interp->tstate_head = tstate->next;
694 if (tstate->next)
695 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200697 if (tstate->on_delete != NULL) {
698 tstate->on_delete(tstate->on_delete_data);
699 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200700 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000701}
702
703
Guido van Rossum29757862001-01-23 01:46:06 +0000704void
705PyThreadState_Delete(PyThreadState *tstate)
706{
Victor Stinner50b48572018-11-01 01:51:40 +0100707 if (tstate == _PyThreadState_GET())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600709 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900710 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600711 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900712 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600713 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200714 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000715}
716
717
Guido van Rossum29757862001-01-23 01:46:06 +0000718void
719PyThreadState_DeleteCurrent()
720{
Victor Stinner50b48572018-11-01 01:51:40 +0100721 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 if (tstate == NULL)
723 Py_FatalError(
724 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100725 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600726 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900727 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600728 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900729 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600730 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100731 _PyThreadState_SET(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000733}
Guido van Rossum29757862001-01-23 01:46:06 +0000734
735
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200736/*
737 * Delete all thread states except the one passed as argument.
738 * Note that, if there is a current thread state, it *must* be the one
739 * passed as argument. Also, this won't touch any other interpreters
740 * than the current one, since we don't know which thread state should
741 * be kept in those other interpreteres.
742 */
743void
744_PyThreadState_DeleteExcept(PyThreadState *tstate)
745{
746 PyInterpreterState *interp = tstate->interp;
747 PyThreadState *p, *next, *garbage;
748 HEAD_LOCK();
749 /* Remove all thread states, except tstate, from the linked list of
750 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200751 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200752 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200753 if (garbage == tstate)
754 garbage = tstate->next;
755 if (tstate->prev)
756 tstate->prev->next = tstate->next;
757 if (tstate->next)
758 tstate->next->prev = tstate->prev;
759 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200760 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200761 HEAD_UNLOCK();
762 /* Clear and deallocate all stale thread states. Even if this
763 executes Python code, we should be safe since it executes
764 in the current thread, not one of the stale threads. */
765 for (p = garbage; p; p = next) {
766 next = p->next;
767 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200768 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200769 }
770}
771
772
Guido van Rossuma027efa1997-05-05 20:56:21 +0000773PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100774_PyThreadState_UncheckedGet(void)
775{
Victor Stinner50b48572018-11-01 01:51:40 +0100776 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100777}
778
779
780PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000781PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000782{
Victor Stinner50b48572018-11-01 01:51:40 +0100783 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (tstate == NULL)
785 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000788}
789
790
791PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000792PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000793{
Victor Stinner50b48572018-11-01 01:51:40 +0100794 PyThreadState *oldts = _PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000795
Victor Stinner9204fb82018-10-30 15:13:17 +0100796 _PyThreadState_SET(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 /* It should not be possible for more than one thread state
798 to be used for a thread. Check this the best we can in debug
799 builds.
800 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200801#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 if (newts) {
803 /* This can be called from PyEval_RestoreThread(). Similar
804 to it, we need to ensure errno doesn't change.
805 */
806 int err = errno;
807 PyThreadState *check = PyGILState_GetThisThreadState();
808 if (check && check->interp == newts->interp && check != newts)
809 Py_FatalError("Invalid thread state for this thread");
810 errno = err;
811 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000812#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000814}
Guido van Rossumede04391998-04-10 20:18:25 +0000815
816/* An extension mechanism to store arbitrary additional per-thread state.
817 PyThreadState_GetDict() returns a dictionary that can be used to hold such
818 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000819 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
820 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000821
822PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000823PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000824{
Victor Stinner50b48572018-11-01 01:51:40 +0100825 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if (tstate == NULL)
827 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 if (tstate->dict == NULL) {
830 PyObject *d;
831 tstate->dict = d = PyDict_New();
832 if (d == NULL)
833 PyErr_Clear();
834 }
835 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000836}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000837
838
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000839/* Asynchronously raise an exception in a thread.
840 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000841 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000842 to call this, or use ctypes. Must be called with the GIL held.
843 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
844 match any known thread id). Can be called with exc=NULL to clear an
845 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000846
847int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200848PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
849{
Victor Stinner9204fb82018-10-30 15:13:17 +0100850 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 /* Although the GIL is held, a few C API functions can be called
854 * without the GIL held, and in particular some that create and
855 * destroy thread and interpreter states. Those can mutate the
856 * list of thread states we're traversing, so to prevent that we lock
857 * head_mutex for the duration.
858 */
859 HEAD_LOCK();
860 for (p = interp->tstate_head; p != NULL; p = p->next) {
861 if (p->thread_id == id) {
862 /* Tricky: we need to decref the current value
863 * (if any) in p->async_exc, but that can in turn
864 * allow arbitrary Python code to run, including
865 * perhaps calls to this function. To prevent
866 * deadlock, we need to release head_mutex before
867 * the decref.
868 */
869 PyObject *old_exc = p->async_exc;
870 Py_XINCREF(exc);
871 p->async_exc = exc;
872 HEAD_UNLOCK();
873 Py_XDECREF(old_exc);
874 _PyEval_SignalAsyncExc();
875 return 1;
876 }
877 }
878 HEAD_UNLOCK();
879 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000880}
881
882
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000883/* Routines for advanced debuggers, requested by David Beazley.
884 Don't use unless you know what you are doing! */
885
886PyInterpreterState *
887PyInterpreterState_Head(void)
888{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600889 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000890}
891
892PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700893PyInterpreterState_Main(void)
894{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600895 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700896}
897
898PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000899PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000901}
902
903PyThreadState *
904PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000906}
907
908PyThreadState *
909PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000911}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000912
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000913/* The implementation of sys._current_frames(). This is intended to be
914 called with the GIL held, as it will be when called via
915 sys._current_frames(). It's possible it would work fine even without
916 the GIL held, but haven't thought enough about that.
917*/
918PyObject *
919_PyThread_CurrentFrames(void)
920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyObject *result;
922 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 result = PyDict_New();
925 if (result == NULL)
926 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 /* for i in all interpreters:
929 * for t in all of i's thread states:
930 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200931 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 * need to grab head_mutex for the duration.
933 */
934 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600935 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 PyThreadState *t;
937 for (t = i->tstate_head; t != NULL; t = t->next) {
938 PyObject *id;
939 int stat;
940 struct _frame *frame = t->frame;
941 if (frame == NULL)
942 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200943 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 if (id == NULL)
945 goto Fail;
946 stat = PyDict_SetItem(result, id, (PyObject *)frame);
947 Py_DECREF(id);
948 if (stat < 0)
949 goto Fail;
950 }
951 }
952 HEAD_UNLOCK();
953 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000954
955 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 HEAD_UNLOCK();
957 Py_DECREF(result);
958 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000959}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000960
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000961/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000962
963/* Keep this as a static, as it is not reliable! It can only
964 ever be compared to the state for the *current* thread.
965 * If not equal, then it doesn't matter that the actual
966 value may change immediately after comparison, as it can't
967 possibly change to the current thread's state.
968 * If equal, then the current thread holds the lock, so the value can't
969 change until we yield the lock.
970*/
971static int
972PyThreadState_IsCurrent(PyThreadState *tstate)
973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 /* Must be the tstate for this thread */
975 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinner50b48572018-11-01 01:51:40 +0100976 return tstate == _PyThreadState_GET();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000977}
978
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000979/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000980 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000981*/
Tim Peters19717fa2004-10-09 17:38:29 +0000982void
983_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000984{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900986 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
987 Py_FatalError("Could not allocate TSS entry");
988 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600989 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900990 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000994}
995
Victor Stinner861d9ab2016-03-16 22:45:24 +0100996PyInterpreterState *
997_PyGILState_GetInterpreterStateUnsafe(void)
998{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600999 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001000}
1001
Tim Peters19717fa2004-10-09 17:38:29 +00001002void
1003_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001004{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001005 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001006 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001007}
1008
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001009/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001010 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001011 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001012 */
1013void
1014_PyGILState_Reinit(void)
1015{
Victor Stinner5d926472018-03-06 14:31:37 +01001016 /* Force default allocator, since _PyRuntimeState_Fini() must
1017 use the same allocator than this function. */
1018 PyMemAllocatorEx old_alloc;
1019 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1020
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001021 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +01001022
1023 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1024
1025 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001026 Py_FatalError("Can't initialize threads for interpreter");
Victor Stinner5d926472018-03-06 14:31:37 +01001027 }
1028
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001029 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001030 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
1031 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1032 Py_FatalError("Could not allocate TSS entry");
1033 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001034
Charles-François Natalia233df82011-11-22 19:49:51 +01001035 /* If the thread had an associated auto thread state, reassociate it with
1036 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001037 if (tstate &&
1038 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
1039 {
1040 Py_FatalError("Couldn't create autoTSSkey mapping");
1041 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001042}
1043
Michael W. Hudson188d4362005-06-20 16:52:57 +00001044/* When a thread state is created for a thread by some mechanism other than
1045 PyGILState_Ensure, it's important that the GILState machinery knows about
1046 it so it doesn't try to create another thread state for the thread (this is
1047 a better fix for SF bug #1010677 than the first one attempted).
1048*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001049static void
Michael W. Hudson188d4362005-06-20 16:52:57 +00001050_PyGILState_NoteThreadState(PyThreadState* tstate)
1051{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001052 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001053 threadstate created in Py_Initialize(). Don't do anything for now
1054 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001055 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001057
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001058 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 The only situation where you can legitimately have more than one
1061 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001062 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001063
Victor Stinner590cebe2013-12-13 11:08:56 +01001064 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1065 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001066
Victor Stinner590cebe2013-12-13 11:08:56 +01001067 The first thread state created for that given OS level thread will
1068 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001070 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
1071 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1072 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001073 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001074 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001075 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001076 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 /* PyGILState_Release must not try to delete this thread state. */
1079 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001080}
1081
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001082/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001083PyThreadState *
1084PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001085{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001086 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001088 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001089}
1090
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001091int
1092PyGILState_Check(void)
1093{
Victor Stinner8a1be612016-03-14 22:07:55 +01001094 PyThreadState *tstate;
1095
1096 if (!_PyGILState_check_enabled)
1097 return 1;
1098
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001099 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001100 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001101 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001102
Victor Stinner50b48572018-11-01 01:51:40 +01001103 tstate = _PyThreadState_GET();
Victor Stinner8a1be612016-03-14 22:07:55 +01001104 if (tstate == NULL)
1105 return 0;
1106
1107 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001108}
1109
Tim Peters19717fa2004-10-09 17:38:29 +00001110PyGILState_STATE
1111PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 int current;
1114 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001115 int need_init_threads = 0;
1116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 /* Note that we do not auto-init Python here - apart from
1118 potential races with 2 threads auto-initializing, pep-311
1119 spells out other issues. Embedders are expected to have
1120 called Py_Initialize() and usually PyEval_InitThreads().
1121 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001122 /* Py_Initialize() hasn't been called! */
1123 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001124
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001125 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001127 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001130 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 if (tcur == NULL)
1132 Py_FatalError("Couldn't create thread-state for new thread");
1133 /* This is our thread state! We'll need to delete it in the
1134 matching call to PyGILState_Release(). */
1135 tcur->gilstate_counter = 0;
1136 current = 0; /* new thread state is never current */
1137 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001138 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001140 }
1141
1142 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001144 }
1145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 /* Update our counter in the thread-state - no need for locks:
1147 - tcur will remain valid as we hold the GIL.
1148 - the counter is safe as we are the only thread "allowed"
1149 to modify this value
1150 */
1151 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001152
1153 if (need_init_threads) {
1154 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1155 called from a new thread for the first time, we need the create the
1156 GIL. */
1157 PyEval_InitThreads();
1158 }
1159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001161}
1162
Tim Peters19717fa2004-10-09 17:38:29 +00001163void
1164PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001165{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001166 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1167 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 if (tcur == NULL)
1169 Py_FatalError("auto-releasing thread-state, "
1170 "but no thread-state for this thread");
1171 /* We must hold the GIL and have our thread state current */
1172 /* XXX - remove the check - the assert should be fine,
1173 but while this is very new (April 2003), the extra check
1174 by release-only users can't hurt.
1175 */
1176 if (! PyThreadState_IsCurrent(tcur))
1177 Py_FatalError("This thread state must be current when releasing");
1178 assert(PyThreadState_IsCurrent(tcur));
1179 --tcur->gilstate_counter;
1180 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 /* If we're going to destroy this thread-state, we must
1183 * clear it while the GIL is held, as destructors may run.
1184 */
1185 if (tcur->gilstate_counter == 0) {
1186 /* can't have been locked when we created it */
1187 assert(oldstate == PyGILState_UNLOCKED);
1188 PyThreadState_Clear(tcur);
1189 /* Delete the thread-state. Note this releases the GIL too!
1190 * It's vital that the GIL be held here, to avoid shutdown
1191 * races; see bugs 225673 and 1061968 (that nasty bug has a
1192 * habit of coming back).
1193 */
1194 PyThreadState_DeleteCurrent();
1195 }
1196 /* Release the lock if necessary */
1197 else if (oldstate == PyGILState_UNLOCKED)
1198 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001199}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001200
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001201
Eric Snow7f8bfc92018-01-29 18:23:44 -07001202/**************************/
1203/* cross-interpreter data */
1204/**************************/
1205
1206/* cross-interpreter data */
1207
1208crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1209
1210/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1211 to keep the registry code separate. */
1212static crossinterpdatafunc
1213_lookup_getdata(PyObject *obj)
1214{
1215 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1216 if (getdata == NULL && PyErr_Occurred() == 0)
1217 PyErr_Format(PyExc_ValueError,
1218 "%S does not support cross-interpreter data", obj);
1219 return getdata;
1220}
1221
1222int
1223_PyObject_CheckCrossInterpreterData(PyObject *obj)
1224{
1225 crossinterpdatafunc getdata = _lookup_getdata(obj);
1226 if (getdata == NULL) {
1227 return -1;
1228 }
1229 return 0;
1230}
1231
1232static int
1233_check_xidata(_PyCrossInterpreterData *data)
1234{
1235 // data->data can be anything, including NULL, so we don't check it.
1236
1237 // data->obj may be NULL, so we don't check it.
1238
1239 if (data->interp < 0) {
1240 PyErr_SetString(PyExc_SystemError, "missing interp");
1241 return -1;
1242 }
1243
1244 if (data->new_object == NULL) {
1245 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1246 return -1;
1247 }
1248
1249 // data->free may be NULL, so we don't check it.
1250
1251 return 0;
1252}
1253
1254int
1255_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1256{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001257 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001258 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001259 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001260
1261 // Reset data before re-populating.
1262 *data = (_PyCrossInterpreterData){0};
1263 data->free = PyMem_RawFree; // Set a default that may be overridden.
1264
1265 // Call the "getdata" func for the object.
1266 Py_INCREF(obj);
1267 crossinterpdatafunc getdata = _lookup_getdata(obj);
1268 if (getdata == NULL) {
1269 Py_DECREF(obj);
1270 return -1;
1271 }
1272 int res = getdata(obj, data);
1273 Py_DECREF(obj);
1274 if (res != 0) {
1275 return -1;
1276 }
1277
1278 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001279 data->interp = interp->id;
1280 if (_check_xidata(data) != 0) {
1281 _PyCrossInterpreterData_Release(data);
1282 return -1;
1283 }
1284
1285 return 0;
1286}
1287
Eric Snow63799132018-06-01 18:45:20 -06001288static void
1289_release_xidata(void *arg)
1290{
1291 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1292 if (data->free != NULL) {
1293 data->free(data->data);
1294 }
1295 Py_XDECREF(data->obj);
1296}
1297
1298static void
1299_call_in_interpreter(PyInterpreterState *interp,
1300 void (*func)(void *), void *arg)
1301{
1302 /* We would use Py_AddPendingCall() if it weren't specific to the
1303 * main interpreter (see bpo-33608). In the meantime we take a
1304 * naive approach.
1305 */
1306 PyThreadState *save_tstate = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001307 if (interp != _PyInterpreterState_Get()) {
Eric Snow63799132018-06-01 18:45:20 -06001308 // XXX Using the "head" thread isn't strictly correct.
1309 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1310 // XXX Possible GILState issues?
1311 save_tstate = PyThreadState_Swap(tstate);
1312 }
1313
1314 func(arg);
1315
1316 // Switch back.
1317 if (save_tstate != NULL) {
1318 PyThreadState_Swap(save_tstate);
1319 }
1320}
1321
Eric Snow7f8bfc92018-01-29 18:23:44 -07001322void
1323_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1324{
1325 if (data->data == NULL && data->obj == NULL) {
1326 // Nothing to release!
1327 return;
1328 }
1329
1330 // Switch to the original interpreter.
1331 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1332 if (interp == NULL) {
1333 // The intepreter was already destroyed.
1334 if (data->free != NULL) {
1335 // XXX Someone leaked some memory...
1336 }
1337 return;
1338 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001339
Eric Snow7f8bfc92018-01-29 18:23:44 -07001340 // "Release" the data and/or the object.
Eric Snow63799132018-06-01 18:45:20 -06001341 _call_in_interpreter(interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001342}
1343
1344PyObject *
1345_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1346{
1347 return data->new_object(data);
1348}
1349
1350/* registry of {type -> crossinterpdatafunc} */
1351
1352/* For now we use a global registry of shareable classes. An
1353 alternative would be to add a tp_* slot for a class's
1354 crossinterpdatafunc. It would be simpler and more efficient. */
1355
1356static int
1357_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1358{
1359 // Note that we effectively replace already registered classes
1360 // rather than failing.
1361 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1362 if (newhead == NULL)
1363 return -1;
1364 newhead->cls = cls;
1365 newhead->getdata = getdata;
1366 newhead->next = _PyRuntime.xidregistry.head;
1367 _PyRuntime.xidregistry.head = newhead;
1368 return 0;
1369}
1370
1371static void _register_builtins_for_crossinterpreter_data(void);
1372
1373int
1374_PyCrossInterpreterData_Register_Class(PyTypeObject *cls,
1375 crossinterpdatafunc getdata)
1376{
1377 if (!PyType_Check(cls)) {
1378 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1379 return -1;
1380 }
1381 if (getdata == NULL) {
1382 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1383 return -1;
1384 }
1385
1386 // Make sure the class isn't ever deallocated.
1387 Py_INCREF((PyObject *)cls);
1388
1389 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1390 if (_PyRuntime.xidregistry.head == NULL) {
1391 _register_builtins_for_crossinterpreter_data();
1392 }
1393 int res = _register_xidata(cls, getdata);
1394 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1395 return res;
1396}
1397
Eric Snow6d2cd902018-05-16 15:04:57 -04001398/* Cross-interpreter objects are looked up by exact match on the class.
1399 We can reassess this policy when we move from a global registry to a
1400 tp_* slot. */
1401
Eric Snow7f8bfc92018-01-29 18:23:44 -07001402crossinterpdatafunc
1403_PyCrossInterpreterData_Lookup(PyObject *obj)
1404{
1405 PyObject *cls = PyObject_Type(obj);
1406 crossinterpdatafunc getdata = NULL;
1407 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1408 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1409 if (cur == NULL) {
1410 _register_builtins_for_crossinterpreter_data();
1411 cur = _PyRuntime.xidregistry.head;
1412 }
1413 for(; cur != NULL; cur = cur->next) {
1414 if (cur->cls == (PyTypeObject *)cls) {
1415 getdata = cur->getdata;
1416 break;
1417 }
1418 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001419 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001420 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1421 return getdata;
1422}
1423
1424/* cross-interpreter data for builtin types */
1425
Eric Snow6d2cd902018-05-16 15:04:57 -04001426struct _shared_bytes_data {
1427 char *bytes;
1428 Py_ssize_t len;
1429};
1430
Eric Snow7f8bfc92018-01-29 18:23:44 -07001431static PyObject *
1432_new_bytes_object(_PyCrossInterpreterData *data)
1433{
Eric Snow6d2cd902018-05-16 15:04:57 -04001434 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1435 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001436}
1437
1438static int
1439_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1440{
Eric Snow6d2cd902018-05-16 15:04:57 -04001441 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1442 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1443 return -1;
1444 }
1445 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001446 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001447 data->obj = obj; // Will be "released" (decref'ed) when data released.
1448 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001449 data->free = PyMem_Free;
1450 return 0;
1451}
1452
1453struct _shared_str_data {
1454 int kind;
1455 const void *buffer;
1456 Py_ssize_t len;
1457};
1458
1459static PyObject *
1460_new_str_object(_PyCrossInterpreterData *data)
1461{
1462 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1463 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1464}
1465
1466static int
1467_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1468{
1469 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1470 shared->kind = PyUnicode_KIND(obj);
1471 shared->buffer = PyUnicode_DATA(obj);
1472 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1473 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001474 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001475 data->obj = obj; // Will be "released" (decref'ed) when data released.
1476 data->new_object = _new_str_object;
1477 data->free = PyMem_Free;
1478 return 0;
1479}
1480
1481static PyObject *
1482_new_long_object(_PyCrossInterpreterData *data)
1483{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001484 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001485}
1486
1487static int
1488_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1489{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001490 /* Note that this means the size of shareable ints is bounded by
1491 * sys.maxsize. Hence on 32-bit architectures that is half the
1492 * size of maximum shareable ints on 64-bit.
1493 */
1494 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001495 if (value == -1 && PyErr_Occurred()) {
1496 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1497 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1498 }
1499 return -1;
1500 }
1501 data->data = (void *)value;
1502 data->obj = NULL;
1503 data->new_object = _new_long_object;
1504 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001505 return 0;
1506}
1507
1508static PyObject *
1509_new_none_object(_PyCrossInterpreterData *data)
1510{
1511 // XXX Singleton refcounts are problematic across interpreters...
1512 Py_INCREF(Py_None);
1513 return Py_None;
1514}
1515
1516static int
1517_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1518{
1519 data->data = NULL;
1520 // data->obj remains NULL
1521 data->new_object = _new_none_object;
1522 data->free = NULL; // There is nothing to free.
1523 return 0;
1524}
1525
1526static void
1527_register_builtins_for_crossinterpreter_data(void)
1528{
1529 // None
1530 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1531 Py_FatalError("could not register None for cross-interpreter sharing");
1532 }
1533
Eric Snow6d2cd902018-05-16 15:04:57 -04001534 // int
1535 if (_register_xidata(&PyLong_Type, _long_shared) != 0) {
1536 Py_FatalError("could not register int for cross-interpreter sharing");
1537 }
1538
Eric Snow7f8bfc92018-01-29 18:23:44 -07001539 // bytes
1540 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1541 Py_FatalError("could not register bytes for cross-interpreter sharing");
1542 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001543
1544 // str
1545 if (_register_xidata(&PyUnicode_Type, _str_shared) != 0) {
1546 Py_FatalError("could not register str for cross-interpreter sharing");
1547 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001548}
1549
1550
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001551#ifdef __cplusplus
1552}
1553#endif