blob: 7d63f4febb932bb28f944b890586c91b6a53ccc8 [file] [log] [blame]
Guido van Rossuma027efa1997-05-05 20:56:21 +00001
2/* Thread and interpreter state structures and their interfaces */
3
4#include "Python.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06005#include "internal/pystate.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +00006
Victor Stinnerb02ef712016-01-22 14:09:55 +01007#define GET_TSTATE() \
8 ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current))
9#define SET_TSTATE(value) \
Benjamin Petersonca470632016-09-06 13:47:26 -070010 _Py_atomic_store_relaxed(&_PyThreadState_Current, (uintptr_t)(value))
Victor Stinnerb02ef712016-01-22 14:09:55 +010011#define GET_INTERP_STATE() \
12 (GET_TSTATE()->interp)
13
Victor Stinnerbfd316e2016-01-20 11:12:38 +010014
Tim Peters84705582004-10-10 02:47:33 +000015/* --------------------------------------------------------------------------
16CAUTION
17
Victor Stinner1a7425f2013-07-07 16:25:15 +020018Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
19number of these functions are advertised as safe to call when the GIL isn't
20held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
21debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
22to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000023-------------------------------------------------------------------------- */
24
Martin v. Löwisf0473d52001-07-18 16:17:16 +000025#ifdef HAVE_DLOPEN
26#ifdef HAVE_DLFCN_H
27#include <dlfcn.h>
28#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030029#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000030#define RTLD_LAZY 1
31#endif
32#endif
33
Benjamin Peterson43162b82012-04-13 11:58:27 -040034#ifdef __cplusplus
35extern "C" {
36#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000037
Victor Stinner5d39e042017-11-29 17:20:38 +010038static _PyInitError
39_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060040{
41 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010042
Eric Snow2ebc5ce2017-09-07 23:51:28 -060043 _PyGC_Initialize(&runtime->gc);
44 _PyEval_Initialize(&runtime->ceval);
Michael W. Hudson188d4362005-06-20 16:52:57 +000045
Eric Snow2ebc5ce2017-09-07 23:51:28 -060046 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080047
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090048 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
49 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080050 Py_tss_t initial = Py_tss_NEEDS_INIT;
51 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000052
Eric Snow2ebc5ce2017-09-07 23:51:28 -060053 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080054 if (runtime->interpreters.mutex == NULL) {
55 return _Py_INIT_ERR("Can't initialize threads for interpreter");
56 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060057 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070058
59 runtime->xidregistry.mutex = PyThread_allocate_lock();
60 if (runtime->xidregistry.mutex == NULL) {
61 return _Py_INIT_ERR("Can't initialize threads for cross-interpreter data registry");
62 }
63
Victor Stinnerf7e5b562017-11-15 15:48:08 -080064 return _Py_INIT_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060065}
Eric Snow05351c12017-09-05 21:43:08 -070066
Victor Stinner5d39e042017-11-29 17:20:38 +010067_PyInitError
68_PyRuntimeState_Init(_PyRuntimeState *runtime)
69{
70 /* Force default allocator, since _PyRuntimeState_Fini() must
71 use the same allocator than this function. */
72 PyMemAllocatorEx old_alloc;
73 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
74
75 _PyInitError err = _PyRuntimeState_Init_impl(runtime);
76
77 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
78 return err;
79}
80
Eric Snow2ebc5ce2017-09-07 23:51:28 -060081void
82_PyRuntimeState_Fini(_PyRuntimeState *runtime)
83{
Victor Stinner5d39e042017-11-29 17:20:38 +010084 /* Force the allocator used by _PyRuntimeState_Init(). */
85 PyMemAllocatorEx old_alloc;
86 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -080087
Eric Snow2ebc5ce2017-09-07 23:51:28 -060088 if (runtime->interpreters.mutex != NULL) {
89 PyThread_free_lock(runtime->interpreters.mutex);
90 runtime->interpreters.mutex = NULL;
91 }
Victor Stinnerccb04422017-11-16 03:20:31 -080092
93 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060094}
95
96#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
97 WAIT_LOCK)
98#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -070099
Michael W. Hudson188d4362005-06-20 16:52:57 +0000100static void _PyGILState_NoteThreadState(PyThreadState* tstate);
101
Victor Stinnera7368ac2017-11-15 18:11:45 -0800102_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600103_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700104{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600105 runtime->interpreters.next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100106
107 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
108 Create a new mutex if needed. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600109 if (runtime->interpreters.mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100110 /* Force default allocator, since _PyRuntimeState_Fini() must
111 use the same allocator than this function. */
112 PyMemAllocatorEx old_alloc;
113 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
114
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600115 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100116
117 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
118
Victor Stinnera7368ac2017-11-15 18:11:45 -0800119 if (runtime->interpreters.mutex == NULL) {
120 return _Py_INIT_ERR("Can't initialize threads for interpreter");
121 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600122 }
Victor Stinner5d926472018-03-06 14:31:37 +0100123
Victor Stinnera7368ac2017-11-15 18:11:45 -0800124 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700125}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000126
127PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000128PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200131 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000132
Victor Stinnerd4341102017-11-23 00:12:09 +0100133 if (interp == NULL) {
134 return NULL;
135 }
136
Eric Snow4c6955e2018-02-16 18:53:40 -0700137 interp->id_refcount = -1;
138 interp->id_mutex = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100139 interp->modules = NULL;
140 interp->modules_by_index = NULL;
141 interp->sysdict = NULL;
142 interp->builtins = NULL;
143 interp->builtins_copy = NULL;
144 interp->tstate_head = NULL;
145 interp->check_interval = 100;
146 interp->num_threads = 0;
147 interp->pythread_stacksize = 0;
148 interp->codec_search_path = NULL;
149 interp->codec_search_cache = NULL;
150 interp->codec_error_registry = NULL;
151 interp->codecs_initialized = 0;
152 interp->fscodec_initialized = 0;
153 interp->core_config = _PyCoreConfig_INIT;
154 interp->config = _PyMainInterpreterConfig_INIT;
155 interp->importlib = NULL;
156 interp->import_func = NULL;
157 interp->eval_frame = _PyEval_EvalFrameDefault;
158 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000159#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300160#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100161 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000162#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100163 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000164#endif
165#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200166#ifdef HAVE_FORK
Victor Stinnerd4341102017-11-23 00:12:09 +0100167 interp->before_forkers = NULL;
168 interp->after_forkers_parent = NULL;
169 interp->after_forkers_child = NULL;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200170#endif
Marcel Plch776407f2017-12-20 11:17:58 +0100171 interp->pyexitfunc = NULL;
172 interp->pyexitmodule = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000173
Victor Stinnerd4341102017-11-23 00:12:09 +0100174 HEAD_LOCK();
Victor Stinnerd4341102017-11-23 00:12:09 +0100175 if (_PyRuntime.interpreters.next_id < 0) {
176 /* overflow or Py_Initialize() not called! */
177 PyErr_SetString(PyExc_RuntimeError,
178 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100179 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100180 interp = NULL;
181 } else {
182 interp->id = _PyRuntime.interpreters.next_id;
183 _PyRuntime.interpreters.next_id += 1;
Pablo Galindo95d630e2018-08-31 22:49:29 +0100184 interp->next = _PyRuntime.interpreters.head;
185 if (_PyRuntime.interpreters.main == NULL) {
186 _PyRuntime.interpreters.main = interp;
187 }
188 _PyRuntime.interpreters.head = interp;
Victor Stinnerd4341102017-11-23 00:12:09 +0100189 }
190 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000191
Pablo Galindo95d630e2018-08-31 22:49:29 +0100192 if (interp == NULL) {
193 return NULL;
194 }
195
Yury Selivanovf23746a2018-01-22 19:11:18 -0500196 interp->tstate_next_unique_id = 0;
197
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000199}
200
201
202void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000203PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 PyThreadState *p;
206 HEAD_LOCK();
207 for (p = interp->tstate_head; p != NULL; p = p->next)
208 PyThreadState_Clear(p);
209 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100210 _PyCoreConfig_Clear(&interp->core_config);
211 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 Py_CLEAR(interp->codec_search_path);
213 Py_CLEAR(interp->codec_search_cache);
214 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700215 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 Py_CLEAR(interp->sysdict);
218 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200219 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400220 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300221 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200222#ifdef HAVE_FORK
223 Py_CLEAR(interp->before_forkers);
224 Py_CLEAR(interp->after_forkers_parent);
225 Py_CLEAR(interp->after_forkers_child);
226#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000227}
228
229
230static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000231zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 PyThreadState *p;
234 /* No need to lock the mutex here because this should only happen
235 when the threads are all really dead (XXX famous last words). */
236 while ((p = interp->tstate_head) != NULL) {
237 PyThreadState_Delete(p);
238 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000239}
240
241
242void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000243PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 PyInterpreterState **p;
246 zapthreads(interp);
247 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600248 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 if (*p == NULL)
250 Py_FatalError(
251 "PyInterpreterState_Delete: invalid interp");
252 if (*p == interp)
253 break;
254 }
255 if (interp->tstate_head != NULL)
256 Py_FatalError("PyInterpreterState_Delete: remaining threads");
257 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600258 if (_PyRuntime.interpreters.main == interp) {
259 _PyRuntime.interpreters.main = NULL;
260 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700261 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
262 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 HEAD_UNLOCK();
Eric Snow4c6955e2018-02-16 18:53:40 -0700264 if (interp->id_mutex != NULL) {
265 PyThread_free_lock(interp->id_mutex);
266 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200267 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000268}
269
270
Victor Stinnercaba55b2018-08-03 15:33:52 +0200271PyInterpreterState *
272_PyInterpreterState_Get(void)
273{
274 PyThreadState *tstate = GET_TSTATE();
275 if (tstate == NULL) {
276 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
277 }
278 PyInterpreterState *interp = tstate->interp;
279 if (interp == NULL) {
280 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
281 }
282 return interp;
283}
284
285
Eric Snowe3774162017-05-22 19:46:40 -0700286int64_t
287PyInterpreterState_GetID(PyInterpreterState *interp)
288{
289 if (interp == NULL) {
290 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
291 return -1;
292 }
293 return interp->id;
294}
295
296
Eric Snow7f8bfc92018-01-29 18:23:44 -0700297PyInterpreterState *
298_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
299{
300 if (requested_id < 0)
301 goto error;
302
303 PyInterpreterState *interp = PyInterpreterState_Head();
304 while (interp != NULL) {
305 PY_INT64_T id = PyInterpreterState_GetID(interp);
306 if (id < 0)
307 return NULL;
308 if (requested_id == id)
309 return interp;
310 interp = PyInterpreterState_Next(interp);
311 }
312
313error:
314 PyErr_Format(PyExc_RuntimeError,
315 "unrecognized interpreter ID %lld", requested_id);
316 return NULL;
317}
318
Eric Snow4c6955e2018-02-16 18:53:40 -0700319
320int
321_PyInterpreterState_IDInitref(PyInterpreterState *interp)
322{
323 if (interp->id_mutex != NULL) {
324 return 0;
325 }
326 interp->id_mutex = PyThread_allocate_lock();
327 if (interp->id_mutex == NULL) {
328 PyErr_SetString(PyExc_RuntimeError,
329 "failed to create init interpreter ID mutex");
330 return -1;
331 }
332 interp->id_refcount = 0;
333 return 0;
334}
335
336
337void
338_PyInterpreterState_IDIncref(PyInterpreterState *interp)
339{
340 if (interp->id_mutex == NULL) {
341 return;
342 }
343 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
344 interp->id_refcount += 1;
345 PyThread_release_lock(interp->id_mutex);
346}
347
348
349void
350_PyInterpreterState_IDDecref(PyInterpreterState *interp)
351{
352 if (interp->id_mutex == NULL) {
353 return;
354 }
355 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
356 assert(interp->id_refcount != 0);
357 interp->id_refcount -= 1;
358 int64_t refcount = interp->id_refcount;
359 PyThread_release_lock(interp->id_mutex);
360
361 if (refcount == 0) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700362 // XXX Using the "head" thread isn't strictly correct.
363 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
364 // XXX Possible GILState issues?
365 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700366 Py_EndInterpreter(tstate);
367 PyThreadState_Swap(save_tstate);
368 }
369}
370
371
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000372/* Default implementation for _PyThreadState_GetFrame */
373static struct _frame *
374threadstate_getframe(PyThreadState *self)
375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000377}
378
Victor Stinner45b9be52010-03-03 23:28:07 +0000379static PyThreadState *
380new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000381{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200382 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 if (_PyThreadState_GetFrame == NULL)
385 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 if (tstate != NULL) {
388 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 tstate->frame = NULL;
391 tstate->recursion_depth = 0;
392 tstate->overflowed = 0;
393 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700394 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 tstate->tracing = 0;
396 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 tstate->gilstate_counter = 0;
398 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 tstate->curexc_type = NULL;
404 tstate->curexc_value = NULL;
405 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000406
Mark Shannonae3087c2017-10-22 22:41:51 +0100407 tstate->exc_state.exc_type = NULL;
408 tstate->exc_state.exc_value = NULL;
409 tstate->exc_state.exc_traceback = NULL;
410 tstate->exc_state.previous_item = NULL;
411 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 tstate->c_profilefunc = NULL;
414 tstate->c_tracefunc = NULL;
415 tstate->c_profileobj = NULL;
416 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000417
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200418 tstate->trash_delete_nesting = 0;
419 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200420 tstate->on_delete = NULL;
421 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200422
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800423 tstate->coroutine_origin_tracking_depth = 0;
424
Yury Selivanov75445082015-05-11 22:57:16 -0400425 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400426 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400427
Yury Selivanoveb636452016-09-08 22:01:51 -0700428 tstate->async_gen_firstiter = NULL;
429 tstate->async_gen_finalizer = NULL;
430
Yury Selivanovf23746a2018-01-22 19:11:18 -0500431 tstate->context = NULL;
432 tstate->context_ver = 1;
433
434 tstate->id = ++interp->tstate_next_unique_id;
435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 if (init)
437 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200440 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200442 if (tstate->next)
443 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 interp->tstate_head = tstate;
445 HEAD_UNLOCK();
446 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000449}
450
Victor Stinner45b9be52010-03-03 23:28:07 +0000451PyThreadState *
452PyThreadState_New(PyInterpreterState *interp)
453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000455}
456
457PyThreadState *
458_PyThreadState_Prealloc(PyInterpreterState *interp)
459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000461}
462
463void
464_PyThreadState_Init(PyThreadState *tstate)
465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000467}
468
Martin v. Löwis1a214512008-06-11 05:26:20 +0000469PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200470PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000471{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200472 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100473 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000475 if (module->m_slots) {
476 return NULL;
477 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 if (index == 0)
479 return NULL;
480 if (state->modules_by_index == NULL)
481 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200482 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 return NULL;
484 res = PyList_GET_ITEM(state->modules_by_index, index);
485 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000486}
487
488int
489_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
490{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000491 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300492 if (!def) {
493 assert(PyErr_Occurred());
494 return -1;
495 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000496 if (def->m_slots) {
497 PyErr_SetString(PyExc_SystemError,
498 "PyState_AddModule called on module with slots");
499 return -1;
500 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100501 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (!state->modules_by_index) {
503 state->modules_by_index = PyList_New(0);
504 if (!state->modules_by_index)
505 return -1;
506 }
507 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
508 if (PyList_Append(state->modules_by_index, Py_None) < 0)
509 return -1;
510 Py_INCREF(module);
511 return PyList_SetItem(state->modules_by_index,
512 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000513}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000514
Martin v. Löwis7800f752012-06-22 12:20:55 +0200515int
516PyState_AddModule(PyObject* module, struct PyModuleDef* def)
517{
518 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100519 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200520 if (!def) {
521 Py_FatalError("PyState_AddModule: Module Definition is NULL");
522 return -1;
523 }
524 index = def->m_base.m_index;
525 if (state->modules_by_index) {
526 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
527 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
528 Py_FatalError("PyState_AddModule: Module already added!");
529 return -1;
530 }
531 }
532 }
533 return _PyState_AddModule(module, def);
534}
535
536int
537PyState_RemoveModule(struct PyModuleDef* def)
538{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000539 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200540 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000541 if (def->m_slots) {
542 PyErr_SetString(PyExc_SystemError,
543 "PyState_RemoveModule called on module with slots");
544 return -1;
545 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100546 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200547 if (index == 0) {
548 Py_FatalError("PyState_RemoveModule: Module index invalid.");
549 return -1;
550 }
551 if (state->modules_by_index == NULL) {
552 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
553 return -1;
554 }
555 if (index > PyList_GET_SIZE(state->modules_by_index)) {
556 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
557 return -1;
558 }
559 return PyList_SetItem(state->modules_by_index, index, Py_None);
560}
561
Antoine Pitrou40322e62013-08-11 00:30:09 +0200562/* used by import.c:PyImport_Cleanup */
563void
564_PyState_ClearModules(void)
565{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100566 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200567 if (state->modules_by_index) {
568 Py_ssize_t i;
569 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
570 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
571 if (PyModule_Check(m)) {
572 /* cleanup the saved copy of module dicts */
573 PyModuleDef *md = PyModule_GetDef(m);
574 if (md)
575 Py_CLEAR(md->m_base.m_copy);
576 }
577 }
578 /* Setting modules_by_index to NULL could be dangerous, so we
579 clear the list instead. */
580 if (PyList_SetSlice(state->modules_by_index,
581 0, PyList_GET_SIZE(state->modules_by_index),
582 NULL))
583 PyErr_WriteUnraisable(state->modules_by_index);
584 }
585}
586
Guido van Rossuma027efa1997-05-05 20:56:21 +0000587void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000588PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000589{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200590 int verbose = tstate->interp->core_config.verbose;
591
592 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 fprintf(stderr,
594 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 Py_CLEAR(tstate->dict);
599 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 Py_CLEAR(tstate->curexc_type);
602 Py_CLEAR(tstate->curexc_value);
603 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000604
Mark Shannonae3087c2017-10-22 22:41:51 +0100605 Py_CLEAR(tstate->exc_state.exc_type);
606 Py_CLEAR(tstate->exc_state.exc_value);
607 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300608
Mark Shannonae3087c2017-10-22 22:41:51 +0100609 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200610 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100611 fprintf(stderr,
612 "PyThreadState_Clear: warning: thread still has a generator\n");
613 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 tstate->c_profilefunc = NULL;
616 tstate->c_tracefunc = NULL;
617 Py_CLEAR(tstate->c_profileobj);
618 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400619
620 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700621 Py_CLEAR(tstate->async_gen_firstiter);
622 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500623
624 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000625}
626
627
Guido van Rossum29757862001-01-23 01:46:06 +0000628/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
629static void
630tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 if (tstate == NULL)
634 Py_FatalError("PyThreadState_Delete: NULL tstate");
635 interp = tstate->interp;
636 if (interp == NULL)
637 Py_FatalError("PyThreadState_Delete: NULL interp");
638 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200639 if (tstate->prev)
640 tstate->prev->next = tstate->next;
641 else
642 interp->tstate_head = tstate->next;
643 if (tstate->next)
644 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200646 if (tstate->on_delete != NULL) {
647 tstate->on_delete(tstate->on_delete_data);
648 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200649 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000650}
651
652
Guido van Rossum29757862001-01-23 01:46:06 +0000653void
654PyThreadState_Delete(PyThreadState *tstate)
655{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100656 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600658 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900659 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600660 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900661 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600662 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200663 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000664}
665
666
Guido van Rossum29757862001-01-23 01:46:06 +0000667void
668PyThreadState_DeleteCurrent()
669{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100670 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 if (tstate == NULL)
672 Py_FatalError(
673 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100674 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600675 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900676 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600677 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900678 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600679 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100680 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000682}
Guido van Rossum29757862001-01-23 01:46:06 +0000683
684
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200685/*
686 * Delete all thread states except the one passed as argument.
687 * Note that, if there is a current thread state, it *must* be the one
688 * passed as argument. Also, this won't touch any other interpreters
689 * than the current one, since we don't know which thread state should
690 * be kept in those other interpreteres.
691 */
692void
693_PyThreadState_DeleteExcept(PyThreadState *tstate)
694{
695 PyInterpreterState *interp = tstate->interp;
696 PyThreadState *p, *next, *garbage;
697 HEAD_LOCK();
698 /* Remove all thread states, except tstate, from the linked list of
699 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200700 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200701 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200702 if (garbage == tstate)
703 garbage = tstate->next;
704 if (tstate->prev)
705 tstate->prev->next = tstate->next;
706 if (tstate->next)
707 tstate->next->prev = tstate->prev;
708 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200709 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200710 HEAD_UNLOCK();
711 /* Clear and deallocate all stale thread states. Even if this
712 executes Python code, we should be safe since it executes
713 in the current thread, not one of the stale threads. */
714 for (p = garbage; p; p = next) {
715 next = p->next;
716 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200717 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200718 }
719}
720
721
Guido van Rossuma027efa1997-05-05 20:56:21 +0000722PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100723_PyThreadState_UncheckedGet(void)
724{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100725 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100726}
727
728
729PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000730PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000731{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100732 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 if (tstate == NULL)
734 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000737}
738
739
740PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000741PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000742{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100743 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000744
Victor Stinnerb02ef712016-01-22 14:09:55 +0100745 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 /* It should not be possible for more than one thread state
747 to be used for a thread. Check this the best we can in debug
748 builds.
749 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200750#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 if (newts) {
752 /* This can be called from PyEval_RestoreThread(). Similar
753 to it, we need to ensure errno doesn't change.
754 */
755 int err = errno;
756 PyThreadState *check = PyGILState_GetThisThreadState();
757 if (check && check->interp == newts->interp && check != newts)
758 Py_FatalError("Invalid thread state for this thread");
759 errno = err;
760 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000761#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000763}
Guido van Rossumede04391998-04-10 20:18:25 +0000764
765/* An extension mechanism to store arbitrary additional per-thread state.
766 PyThreadState_GetDict() returns a dictionary that can be used to hold such
767 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000768 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
769 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000770
771PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000772PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000773{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100774 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 if (tstate == NULL)
776 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 if (tstate->dict == NULL) {
779 PyObject *d;
780 tstate->dict = d = PyDict_New();
781 if (d == NULL)
782 PyErr_Clear();
783 }
784 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000785}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000786
787
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000788/* Asynchronously raise an exception in a thread.
789 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000790 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000791 to call this, or use ctypes. Must be called with the GIL held.
792 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
793 match any known thread id). Can be called with exc=NULL to clear an
794 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000795
796int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200797PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
798{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100799 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000802 /* Although the GIL is held, a few C API functions can be called
803 * without the GIL held, and in particular some that create and
804 * destroy thread and interpreter states. Those can mutate the
805 * list of thread states we're traversing, so to prevent that we lock
806 * head_mutex for the duration.
807 */
808 HEAD_LOCK();
809 for (p = interp->tstate_head; p != NULL; p = p->next) {
810 if (p->thread_id == id) {
811 /* Tricky: we need to decref the current value
812 * (if any) in p->async_exc, but that can in turn
813 * allow arbitrary Python code to run, including
814 * perhaps calls to this function. To prevent
815 * deadlock, we need to release head_mutex before
816 * the decref.
817 */
818 PyObject *old_exc = p->async_exc;
819 Py_XINCREF(exc);
820 p->async_exc = exc;
821 HEAD_UNLOCK();
822 Py_XDECREF(old_exc);
823 _PyEval_SignalAsyncExc();
824 return 1;
825 }
826 }
827 HEAD_UNLOCK();
828 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000829}
830
831
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000832/* Routines for advanced debuggers, requested by David Beazley.
833 Don't use unless you know what you are doing! */
834
835PyInterpreterState *
836PyInterpreterState_Head(void)
837{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600838 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000839}
840
841PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700842PyInterpreterState_Main(void)
843{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600844 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700845}
846
847PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000848PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000850}
851
852PyThreadState *
853PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000855}
856
857PyThreadState *
858PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000860}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000861
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000862/* The implementation of sys._current_frames(). This is intended to be
863 called with the GIL held, as it will be when called via
864 sys._current_frames(). It's possible it would work fine even without
865 the GIL held, but haven't thought enough about that.
866*/
867PyObject *
868_PyThread_CurrentFrames(void)
869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 PyObject *result;
871 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 result = PyDict_New();
874 if (result == NULL)
875 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 /* for i in all interpreters:
878 * for t in all of i's thread states:
879 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200880 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 * need to grab head_mutex for the duration.
882 */
883 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600884 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 PyThreadState *t;
886 for (t = i->tstate_head; t != NULL; t = t->next) {
887 PyObject *id;
888 int stat;
889 struct _frame *frame = t->frame;
890 if (frame == NULL)
891 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200892 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 if (id == NULL)
894 goto Fail;
895 stat = PyDict_SetItem(result, id, (PyObject *)frame);
896 Py_DECREF(id);
897 if (stat < 0)
898 goto Fail;
899 }
900 }
901 HEAD_UNLOCK();
902 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000903
904 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 HEAD_UNLOCK();
906 Py_DECREF(result);
907 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000908}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000909
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000910/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000911
912/* Keep this as a static, as it is not reliable! It can only
913 ever be compared to the state for the *current* thread.
914 * If not equal, then it doesn't matter that the actual
915 value may change immediately after comparison, as it can't
916 possibly change to the current thread's state.
917 * If equal, then the current thread holds the lock, so the value can't
918 change until we yield the lock.
919*/
920static int
921PyThreadState_IsCurrent(PyThreadState *tstate)
922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 /* Must be the tstate for this thread */
924 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100925 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000926}
927
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000928/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000929 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000930*/
Tim Peters19717fa2004-10-09 17:38:29 +0000931void
932_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900935 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
936 Py_FatalError("Could not allocate TSS entry");
937 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600938 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900939 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000943}
944
Victor Stinner861d9ab2016-03-16 22:45:24 +0100945PyInterpreterState *
946_PyGILState_GetInterpreterStateUnsafe(void)
947{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600948 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100949}
950
Tim Peters19717fa2004-10-09 17:38:29 +0000951void
952_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000953{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900954 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600955 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000956}
957
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900958/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200959 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900960 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200961 */
962void
963_PyGILState_Reinit(void)
964{
Victor Stinner5d926472018-03-06 14:31:37 +0100965 /* Force default allocator, since _PyRuntimeState_Fini() must
966 use the same allocator than this function. */
967 PyMemAllocatorEx old_alloc;
968 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
969
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600970 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100971
972 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
973
974 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600975 Py_FatalError("Can't initialize threads for interpreter");
Victor Stinner5d926472018-03-06 14:31:37 +0100976 }
977
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200978 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900979 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
980 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
981 Py_FatalError("Could not allocate TSS entry");
982 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200983
Charles-François Natalia233df82011-11-22 19:49:51 +0100984 /* If the thread had an associated auto thread state, reassociate it with
985 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900986 if (tstate &&
987 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
988 {
989 Py_FatalError("Couldn't create autoTSSkey mapping");
990 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200991}
992
Michael W. Hudson188d4362005-06-20 16:52:57 +0000993/* When a thread state is created for a thread by some mechanism other than
994 PyGILState_Ensure, it's important that the GILState machinery knows about
995 it so it doesn't try to create another thread state for the thread (this is
996 a better fix for SF bug #1010677 than the first one attempted).
997*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000998static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000999_PyGILState_NoteThreadState(PyThreadState* tstate)
1000{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001001 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001002 threadstate created in Py_Initialize(). Don't do anything for now
1003 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001004 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001006
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001007 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 The only situation where you can legitimately have more than one
1010 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001011 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001012
Victor Stinner590cebe2013-12-13 11:08:56 +01001013 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1014 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001015
Victor Stinner590cebe2013-12-13 11:08:56 +01001016 The first thread state created for that given OS level thread will
1017 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001019 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
1020 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1021 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001022 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001023 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001024 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001025 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 /* PyGILState_Release must not try to delete this thread state. */
1028 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001029}
1030
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001031/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001032PyThreadState *
1033PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001034{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001035 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001037 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001038}
1039
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001040int
1041PyGILState_Check(void)
1042{
Victor Stinner8a1be612016-03-14 22:07:55 +01001043 PyThreadState *tstate;
1044
1045 if (!_PyGILState_check_enabled)
1046 return 1;
1047
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001048 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001049 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001050 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001051
1052 tstate = GET_TSTATE();
1053 if (tstate == NULL)
1054 return 0;
1055
1056 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001057}
1058
Tim Peters19717fa2004-10-09 17:38:29 +00001059PyGILState_STATE
1060PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 int current;
1063 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001064 int need_init_threads = 0;
1065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 /* Note that we do not auto-init Python here - apart from
1067 potential races with 2 threads auto-initializing, pep-311
1068 spells out other issues. Embedders are expected to have
1069 called Py_Initialize() and usually PyEval_InitThreads().
1070 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001071 /* Py_Initialize() hasn't been called! */
1072 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001073
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001074 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001076 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001079 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 if (tcur == NULL)
1081 Py_FatalError("Couldn't create thread-state for new thread");
1082 /* This is our thread state! We'll need to delete it in the
1083 matching call to PyGILState_Release(). */
1084 tcur->gilstate_counter = 0;
1085 current = 0; /* new thread state is never current */
1086 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001087 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001089 }
1090
1091 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001093 }
1094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 /* Update our counter in the thread-state - no need for locks:
1096 - tcur will remain valid as we hold the GIL.
1097 - the counter is safe as we are the only thread "allowed"
1098 to modify this value
1099 */
1100 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001101
1102 if (need_init_threads) {
1103 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1104 called from a new thread for the first time, we need the create the
1105 GIL. */
1106 PyEval_InitThreads();
1107 }
1108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001110}
1111
Tim Peters19717fa2004-10-09 17:38:29 +00001112void
1113PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001114{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001115 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1116 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 if (tcur == NULL)
1118 Py_FatalError("auto-releasing thread-state, "
1119 "but no thread-state for this thread");
1120 /* We must hold the GIL and have our thread state current */
1121 /* XXX - remove the check - the assert should be fine,
1122 but while this is very new (April 2003), the extra check
1123 by release-only users can't hurt.
1124 */
1125 if (! PyThreadState_IsCurrent(tcur))
1126 Py_FatalError("This thread state must be current when releasing");
1127 assert(PyThreadState_IsCurrent(tcur));
1128 --tcur->gilstate_counter;
1129 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 /* If we're going to destroy this thread-state, we must
1132 * clear it while the GIL is held, as destructors may run.
1133 */
1134 if (tcur->gilstate_counter == 0) {
1135 /* can't have been locked when we created it */
1136 assert(oldstate == PyGILState_UNLOCKED);
1137 PyThreadState_Clear(tcur);
1138 /* Delete the thread-state. Note this releases the GIL too!
1139 * It's vital that the GIL be held here, to avoid shutdown
1140 * races; see bugs 225673 and 1061968 (that nasty bug has a
1141 * habit of coming back).
1142 */
1143 PyThreadState_DeleteCurrent();
1144 }
1145 /* Release the lock if necessary */
1146 else if (oldstate == PyGILState_UNLOCKED)
1147 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001148}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001149
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001150
Eric Snow7f8bfc92018-01-29 18:23:44 -07001151/**************************/
1152/* cross-interpreter data */
1153/**************************/
1154
1155/* cross-interpreter data */
1156
1157crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1158
1159/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1160 to keep the registry code separate. */
1161static crossinterpdatafunc
1162_lookup_getdata(PyObject *obj)
1163{
1164 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1165 if (getdata == NULL && PyErr_Occurred() == 0)
1166 PyErr_Format(PyExc_ValueError,
1167 "%S does not support cross-interpreter data", obj);
1168 return getdata;
1169}
1170
1171int
1172_PyObject_CheckCrossInterpreterData(PyObject *obj)
1173{
1174 crossinterpdatafunc getdata = _lookup_getdata(obj);
1175 if (getdata == NULL) {
1176 return -1;
1177 }
1178 return 0;
1179}
1180
1181static int
1182_check_xidata(_PyCrossInterpreterData *data)
1183{
1184 // data->data can be anything, including NULL, so we don't check it.
1185
1186 // data->obj may be NULL, so we don't check it.
1187
1188 if (data->interp < 0) {
1189 PyErr_SetString(PyExc_SystemError, "missing interp");
1190 return -1;
1191 }
1192
1193 if (data->new_object == NULL) {
1194 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1195 return -1;
1196 }
1197
1198 // data->free may be NULL, so we don't check it.
1199
1200 return 0;
1201}
1202
1203int
1204_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1205{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001206 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001207 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001208 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001209
1210 // Reset data before re-populating.
1211 *data = (_PyCrossInterpreterData){0};
1212 data->free = PyMem_RawFree; // Set a default that may be overridden.
1213
1214 // Call the "getdata" func for the object.
1215 Py_INCREF(obj);
1216 crossinterpdatafunc getdata = _lookup_getdata(obj);
1217 if (getdata == NULL) {
1218 Py_DECREF(obj);
1219 return -1;
1220 }
1221 int res = getdata(obj, data);
1222 Py_DECREF(obj);
1223 if (res != 0) {
1224 return -1;
1225 }
1226
1227 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001228 data->interp = interp->id;
1229 if (_check_xidata(data) != 0) {
1230 _PyCrossInterpreterData_Release(data);
1231 return -1;
1232 }
1233
1234 return 0;
1235}
1236
Eric Snow63799132018-06-01 18:45:20 -06001237static void
1238_release_xidata(void *arg)
1239{
1240 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1241 if (data->free != NULL) {
1242 data->free(data->data);
1243 }
1244 Py_XDECREF(data->obj);
1245}
1246
1247static void
1248_call_in_interpreter(PyInterpreterState *interp,
1249 void (*func)(void *), void *arg)
1250{
1251 /* We would use Py_AddPendingCall() if it weren't specific to the
1252 * main interpreter (see bpo-33608). In the meantime we take a
1253 * naive approach.
1254 */
1255 PyThreadState *save_tstate = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001256 if (interp != _PyInterpreterState_Get()) {
Eric Snow63799132018-06-01 18:45:20 -06001257 // XXX Using the "head" thread isn't strictly correct.
1258 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1259 // XXX Possible GILState issues?
1260 save_tstate = PyThreadState_Swap(tstate);
1261 }
1262
1263 func(arg);
1264
1265 // Switch back.
1266 if (save_tstate != NULL) {
1267 PyThreadState_Swap(save_tstate);
1268 }
1269}
1270
Eric Snow7f8bfc92018-01-29 18:23:44 -07001271void
1272_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1273{
1274 if (data->data == NULL && data->obj == NULL) {
1275 // Nothing to release!
1276 return;
1277 }
1278
1279 // Switch to the original interpreter.
1280 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1281 if (interp == NULL) {
1282 // The intepreter was already destroyed.
1283 if (data->free != NULL) {
1284 // XXX Someone leaked some memory...
1285 }
1286 return;
1287 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001288
Eric Snow7f8bfc92018-01-29 18:23:44 -07001289 // "Release" the data and/or the object.
Eric Snow63799132018-06-01 18:45:20 -06001290 _call_in_interpreter(interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001291}
1292
1293PyObject *
1294_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1295{
1296 return data->new_object(data);
1297}
1298
1299/* registry of {type -> crossinterpdatafunc} */
1300
1301/* For now we use a global registry of shareable classes. An
1302 alternative would be to add a tp_* slot for a class's
1303 crossinterpdatafunc. It would be simpler and more efficient. */
1304
1305static int
1306_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1307{
1308 // Note that we effectively replace already registered classes
1309 // rather than failing.
1310 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1311 if (newhead == NULL)
1312 return -1;
1313 newhead->cls = cls;
1314 newhead->getdata = getdata;
1315 newhead->next = _PyRuntime.xidregistry.head;
1316 _PyRuntime.xidregistry.head = newhead;
1317 return 0;
1318}
1319
1320static void _register_builtins_for_crossinterpreter_data(void);
1321
1322int
1323_PyCrossInterpreterData_Register_Class(PyTypeObject *cls,
1324 crossinterpdatafunc getdata)
1325{
1326 if (!PyType_Check(cls)) {
1327 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1328 return -1;
1329 }
1330 if (getdata == NULL) {
1331 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1332 return -1;
1333 }
1334
1335 // Make sure the class isn't ever deallocated.
1336 Py_INCREF((PyObject *)cls);
1337
1338 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1339 if (_PyRuntime.xidregistry.head == NULL) {
1340 _register_builtins_for_crossinterpreter_data();
1341 }
1342 int res = _register_xidata(cls, getdata);
1343 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1344 return res;
1345}
1346
Eric Snow6d2cd902018-05-16 15:04:57 -04001347/* Cross-interpreter objects are looked up by exact match on the class.
1348 We can reassess this policy when we move from a global registry to a
1349 tp_* slot. */
1350
Eric Snow7f8bfc92018-01-29 18:23:44 -07001351crossinterpdatafunc
1352_PyCrossInterpreterData_Lookup(PyObject *obj)
1353{
1354 PyObject *cls = PyObject_Type(obj);
1355 crossinterpdatafunc getdata = NULL;
1356 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1357 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1358 if (cur == NULL) {
1359 _register_builtins_for_crossinterpreter_data();
1360 cur = _PyRuntime.xidregistry.head;
1361 }
1362 for(; cur != NULL; cur = cur->next) {
1363 if (cur->cls == (PyTypeObject *)cls) {
1364 getdata = cur->getdata;
1365 break;
1366 }
1367 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001368 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001369 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1370 return getdata;
1371}
1372
1373/* cross-interpreter data for builtin types */
1374
Eric Snow6d2cd902018-05-16 15:04:57 -04001375struct _shared_bytes_data {
1376 char *bytes;
1377 Py_ssize_t len;
1378};
1379
Eric Snow7f8bfc92018-01-29 18:23:44 -07001380static PyObject *
1381_new_bytes_object(_PyCrossInterpreterData *data)
1382{
Eric Snow6d2cd902018-05-16 15:04:57 -04001383 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1384 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001385}
1386
1387static int
1388_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1389{
Eric Snow6d2cd902018-05-16 15:04:57 -04001390 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1391 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1392 return -1;
1393 }
1394 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001395 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001396 data->obj = obj; // Will be "released" (decref'ed) when data released.
1397 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001398 data->free = PyMem_Free;
1399 return 0;
1400}
1401
1402struct _shared_str_data {
1403 int kind;
1404 const void *buffer;
1405 Py_ssize_t len;
1406};
1407
1408static PyObject *
1409_new_str_object(_PyCrossInterpreterData *data)
1410{
1411 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1412 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1413}
1414
1415static int
1416_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1417{
1418 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1419 shared->kind = PyUnicode_KIND(obj);
1420 shared->buffer = PyUnicode_DATA(obj);
1421 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1422 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001423 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001424 data->obj = obj; // Will be "released" (decref'ed) when data released.
1425 data->new_object = _new_str_object;
1426 data->free = PyMem_Free;
1427 return 0;
1428}
1429
1430static PyObject *
1431_new_long_object(_PyCrossInterpreterData *data)
1432{
1433 return PyLong_FromLongLong((int64_t)(data->data));
1434}
1435
1436static int
1437_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1438{
1439 int64_t value = PyLong_AsLongLong(obj);
1440 if (value == -1 && PyErr_Occurred()) {
1441 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1442 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1443 }
1444 return -1;
1445 }
1446 data->data = (void *)value;
1447 data->obj = NULL;
1448 data->new_object = _new_long_object;
1449 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001450 return 0;
1451}
1452
1453static PyObject *
1454_new_none_object(_PyCrossInterpreterData *data)
1455{
1456 // XXX Singleton refcounts are problematic across interpreters...
1457 Py_INCREF(Py_None);
1458 return Py_None;
1459}
1460
1461static int
1462_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1463{
1464 data->data = NULL;
1465 // data->obj remains NULL
1466 data->new_object = _new_none_object;
1467 data->free = NULL; // There is nothing to free.
1468 return 0;
1469}
1470
1471static void
1472_register_builtins_for_crossinterpreter_data(void)
1473{
1474 // None
1475 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1476 Py_FatalError("could not register None for cross-interpreter sharing");
1477 }
1478
Eric Snow6d2cd902018-05-16 15:04:57 -04001479 // int
1480 if (_register_xidata(&PyLong_Type, _long_shared) != 0) {
1481 Py_FatalError("could not register int for cross-interpreter sharing");
1482 }
1483
Eric Snow7f8bfc92018-01-29 18:23:44 -07001484 // bytes
1485 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1486 Py_FatalError("could not register bytes for cross-interpreter sharing");
1487 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001488
1489 // str
1490 if (_register_xidata(&PyUnicode_Type, _str_shared) != 0) {
1491 Py_FatalError("could not register str for cross-interpreter sharing");
1492 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001493}
1494
1495
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001496#ifdef __cplusplus
1497}
1498#endif