blob: 7a4cd48077f3b14ea3c099ce6cf911f322c8f137 [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();
175 interp->next = _PyRuntime.interpreters.head;
176 if (_PyRuntime.interpreters.main == NULL) {
177 _PyRuntime.interpreters.main = interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 }
Victor Stinnerd4341102017-11-23 00:12:09 +0100179 _PyRuntime.interpreters.head = interp;
180 if (_PyRuntime.interpreters.next_id < 0) {
181 /* overflow or Py_Initialize() not called! */
182 PyErr_SetString(PyExc_RuntimeError,
183 "failed to get an interpreter ID");
Eric Snow7f8bfc92018-01-29 18:23:44 -0700184 /* XXX deallocate! */
Victor Stinnerd4341102017-11-23 00:12:09 +0100185 interp = NULL;
186 } else {
187 interp->id = _PyRuntime.interpreters.next_id;
188 _PyRuntime.interpreters.next_id += 1;
189 }
190 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000191
Yury Selivanovf23746a2018-01-22 19:11:18 -0500192 interp->tstate_next_unique_id = 0;
193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000195}
196
197
198void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000199PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 PyThreadState *p;
202 HEAD_LOCK();
203 for (p = interp->tstate_head; p != NULL; p = p->next)
204 PyThreadState_Clear(p);
205 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100206 _PyCoreConfig_Clear(&interp->core_config);
207 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 Py_CLEAR(interp->codec_search_path);
209 Py_CLEAR(interp->codec_search_cache);
210 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700211 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 Py_CLEAR(interp->sysdict);
214 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200215 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400216 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300217 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200218#ifdef HAVE_FORK
219 Py_CLEAR(interp->before_forkers);
220 Py_CLEAR(interp->after_forkers_parent);
221 Py_CLEAR(interp->after_forkers_child);
222#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000223}
224
225
226static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000227zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 PyThreadState *p;
230 /* No need to lock the mutex here because this should only happen
231 when the threads are all really dead (XXX famous last words). */
232 while ((p = interp->tstate_head) != NULL) {
233 PyThreadState_Delete(p);
234 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000235}
236
237
238void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000239PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 PyInterpreterState **p;
242 zapthreads(interp);
243 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600244 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 if (*p == NULL)
246 Py_FatalError(
247 "PyInterpreterState_Delete: invalid interp");
248 if (*p == interp)
249 break;
250 }
251 if (interp->tstate_head != NULL)
252 Py_FatalError("PyInterpreterState_Delete: remaining threads");
253 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600254 if (_PyRuntime.interpreters.main == interp) {
255 _PyRuntime.interpreters.main = NULL;
256 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700257 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
258 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 HEAD_UNLOCK();
Eric Snow4c6955e2018-02-16 18:53:40 -0700260 if (interp->id_mutex != NULL) {
261 PyThread_free_lock(interp->id_mutex);
262 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200263 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000264}
265
266
Victor Stinnercaba55b2018-08-03 15:33:52 +0200267PyInterpreterState *
268_PyInterpreterState_Get(void)
269{
270 PyThreadState *tstate = GET_TSTATE();
271 if (tstate == NULL) {
272 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
273 }
274 PyInterpreterState *interp = tstate->interp;
275 if (interp == NULL) {
276 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
277 }
278 return interp;
279}
280
281
Eric Snowe3774162017-05-22 19:46:40 -0700282int64_t
283PyInterpreterState_GetID(PyInterpreterState *interp)
284{
285 if (interp == NULL) {
286 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
287 return -1;
288 }
289 return interp->id;
290}
291
292
Eric Snow7f8bfc92018-01-29 18:23:44 -0700293PyInterpreterState *
294_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
295{
296 if (requested_id < 0)
297 goto error;
298
299 PyInterpreterState *interp = PyInterpreterState_Head();
300 while (interp != NULL) {
301 PY_INT64_T id = PyInterpreterState_GetID(interp);
302 if (id < 0)
303 return NULL;
304 if (requested_id == id)
305 return interp;
306 interp = PyInterpreterState_Next(interp);
307 }
308
309error:
310 PyErr_Format(PyExc_RuntimeError,
311 "unrecognized interpreter ID %lld", requested_id);
312 return NULL;
313}
314
Eric Snow4c6955e2018-02-16 18:53:40 -0700315
316int
317_PyInterpreterState_IDInitref(PyInterpreterState *interp)
318{
319 if (interp->id_mutex != NULL) {
320 return 0;
321 }
322 interp->id_mutex = PyThread_allocate_lock();
323 if (interp->id_mutex == NULL) {
324 PyErr_SetString(PyExc_RuntimeError,
325 "failed to create init interpreter ID mutex");
326 return -1;
327 }
328 interp->id_refcount = 0;
329 return 0;
330}
331
332
333void
334_PyInterpreterState_IDIncref(PyInterpreterState *interp)
335{
336 if (interp->id_mutex == NULL) {
337 return;
338 }
339 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
340 interp->id_refcount += 1;
341 PyThread_release_lock(interp->id_mutex);
342}
343
344
345void
346_PyInterpreterState_IDDecref(PyInterpreterState *interp)
347{
348 if (interp->id_mutex == NULL) {
349 return;
350 }
351 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
352 assert(interp->id_refcount != 0);
353 interp->id_refcount -= 1;
354 int64_t refcount = interp->id_refcount;
355 PyThread_release_lock(interp->id_mutex);
356
357 if (refcount == 0) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700358 // XXX Using the "head" thread isn't strictly correct.
359 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
360 // XXX Possible GILState issues?
361 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700362 Py_EndInterpreter(tstate);
363 PyThreadState_Swap(save_tstate);
364 }
365}
366
367
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000368/* Default implementation for _PyThreadState_GetFrame */
369static struct _frame *
370threadstate_getframe(PyThreadState *self)
371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000373}
374
Victor Stinner45b9be52010-03-03 23:28:07 +0000375static PyThreadState *
376new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000377{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200378 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 if (_PyThreadState_GetFrame == NULL)
381 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 if (tstate != NULL) {
384 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000385
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 tstate->frame = NULL;
387 tstate->recursion_depth = 0;
388 tstate->overflowed = 0;
389 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700390 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 tstate->tracing = 0;
392 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 tstate->gilstate_counter = 0;
394 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 tstate->curexc_type = NULL;
400 tstate->curexc_value = NULL;
401 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000402
Mark Shannonae3087c2017-10-22 22:41:51 +0100403 tstate->exc_state.exc_type = NULL;
404 tstate->exc_state.exc_value = NULL;
405 tstate->exc_state.exc_traceback = NULL;
406 tstate->exc_state.previous_item = NULL;
407 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 tstate->c_profilefunc = NULL;
410 tstate->c_tracefunc = NULL;
411 tstate->c_profileobj = NULL;
412 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000413
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200414 tstate->trash_delete_nesting = 0;
415 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200416 tstate->on_delete = NULL;
417 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200418
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800419 tstate->coroutine_origin_tracking_depth = 0;
420
Yury Selivanov75445082015-05-11 22:57:16 -0400421 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400422 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400423
Yury Selivanoveb636452016-09-08 22:01:51 -0700424 tstate->async_gen_firstiter = NULL;
425 tstate->async_gen_finalizer = NULL;
426
Yury Selivanovf23746a2018-01-22 19:11:18 -0500427 tstate->context = NULL;
428 tstate->context_ver = 1;
429
430 tstate->id = ++interp->tstate_next_unique_id;
431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 if (init)
433 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200436 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200438 if (tstate->next)
439 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 interp->tstate_head = tstate;
441 HEAD_UNLOCK();
442 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000445}
446
Victor Stinner45b9be52010-03-03 23:28:07 +0000447PyThreadState *
448PyThreadState_New(PyInterpreterState *interp)
449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000451}
452
453PyThreadState *
454_PyThreadState_Prealloc(PyInterpreterState *interp)
455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000457}
458
459void
460_PyThreadState_Init(PyThreadState *tstate)
461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000463}
464
Martin v. Löwis1a214512008-06-11 05:26:20 +0000465PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200466PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000467{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200468 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100469 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000471 if (module->m_slots) {
472 return NULL;
473 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (index == 0)
475 return NULL;
476 if (state->modules_by_index == NULL)
477 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200478 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 return NULL;
480 res = PyList_GET_ITEM(state->modules_by_index, index);
481 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000482}
483
484int
485_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
486{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000487 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300488 if (!def) {
489 assert(PyErr_Occurred());
490 return -1;
491 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000492 if (def->m_slots) {
493 PyErr_SetString(PyExc_SystemError,
494 "PyState_AddModule called on module with slots");
495 return -1;
496 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100497 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 if (!state->modules_by_index) {
499 state->modules_by_index = PyList_New(0);
500 if (!state->modules_by_index)
501 return -1;
502 }
503 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
504 if (PyList_Append(state->modules_by_index, Py_None) < 0)
505 return -1;
506 Py_INCREF(module);
507 return PyList_SetItem(state->modules_by_index,
508 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000509}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000510
Martin v. Löwis7800f752012-06-22 12:20:55 +0200511int
512PyState_AddModule(PyObject* module, struct PyModuleDef* def)
513{
514 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100515 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200516 if (!def) {
517 Py_FatalError("PyState_AddModule: Module Definition is NULL");
518 return -1;
519 }
520 index = def->m_base.m_index;
521 if (state->modules_by_index) {
522 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
523 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
524 Py_FatalError("PyState_AddModule: Module already added!");
525 return -1;
526 }
527 }
528 }
529 return _PyState_AddModule(module, def);
530}
531
532int
533PyState_RemoveModule(struct PyModuleDef* def)
534{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000535 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200536 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000537 if (def->m_slots) {
538 PyErr_SetString(PyExc_SystemError,
539 "PyState_RemoveModule called on module with slots");
540 return -1;
541 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100542 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200543 if (index == 0) {
544 Py_FatalError("PyState_RemoveModule: Module index invalid.");
545 return -1;
546 }
547 if (state->modules_by_index == NULL) {
548 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
549 return -1;
550 }
551 if (index > PyList_GET_SIZE(state->modules_by_index)) {
552 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
553 return -1;
554 }
555 return PyList_SetItem(state->modules_by_index, index, Py_None);
556}
557
Antoine Pitrou40322e62013-08-11 00:30:09 +0200558/* used by import.c:PyImport_Cleanup */
559void
560_PyState_ClearModules(void)
561{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100562 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200563 if (state->modules_by_index) {
564 Py_ssize_t i;
565 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
566 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
567 if (PyModule_Check(m)) {
568 /* cleanup the saved copy of module dicts */
569 PyModuleDef *md = PyModule_GetDef(m);
570 if (md)
571 Py_CLEAR(md->m_base.m_copy);
572 }
573 }
574 /* Setting modules_by_index to NULL could be dangerous, so we
575 clear the list instead. */
576 if (PyList_SetSlice(state->modules_by_index,
577 0, PyList_GET_SIZE(state->modules_by_index),
578 NULL))
579 PyErr_WriteUnraisable(state->modules_by_index);
580 }
581}
582
Guido van Rossuma027efa1997-05-05 20:56:21 +0000583void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000584PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000585{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200586 int verbose = tstate->interp->core_config.verbose;
587
588 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 fprintf(stderr,
590 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 Py_CLEAR(tstate->dict);
595 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 Py_CLEAR(tstate->curexc_type);
598 Py_CLEAR(tstate->curexc_value);
599 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000600
Mark Shannonae3087c2017-10-22 22:41:51 +0100601 Py_CLEAR(tstate->exc_state.exc_type);
602 Py_CLEAR(tstate->exc_state.exc_value);
603 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300604
Mark Shannonae3087c2017-10-22 22:41:51 +0100605 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200606 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100607 fprintf(stderr,
608 "PyThreadState_Clear: warning: thread still has a generator\n");
609 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 tstate->c_profilefunc = NULL;
612 tstate->c_tracefunc = NULL;
613 Py_CLEAR(tstate->c_profileobj);
614 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400615
616 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700617 Py_CLEAR(tstate->async_gen_firstiter);
618 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500619
620 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000621}
622
623
Guido van Rossum29757862001-01-23 01:46:06 +0000624/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
625static void
626tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 if (tstate == NULL)
630 Py_FatalError("PyThreadState_Delete: NULL tstate");
631 interp = tstate->interp;
632 if (interp == NULL)
633 Py_FatalError("PyThreadState_Delete: NULL interp");
634 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200635 if (tstate->prev)
636 tstate->prev->next = tstate->next;
637 else
638 interp->tstate_head = tstate->next;
639 if (tstate->next)
640 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200642 if (tstate->on_delete != NULL) {
643 tstate->on_delete(tstate->on_delete_data);
644 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200645 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000646}
647
648
Guido van Rossum29757862001-01-23 01:46:06 +0000649void
650PyThreadState_Delete(PyThreadState *tstate)
651{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100652 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600654 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900655 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600656 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900657 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600658 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200659 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000660}
661
662
Guido van Rossum29757862001-01-23 01:46:06 +0000663void
664PyThreadState_DeleteCurrent()
665{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100666 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 if (tstate == NULL)
668 Py_FatalError(
669 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100670 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600671 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900672 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600673 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900674 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600675 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100676 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000678}
Guido van Rossum29757862001-01-23 01:46:06 +0000679
680
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200681/*
682 * Delete all thread states except the one passed as argument.
683 * Note that, if there is a current thread state, it *must* be the one
684 * passed as argument. Also, this won't touch any other interpreters
685 * than the current one, since we don't know which thread state should
686 * be kept in those other interpreteres.
687 */
688void
689_PyThreadState_DeleteExcept(PyThreadState *tstate)
690{
691 PyInterpreterState *interp = tstate->interp;
692 PyThreadState *p, *next, *garbage;
693 HEAD_LOCK();
694 /* Remove all thread states, except tstate, from the linked list of
695 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200696 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200697 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200698 if (garbage == tstate)
699 garbage = tstate->next;
700 if (tstate->prev)
701 tstate->prev->next = tstate->next;
702 if (tstate->next)
703 tstate->next->prev = tstate->prev;
704 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200705 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200706 HEAD_UNLOCK();
707 /* Clear and deallocate all stale thread states. Even if this
708 executes Python code, we should be safe since it executes
709 in the current thread, not one of the stale threads. */
710 for (p = garbage; p; p = next) {
711 next = p->next;
712 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200713 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200714 }
715}
716
717
Guido van Rossuma027efa1997-05-05 20:56:21 +0000718PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100719_PyThreadState_UncheckedGet(void)
720{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100721 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100722}
723
724
725PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000726PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000727{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100728 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 if (tstate == NULL)
730 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000733}
734
735
736PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000737PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000738{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100739 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000740
Victor Stinnerb02ef712016-01-22 14:09:55 +0100741 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 /* It should not be possible for more than one thread state
743 to be used for a thread. Check this the best we can in debug
744 builds.
745 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200746#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 if (newts) {
748 /* This can be called from PyEval_RestoreThread(). Similar
749 to it, we need to ensure errno doesn't change.
750 */
751 int err = errno;
752 PyThreadState *check = PyGILState_GetThisThreadState();
753 if (check && check->interp == newts->interp && check != newts)
754 Py_FatalError("Invalid thread state for this thread");
755 errno = err;
756 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000757#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000759}
Guido van Rossumede04391998-04-10 20:18:25 +0000760
761/* An extension mechanism to store arbitrary additional per-thread state.
762 PyThreadState_GetDict() returns a dictionary that can be used to hold such
763 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000764 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
765 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000766
767PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000768PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000769{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100770 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 if (tstate == NULL)
772 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 if (tstate->dict == NULL) {
775 PyObject *d;
776 tstate->dict = d = PyDict_New();
777 if (d == NULL)
778 PyErr_Clear();
779 }
780 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000781}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000782
783
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000784/* Asynchronously raise an exception in a thread.
785 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000786 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000787 to call this, or use ctypes. Must be called with the GIL held.
788 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
789 match any known thread id). Can be called with exc=NULL to clear an
790 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000791
792int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200793PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
794{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100795 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 /* Although the GIL is held, a few C API functions can be called
799 * without the GIL held, and in particular some that create and
800 * destroy thread and interpreter states. Those can mutate the
801 * list of thread states we're traversing, so to prevent that we lock
802 * head_mutex for the duration.
803 */
804 HEAD_LOCK();
805 for (p = interp->tstate_head; p != NULL; p = p->next) {
806 if (p->thread_id == id) {
807 /* Tricky: we need to decref the current value
808 * (if any) in p->async_exc, but that can in turn
809 * allow arbitrary Python code to run, including
810 * perhaps calls to this function. To prevent
811 * deadlock, we need to release head_mutex before
812 * the decref.
813 */
814 PyObject *old_exc = p->async_exc;
815 Py_XINCREF(exc);
816 p->async_exc = exc;
817 HEAD_UNLOCK();
818 Py_XDECREF(old_exc);
819 _PyEval_SignalAsyncExc();
820 return 1;
821 }
822 }
823 HEAD_UNLOCK();
824 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000825}
826
827
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000828/* Routines for advanced debuggers, requested by David Beazley.
829 Don't use unless you know what you are doing! */
830
831PyInterpreterState *
832PyInterpreterState_Head(void)
833{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600834 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000835}
836
837PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700838PyInterpreterState_Main(void)
839{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600840 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700841}
842
843PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000844PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000846}
847
848PyThreadState *
849PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000851}
852
853PyThreadState *
854PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000856}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000857
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000858/* The implementation of sys._current_frames(). This is intended to be
859 called with the GIL held, as it will be when called via
860 sys._current_frames(). It's possible it would work fine even without
861 the GIL held, but haven't thought enough about that.
862*/
863PyObject *
864_PyThread_CurrentFrames(void)
865{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 PyObject *result;
867 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 result = PyDict_New();
870 if (result == NULL)
871 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 /* for i in all interpreters:
874 * for t in all of i's thread states:
875 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200876 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 * need to grab head_mutex for the duration.
878 */
879 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600880 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 PyThreadState *t;
882 for (t = i->tstate_head; t != NULL; t = t->next) {
883 PyObject *id;
884 int stat;
885 struct _frame *frame = t->frame;
886 if (frame == NULL)
887 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200888 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 if (id == NULL)
890 goto Fail;
891 stat = PyDict_SetItem(result, id, (PyObject *)frame);
892 Py_DECREF(id);
893 if (stat < 0)
894 goto Fail;
895 }
896 }
897 HEAD_UNLOCK();
898 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000899
900 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 HEAD_UNLOCK();
902 Py_DECREF(result);
903 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000904}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000905
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000906/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000907
908/* Keep this as a static, as it is not reliable! It can only
909 ever be compared to the state for the *current* thread.
910 * If not equal, then it doesn't matter that the actual
911 value may change immediately after comparison, as it can't
912 possibly change to the current thread's state.
913 * If equal, then the current thread holds the lock, so the value can't
914 change until we yield the lock.
915*/
916static int
917PyThreadState_IsCurrent(PyThreadState *tstate)
918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 /* Must be the tstate for this thread */
920 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100921 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000922}
923
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000924/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000925 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000926*/
Tim Peters19717fa2004-10-09 17:38:29 +0000927void
928_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900931 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
932 Py_FatalError("Could not allocate TSS entry");
933 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600934 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900935 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000939}
940
Victor Stinner861d9ab2016-03-16 22:45:24 +0100941PyInterpreterState *
942_PyGILState_GetInterpreterStateUnsafe(void)
943{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600944 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100945}
946
Tim Peters19717fa2004-10-09 17:38:29 +0000947void
948_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000949{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900950 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600951 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000952}
953
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900954/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200955 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900956 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200957 */
958void
959_PyGILState_Reinit(void)
960{
Victor Stinner5d926472018-03-06 14:31:37 +0100961 /* Force default allocator, since _PyRuntimeState_Fini() must
962 use the same allocator than this function. */
963 PyMemAllocatorEx old_alloc;
964 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
965
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600966 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100967
968 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
969
970 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600971 Py_FatalError("Can't initialize threads for interpreter");
Victor Stinner5d926472018-03-06 14:31:37 +0100972 }
973
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200974 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900975 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
976 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
977 Py_FatalError("Could not allocate TSS entry");
978 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200979
Charles-François Natalia233df82011-11-22 19:49:51 +0100980 /* If the thread had an associated auto thread state, reassociate it with
981 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900982 if (tstate &&
983 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
984 {
985 Py_FatalError("Couldn't create autoTSSkey mapping");
986 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200987}
988
Michael W. Hudson188d4362005-06-20 16:52:57 +0000989/* When a thread state is created for a thread by some mechanism other than
990 PyGILState_Ensure, it's important that the GILState machinery knows about
991 it so it doesn't try to create another thread state for the thread (this is
992 a better fix for SF bug #1010677 than the first one attempted).
993*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000994static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000995_PyGILState_NoteThreadState(PyThreadState* tstate)
996{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900997 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +0000998 threadstate created in Py_Initialize(). Don't do anything for now
999 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001000 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001002
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001003 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 The only situation where you can legitimately have more than one
1006 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001007 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001008
Victor Stinner590cebe2013-12-13 11:08:56 +01001009 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1010 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001011
Victor Stinner590cebe2013-12-13 11:08:56 +01001012 The first thread state created for that given OS level thread will
1013 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001015 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
1016 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1017 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001018 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001019 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001020 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001021 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 /* PyGILState_Release must not try to delete this thread state. */
1024 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001025}
1026
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001027/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001028PyThreadState *
1029PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001030{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001031 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001033 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001034}
1035
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001036int
1037PyGILState_Check(void)
1038{
Victor Stinner8a1be612016-03-14 22:07:55 +01001039 PyThreadState *tstate;
1040
1041 if (!_PyGILState_check_enabled)
1042 return 1;
1043
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001044 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001045 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001046 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001047
1048 tstate = GET_TSTATE();
1049 if (tstate == NULL)
1050 return 0;
1051
1052 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001053}
1054
Tim Peters19717fa2004-10-09 17:38:29 +00001055PyGILState_STATE
1056PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 int current;
1059 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001060 int need_init_threads = 0;
1061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 /* Note that we do not auto-init Python here - apart from
1063 potential races with 2 threads auto-initializing, pep-311
1064 spells out other issues. Embedders are expected to have
1065 called Py_Initialize() and usually PyEval_InitThreads().
1066 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001067 /* Py_Initialize() hasn't been called! */
1068 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001069
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001070 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001072 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001075 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 if (tcur == NULL)
1077 Py_FatalError("Couldn't create thread-state for new thread");
1078 /* This is our thread state! We'll need to delete it in the
1079 matching call to PyGILState_Release(). */
1080 tcur->gilstate_counter = 0;
1081 current = 0; /* new thread state is never current */
1082 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001083 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001085 }
1086
1087 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001089 }
1090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 /* Update our counter in the thread-state - no need for locks:
1092 - tcur will remain valid as we hold the GIL.
1093 - the counter is safe as we are the only thread "allowed"
1094 to modify this value
1095 */
1096 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001097
1098 if (need_init_threads) {
1099 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1100 called from a new thread for the first time, we need the create the
1101 GIL. */
1102 PyEval_InitThreads();
1103 }
1104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001106}
1107
Tim Peters19717fa2004-10-09 17:38:29 +00001108void
1109PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001110{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001111 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1112 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 if (tcur == NULL)
1114 Py_FatalError("auto-releasing thread-state, "
1115 "but no thread-state for this thread");
1116 /* We must hold the GIL and have our thread state current */
1117 /* XXX - remove the check - the assert should be fine,
1118 but while this is very new (April 2003), the extra check
1119 by release-only users can't hurt.
1120 */
1121 if (! PyThreadState_IsCurrent(tcur))
1122 Py_FatalError("This thread state must be current when releasing");
1123 assert(PyThreadState_IsCurrent(tcur));
1124 --tcur->gilstate_counter;
1125 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 /* If we're going to destroy this thread-state, we must
1128 * clear it while the GIL is held, as destructors may run.
1129 */
1130 if (tcur->gilstate_counter == 0) {
1131 /* can't have been locked when we created it */
1132 assert(oldstate == PyGILState_UNLOCKED);
1133 PyThreadState_Clear(tcur);
1134 /* Delete the thread-state. Note this releases the GIL too!
1135 * It's vital that the GIL be held here, to avoid shutdown
1136 * races; see bugs 225673 and 1061968 (that nasty bug has a
1137 * habit of coming back).
1138 */
1139 PyThreadState_DeleteCurrent();
1140 }
1141 /* Release the lock if necessary */
1142 else if (oldstate == PyGILState_UNLOCKED)
1143 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001144}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001145
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001146
Eric Snow7f8bfc92018-01-29 18:23:44 -07001147/**************************/
1148/* cross-interpreter data */
1149/**************************/
1150
1151/* cross-interpreter data */
1152
1153crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1154
1155/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1156 to keep the registry code separate. */
1157static crossinterpdatafunc
1158_lookup_getdata(PyObject *obj)
1159{
1160 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1161 if (getdata == NULL && PyErr_Occurred() == 0)
1162 PyErr_Format(PyExc_ValueError,
1163 "%S does not support cross-interpreter data", obj);
1164 return getdata;
1165}
1166
1167int
1168_PyObject_CheckCrossInterpreterData(PyObject *obj)
1169{
1170 crossinterpdatafunc getdata = _lookup_getdata(obj);
1171 if (getdata == NULL) {
1172 return -1;
1173 }
1174 return 0;
1175}
1176
1177static int
1178_check_xidata(_PyCrossInterpreterData *data)
1179{
1180 // data->data can be anything, including NULL, so we don't check it.
1181
1182 // data->obj may be NULL, so we don't check it.
1183
1184 if (data->interp < 0) {
1185 PyErr_SetString(PyExc_SystemError, "missing interp");
1186 return -1;
1187 }
1188
1189 if (data->new_object == NULL) {
1190 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1191 return -1;
1192 }
1193
1194 // data->free may be NULL, so we don't check it.
1195
1196 return 0;
1197}
1198
1199int
1200_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1201{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001202 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001203 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001204 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001205
1206 // Reset data before re-populating.
1207 *data = (_PyCrossInterpreterData){0};
1208 data->free = PyMem_RawFree; // Set a default that may be overridden.
1209
1210 // Call the "getdata" func for the object.
1211 Py_INCREF(obj);
1212 crossinterpdatafunc getdata = _lookup_getdata(obj);
1213 if (getdata == NULL) {
1214 Py_DECREF(obj);
1215 return -1;
1216 }
1217 int res = getdata(obj, data);
1218 Py_DECREF(obj);
1219 if (res != 0) {
1220 return -1;
1221 }
1222
1223 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001224 data->interp = interp->id;
1225 if (_check_xidata(data) != 0) {
1226 _PyCrossInterpreterData_Release(data);
1227 return -1;
1228 }
1229
1230 return 0;
1231}
1232
Eric Snow63799132018-06-01 18:45:20 -06001233static void
1234_release_xidata(void *arg)
1235{
1236 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1237 if (data->free != NULL) {
1238 data->free(data->data);
1239 }
1240 Py_XDECREF(data->obj);
1241}
1242
1243static void
1244_call_in_interpreter(PyInterpreterState *interp,
1245 void (*func)(void *), void *arg)
1246{
1247 /* We would use Py_AddPendingCall() if it weren't specific to the
1248 * main interpreter (see bpo-33608). In the meantime we take a
1249 * naive approach.
1250 */
1251 PyThreadState *save_tstate = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001252 if (interp != _PyInterpreterState_Get()) {
Eric Snow63799132018-06-01 18:45:20 -06001253 // XXX Using the "head" thread isn't strictly correct.
1254 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1255 // XXX Possible GILState issues?
1256 save_tstate = PyThreadState_Swap(tstate);
1257 }
1258
1259 func(arg);
1260
1261 // Switch back.
1262 if (save_tstate != NULL) {
1263 PyThreadState_Swap(save_tstate);
1264 }
1265}
1266
Eric Snow7f8bfc92018-01-29 18:23:44 -07001267void
1268_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1269{
1270 if (data->data == NULL && data->obj == NULL) {
1271 // Nothing to release!
1272 return;
1273 }
1274
1275 // Switch to the original interpreter.
1276 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1277 if (interp == NULL) {
1278 // The intepreter was already destroyed.
1279 if (data->free != NULL) {
1280 // XXX Someone leaked some memory...
1281 }
1282 return;
1283 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001284
Eric Snow7f8bfc92018-01-29 18:23:44 -07001285 // "Release" the data and/or the object.
Eric Snow63799132018-06-01 18:45:20 -06001286 _call_in_interpreter(interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001287}
1288
1289PyObject *
1290_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1291{
1292 return data->new_object(data);
1293}
1294
1295/* registry of {type -> crossinterpdatafunc} */
1296
1297/* For now we use a global registry of shareable classes. An
1298 alternative would be to add a tp_* slot for a class's
1299 crossinterpdatafunc. It would be simpler and more efficient. */
1300
1301static int
1302_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1303{
1304 // Note that we effectively replace already registered classes
1305 // rather than failing.
1306 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1307 if (newhead == NULL)
1308 return -1;
1309 newhead->cls = cls;
1310 newhead->getdata = getdata;
1311 newhead->next = _PyRuntime.xidregistry.head;
1312 _PyRuntime.xidregistry.head = newhead;
1313 return 0;
1314}
1315
1316static void _register_builtins_for_crossinterpreter_data(void);
1317
1318int
1319_PyCrossInterpreterData_Register_Class(PyTypeObject *cls,
1320 crossinterpdatafunc getdata)
1321{
1322 if (!PyType_Check(cls)) {
1323 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1324 return -1;
1325 }
1326 if (getdata == NULL) {
1327 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1328 return -1;
1329 }
1330
1331 // Make sure the class isn't ever deallocated.
1332 Py_INCREF((PyObject *)cls);
1333
1334 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1335 if (_PyRuntime.xidregistry.head == NULL) {
1336 _register_builtins_for_crossinterpreter_data();
1337 }
1338 int res = _register_xidata(cls, getdata);
1339 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1340 return res;
1341}
1342
Eric Snow6d2cd902018-05-16 15:04:57 -04001343/* Cross-interpreter objects are looked up by exact match on the class.
1344 We can reassess this policy when we move from a global registry to a
1345 tp_* slot. */
1346
Eric Snow7f8bfc92018-01-29 18:23:44 -07001347crossinterpdatafunc
1348_PyCrossInterpreterData_Lookup(PyObject *obj)
1349{
1350 PyObject *cls = PyObject_Type(obj);
1351 crossinterpdatafunc getdata = NULL;
1352 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1353 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1354 if (cur == NULL) {
1355 _register_builtins_for_crossinterpreter_data();
1356 cur = _PyRuntime.xidregistry.head;
1357 }
1358 for(; cur != NULL; cur = cur->next) {
1359 if (cur->cls == (PyTypeObject *)cls) {
1360 getdata = cur->getdata;
1361 break;
1362 }
1363 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001364 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001365 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1366 return getdata;
1367}
1368
1369/* cross-interpreter data for builtin types */
1370
Eric Snow6d2cd902018-05-16 15:04:57 -04001371struct _shared_bytes_data {
1372 char *bytes;
1373 Py_ssize_t len;
1374};
1375
Eric Snow7f8bfc92018-01-29 18:23:44 -07001376static PyObject *
1377_new_bytes_object(_PyCrossInterpreterData *data)
1378{
Eric Snow6d2cd902018-05-16 15:04:57 -04001379 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1380 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001381}
1382
1383static int
1384_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1385{
Eric Snow6d2cd902018-05-16 15:04:57 -04001386 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1387 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1388 return -1;
1389 }
1390 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001391 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001392 data->obj = obj; // Will be "released" (decref'ed) when data released.
1393 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001394 data->free = PyMem_Free;
1395 return 0;
1396}
1397
1398struct _shared_str_data {
1399 int kind;
1400 const void *buffer;
1401 Py_ssize_t len;
1402};
1403
1404static PyObject *
1405_new_str_object(_PyCrossInterpreterData *data)
1406{
1407 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1408 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1409}
1410
1411static int
1412_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1413{
1414 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1415 shared->kind = PyUnicode_KIND(obj);
1416 shared->buffer = PyUnicode_DATA(obj);
1417 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1418 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001419 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001420 data->obj = obj; // Will be "released" (decref'ed) when data released.
1421 data->new_object = _new_str_object;
1422 data->free = PyMem_Free;
1423 return 0;
1424}
1425
1426static PyObject *
1427_new_long_object(_PyCrossInterpreterData *data)
1428{
1429 return PyLong_FromLongLong((int64_t)(data->data));
1430}
1431
1432static int
1433_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1434{
1435 int64_t value = PyLong_AsLongLong(obj);
1436 if (value == -1 && PyErr_Occurred()) {
1437 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1438 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1439 }
1440 return -1;
1441 }
1442 data->data = (void *)value;
1443 data->obj = NULL;
1444 data->new_object = _new_long_object;
1445 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001446 return 0;
1447}
1448
1449static PyObject *
1450_new_none_object(_PyCrossInterpreterData *data)
1451{
1452 // XXX Singleton refcounts are problematic across interpreters...
1453 Py_INCREF(Py_None);
1454 return Py_None;
1455}
1456
1457static int
1458_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1459{
1460 data->data = NULL;
1461 // data->obj remains NULL
1462 data->new_object = _new_none_object;
1463 data->free = NULL; // There is nothing to free.
1464 return 0;
1465}
1466
1467static void
1468_register_builtins_for_crossinterpreter_data(void)
1469{
1470 // None
1471 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1472 Py_FatalError("could not register None for cross-interpreter sharing");
1473 }
1474
Eric Snow6d2cd902018-05-16 15:04:57 -04001475 // int
1476 if (_register_xidata(&PyLong_Type, _long_shared) != 0) {
1477 Py_FatalError("could not register int for cross-interpreter sharing");
1478 }
1479
Eric Snow7f8bfc92018-01-29 18:23:44 -07001480 // bytes
1481 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1482 Py_FatalError("could not register bytes for cross-interpreter sharing");
1483 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001484
1485 // str
1486 if (_register_xidata(&PyUnicode_Type, _str_shared) != 0) {
1487 Py_FatalError("could not register str for cross-interpreter sharing");
1488 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001489}
1490
1491
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001492#ifdef __cplusplus
1493}
1494#endif