blob: 7b3d3d4c9032590869638a8d3371b23422407bd4 [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
Eric Snow59032962018-09-14 14:17:20 -0700271/*
272 * Delete all interpreter states except the main interpreter. If there
273 * is a current interpreter state, it *must* be the main interpreter.
274 */
275void
276_PyInterpreterState_DeleteExceptMain()
277{
278 PyThreadState *tstate = PyThreadState_Swap(NULL);
279 if (tstate != NULL && tstate->interp != _PyRuntime.interpreters.main) {
280 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
281 }
282
283 HEAD_LOCK();
284 PyInterpreterState *interp = _PyRuntime.interpreters.head;
285 _PyRuntime.interpreters.head = NULL;
286 for (; interp != NULL; interp = interp->next) {
287 if (interp == _PyRuntime.interpreters.main) {
288 _PyRuntime.interpreters.main->next = NULL;
289 _PyRuntime.interpreters.head = interp;
290 continue;
291 }
292
293 PyInterpreterState_Clear(interp); // XXX must activate?
294 zapthreads(interp);
295 if (interp->id_mutex != NULL) {
296 PyThread_free_lock(interp->id_mutex);
297 }
298 PyMem_RawFree(interp);
299 }
300 HEAD_UNLOCK();
301
302 if (_PyRuntime.interpreters.head == NULL) {
303 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
304 }
305 PyThreadState_Swap(tstate);
306}
307
308
Victor Stinnercaba55b2018-08-03 15:33:52 +0200309PyInterpreterState *
310_PyInterpreterState_Get(void)
311{
312 PyThreadState *tstate = GET_TSTATE();
313 if (tstate == NULL) {
314 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
315 }
316 PyInterpreterState *interp = tstate->interp;
317 if (interp == NULL) {
318 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
319 }
320 return interp;
321}
322
323
Eric Snowe3774162017-05-22 19:46:40 -0700324int64_t
325PyInterpreterState_GetID(PyInterpreterState *interp)
326{
327 if (interp == NULL) {
328 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
329 return -1;
330 }
331 return interp->id;
332}
333
334
Eric Snow7f8bfc92018-01-29 18:23:44 -0700335PyInterpreterState *
336_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
337{
338 if (requested_id < 0)
339 goto error;
340
341 PyInterpreterState *interp = PyInterpreterState_Head();
342 while (interp != NULL) {
343 PY_INT64_T id = PyInterpreterState_GetID(interp);
344 if (id < 0)
345 return NULL;
346 if (requested_id == id)
347 return interp;
348 interp = PyInterpreterState_Next(interp);
349 }
350
351error:
352 PyErr_Format(PyExc_RuntimeError,
353 "unrecognized interpreter ID %lld", requested_id);
354 return NULL;
355}
356
Eric Snow4c6955e2018-02-16 18:53:40 -0700357
358int
359_PyInterpreterState_IDInitref(PyInterpreterState *interp)
360{
361 if (interp->id_mutex != NULL) {
362 return 0;
363 }
364 interp->id_mutex = PyThread_allocate_lock();
365 if (interp->id_mutex == NULL) {
366 PyErr_SetString(PyExc_RuntimeError,
367 "failed to create init interpreter ID mutex");
368 return -1;
369 }
370 interp->id_refcount = 0;
371 return 0;
372}
373
374
375void
376_PyInterpreterState_IDIncref(PyInterpreterState *interp)
377{
378 if (interp->id_mutex == NULL) {
379 return;
380 }
381 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
382 interp->id_refcount += 1;
383 PyThread_release_lock(interp->id_mutex);
384}
385
386
387void
388_PyInterpreterState_IDDecref(PyInterpreterState *interp)
389{
390 if (interp->id_mutex == NULL) {
391 return;
392 }
393 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
394 assert(interp->id_refcount != 0);
395 interp->id_refcount -= 1;
396 int64_t refcount = interp->id_refcount;
397 PyThread_release_lock(interp->id_mutex);
398
399 if (refcount == 0) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700400 // XXX Using the "head" thread isn't strictly correct.
401 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
402 // XXX Possible GILState issues?
403 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700404 Py_EndInterpreter(tstate);
405 PyThreadState_Swap(save_tstate);
406 }
407}
408
409
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000410/* Default implementation for _PyThreadState_GetFrame */
411static struct _frame *
412threadstate_getframe(PyThreadState *self)
413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000415}
416
Victor Stinner45b9be52010-03-03 23:28:07 +0000417static PyThreadState *
418new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000419{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200420 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 if (_PyThreadState_GetFrame == NULL)
423 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (tstate != NULL) {
426 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 tstate->frame = NULL;
429 tstate->recursion_depth = 0;
430 tstate->overflowed = 0;
431 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700432 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 tstate->tracing = 0;
434 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 tstate->gilstate_counter = 0;
436 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 tstate->curexc_type = NULL;
442 tstate->curexc_value = NULL;
443 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000444
Mark Shannonae3087c2017-10-22 22:41:51 +0100445 tstate->exc_state.exc_type = NULL;
446 tstate->exc_state.exc_value = NULL;
447 tstate->exc_state.exc_traceback = NULL;
448 tstate->exc_state.previous_item = NULL;
449 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 tstate->c_profilefunc = NULL;
452 tstate->c_tracefunc = NULL;
453 tstate->c_profileobj = NULL;
454 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000455
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200456 tstate->trash_delete_nesting = 0;
457 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200458 tstate->on_delete = NULL;
459 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200460
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800461 tstate->coroutine_origin_tracking_depth = 0;
462
Yury Selivanov75445082015-05-11 22:57:16 -0400463 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400464 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400465
Yury Selivanoveb636452016-09-08 22:01:51 -0700466 tstate->async_gen_firstiter = NULL;
467 tstate->async_gen_finalizer = NULL;
468
Yury Selivanovf23746a2018-01-22 19:11:18 -0500469 tstate->context = NULL;
470 tstate->context_ver = 1;
471
472 tstate->id = ++interp->tstate_next_unique_id;
473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (init)
475 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200478 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200480 if (tstate->next)
481 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 interp->tstate_head = tstate;
483 HEAD_UNLOCK();
484 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000487}
488
Victor Stinner45b9be52010-03-03 23:28:07 +0000489PyThreadState *
490PyThreadState_New(PyInterpreterState *interp)
491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000493}
494
495PyThreadState *
496_PyThreadState_Prealloc(PyInterpreterState *interp)
497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000499}
500
501void
502_PyThreadState_Init(PyThreadState *tstate)
503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000505}
506
Martin v. Löwis1a214512008-06-11 05:26:20 +0000507PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200508PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000509{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200510 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100511 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000513 if (module->m_slots) {
514 return NULL;
515 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 if (index == 0)
517 return NULL;
518 if (state->modules_by_index == NULL)
519 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200520 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 return NULL;
522 res = PyList_GET_ITEM(state->modules_by_index, index);
523 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000524}
525
526int
527_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
528{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000529 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300530 if (!def) {
531 assert(PyErr_Occurred());
532 return -1;
533 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000534 if (def->m_slots) {
535 PyErr_SetString(PyExc_SystemError,
536 "PyState_AddModule called on module with slots");
537 return -1;
538 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100539 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 if (!state->modules_by_index) {
541 state->modules_by_index = PyList_New(0);
542 if (!state->modules_by_index)
543 return -1;
544 }
545 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
546 if (PyList_Append(state->modules_by_index, Py_None) < 0)
547 return -1;
548 Py_INCREF(module);
549 return PyList_SetItem(state->modules_by_index,
550 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000551}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000552
Martin v. Löwis7800f752012-06-22 12:20:55 +0200553int
554PyState_AddModule(PyObject* module, struct PyModuleDef* def)
555{
556 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100557 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200558 if (!def) {
559 Py_FatalError("PyState_AddModule: Module Definition is NULL");
560 return -1;
561 }
562 index = def->m_base.m_index;
563 if (state->modules_by_index) {
564 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
565 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
566 Py_FatalError("PyState_AddModule: Module already added!");
567 return -1;
568 }
569 }
570 }
571 return _PyState_AddModule(module, def);
572}
573
574int
575PyState_RemoveModule(struct PyModuleDef* def)
576{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000577 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200578 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000579 if (def->m_slots) {
580 PyErr_SetString(PyExc_SystemError,
581 "PyState_RemoveModule called on module with slots");
582 return -1;
583 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100584 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200585 if (index == 0) {
586 Py_FatalError("PyState_RemoveModule: Module index invalid.");
587 return -1;
588 }
589 if (state->modules_by_index == NULL) {
590 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
591 return -1;
592 }
593 if (index > PyList_GET_SIZE(state->modules_by_index)) {
594 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
595 return -1;
596 }
597 return PyList_SetItem(state->modules_by_index, index, Py_None);
598}
599
Antoine Pitrou40322e62013-08-11 00:30:09 +0200600/* used by import.c:PyImport_Cleanup */
601void
602_PyState_ClearModules(void)
603{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100604 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200605 if (state->modules_by_index) {
606 Py_ssize_t i;
607 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
608 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
609 if (PyModule_Check(m)) {
610 /* cleanup the saved copy of module dicts */
611 PyModuleDef *md = PyModule_GetDef(m);
612 if (md)
613 Py_CLEAR(md->m_base.m_copy);
614 }
615 }
616 /* Setting modules_by_index to NULL could be dangerous, so we
617 clear the list instead. */
618 if (PyList_SetSlice(state->modules_by_index,
619 0, PyList_GET_SIZE(state->modules_by_index),
620 NULL))
621 PyErr_WriteUnraisable(state->modules_by_index);
622 }
623}
624
Guido van Rossuma027efa1997-05-05 20:56:21 +0000625void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000626PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000627{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200628 int verbose = tstate->interp->core_config.verbose;
629
630 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 fprintf(stderr,
632 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 Py_CLEAR(tstate->dict);
637 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 Py_CLEAR(tstate->curexc_type);
640 Py_CLEAR(tstate->curexc_value);
641 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000642
Mark Shannonae3087c2017-10-22 22:41:51 +0100643 Py_CLEAR(tstate->exc_state.exc_type);
644 Py_CLEAR(tstate->exc_state.exc_value);
645 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300646
Mark Shannonae3087c2017-10-22 22:41:51 +0100647 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200648 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100649 fprintf(stderr,
650 "PyThreadState_Clear: warning: thread still has a generator\n");
651 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 tstate->c_profilefunc = NULL;
654 tstate->c_tracefunc = NULL;
655 Py_CLEAR(tstate->c_profileobj);
656 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400657
658 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700659 Py_CLEAR(tstate->async_gen_firstiter);
660 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500661
662 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000663}
664
665
Guido van Rossum29757862001-01-23 01:46:06 +0000666/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
667static void
668tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 if (tstate == NULL)
672 Py_FatalError("PyThreadState_Delete: NULL tstate");
673 interp = tstate->interp;
674 if (interp == NULL)
675 Py_FatalError("PyThreadState_Delete: NULL interp");
676 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200677 if (tstate->prev)
678 tstate->prev->next = tstate->next;
679 else
680 interp->tstate_head = tstate->next;
681 if (tstate->next)
682 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200684 if (tstate->on_delete != NULL) {
685 tstate->on_delete(tstate->on_delete_data);
686 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200687 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000688}
689
690
Guido van Rossum29757862001-01-23 01:46:06 +0000691void
692PyThreadState_Delete(PyThreadState *tstate)
693{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100694 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600696 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900697 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600698 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900699 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600700 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200701 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000702}
703
704
Guido van Rossum29757862001-01-23 01:46:06 +0000705void
706PyThreadState_DeleteCurrent()
707{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100708 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 if (tstate == NULL)
710 Py_FatalError(
711 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100712 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600713 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900714 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600715 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900716 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600717 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100718 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000720}
Guido van Rossum29757862001-01-23 01:46:06 +0000721
722
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200723/*
724 * Delete all thread states except the one passed as argument.
725 * Note that, if there is a current thread state, it *must* be the one
726 * passed as argument. Also, this won't touch any other interpreters
727 * than the current one, since we don't know which thread state should
728 * be kept in those other interpreteres.
729 */
730void
731_PyThreadState_DeleteExcept(PyThreadState *tstate)
732{
733 PyInterpreterState *interp = tstate->interp;
734 PyThreadState *p, *next, *garbage;
735 HEAD_LOCK();
736 /* Remove all thread states, except tstate, from the linked list of
737 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200738 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200739 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200740 if (garbage == tstate)
741 garbage = tstate->next;
742 if (tstate->prev)
743 tstate->prev->next = tstate->next;
744 if (tstate->next)
745 tstate->next->prev = tstate->prev;
746 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200747 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200748 HEAD_UNLOCK();
749 /* Clear and deallocate all stale thread states. Even if this
750 executes Python code, we should be safe since it executes
751 in the current thread, not one of the stale threads. */
752 for (p = garbage; p; p = next) {
753 next = p->next;
754 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200755 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200756 }
757}
758
759
Guido van Rossuma027efa1997-05-05 20:56:21 +0000760PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100761_PyThreadState_UncheckedGet(void)
762{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100763 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100764}
765
766
767PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000768PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +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 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000775}
776
777
778PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000779PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000780{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100781 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000782
Victor Stinnerb02ef712016-01-22 14:09:55 +0100783 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 /* It should not be possible for more than one thread state
785 to be used for a thread. Check this the best we can in debug
786 builds.
787 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200788#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 if (newts) {
790 /* This can be called from PyEval_RestoreThread(). Similar
791 to it, we need to ensure errno doesn't change.
792 */
793 int err = errno;
794 PyThreadState *check = PyGILState_GetThisThreadState();
795 if (check && check->interp == newts->interp && check != newts)
796 Py_FatalError("Invalid thread state for this thread");
797 errno = err;
798 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000799#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000801}
Guido van Rossumede04391998-04-10 20:18:25 +0000802
803/* An extension mechanism to store arbitrary additional per-thread state.
804 PyThreadState_GetDict() returns a dictionary that can be used to hold such
805 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000806 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
807 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000808
809PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000810PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000811{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100812 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 if (tstate == NULL)
814 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 if (tstate->dict == NULL) {
817 PyObject *d;
818 tstate->dict = d = PyDict_New();
819 if (d == NULL)
820 PyErr_Clear();
821 }
822 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000823}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000824
825
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000826/* Asynchronously raise an exception in a thread.
827 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000828 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000829 to call this, or use ctypes. Must be called with the GIL held.
830 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
831 match any known thread id). Can be called with exc=NULL to clear an
832 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000833
834int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200835PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
836{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100837 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 /* Although the GIL is held, a few C API functions can be called
841 * without the GIL held, and in particular some that create and
842 * destroy thread and interpreter states. Those can mutate the
843 * list of thread states we're traversing, so to prevent that we lock
844 * head_mutex for the duration.
845 */
846 HEAD_LOCK();
847 for (p = interp->tstate_head; p != NULL; p = p->next) {
848 if (p->thread_id == id) {
849 /* Tricky: we need to decref the current value
850 * (if any) in p->async_exc, but that can in turn
851 * allow arbitrary Python code to run, including
852 * perhaps calls to this function. To prevent
853 * deadlock, we need to release head_mutex before
854 * the decref.
855 */
856 PyObject *old_exc = p->async_exc;
857 Py_XINCREF(exc);
858 p->async_exc = exc;
859 HEAD_UNLOCK();
860 Py_XDECREF(old_exc);
861 _PyEval_SignalAsyncExc();
862 return 1;
863 }
864 }
865 HEAD_UNLOCK();
866 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000867}
868
869
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000870/* Routines for advanced debuggers, requested by David Beazley.
871 Don't use unless you know what you are doing! */
872
873PyInterpreterState *
874PyInterpreterState_Head(void)
875{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600876 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000877}
878
879PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700880PyInterpreterState_Main(void)
881{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600882 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700883}
884
885PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000886PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000888}
889
890PyThreadState *
891PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000893}
894
895PyThreadState *
896PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000898}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000899
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000900/* The implementation of sys._current_frames(). This is intended to be
901 called with the GIL held, as it will be when called via
902 sys._current_frames(). It's possible it would work fine even without
903 the GIL held, but haven't thought enough about that.
904*/
905PyObject *
906_PyThread_CurrentFrames(void)
907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 PyObject *result;
909 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 result = PyDict_New();
912 if (result == NULL)
913 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 /* for i in all interpreters:
916 * for t in all of i's thread states:
917 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200918 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 * need to grab head_mutex for the duration.
920 */
921 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600922 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 PyThreadState *t;
924 for (t = i->tstate_head; t != NULL; t = t->next) {
925 PyObject *id;
926 int stat;
927 struct _frame *frame = t->frame;
928 if (frame == NULL)
929 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200930 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 if (id == NULL)
932 goto Fail;
933 stat = PyDict_SetItem(result, id, (PyObject *)frame);
934 Py_DECREF(id);
935 if (stat < 0)
936 goto Fail;
937 }
938 }
939 HEAD_UNLOCK();
940 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000941
942 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 HEAD_UNLOCK();
944 Py_DECREF(result);
945 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000946}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000947
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000948/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000949
950/* Keep this as a static, as it is not reliable! It can only
951 ever be compared to the state for the *current* thread.
952 * If not equal, then it doesn't matter that the actual
953 value may change immediately after comparison, as it can't
954 possibly change to the current thread's state.
955 * If equal, then the current thread holds the lock, so the value can't
956 change until we yield the lock.
957*/
958static int
959PyThreadState_IsCurrent(PyThreadState *tstate)
960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 /* Must be the tstate for this thread */
962 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100963 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000964}
965
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000966/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000967 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000968*/
Tim Peters19717fa2004-10-09 17:38:29 +0000969void
970_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000971{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900973 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
974 Py_FatalError("Could not allocate TSS entry");
975 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600976 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900977 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000979
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000981}
982
Victor Stinner861d9ab2016-03-16 22:45:24 +0100983PyInterpreterState *
984_PyGILState_GetInterpreterStateUnsafe(void)
985{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600986 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100987}
988
Tim Peters19717fa2004-10-09 17:38:29 +0000989void
990_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000991{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900992 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600993 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000994}
995
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900996/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200997 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900998 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200999 */
1000void
1001_PyGILState_Reinit(void)
1002{
Victor Stinner5d926472018-03-06 14:31:37 +01001003 /* Force default allocator, since _PyRuntimeState_Fini() must
1004 use the same allocator than this function. */
1005 PyMemAllocatorEx old_alloc;
1006 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1007
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001008 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +01001009
1010 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1011
1012 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001013 Py_FatalError("Can't initialize threads for interpreter");
Victor Stinner5d926472018-03-06 14:31:37 +01001014 }
1015
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001016 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001017 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
1018 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1019 Py_FatalError("Could not allocate TSS entry");
1020 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001021
Charles-François Natalia233df82011-11-22 19:49:51 +01001022 /* If the thread had an associated auto thread state, reassociate it with
1023 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001024 if (tstate &&
1025 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
1026 {
1027 Py_FatalError("Couldn't create autoTSSkey mapping");
1028 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001029}
1030
Michael W. Hudson188d4362005-06-20 16:52:57 +00001031/* When a thread state is created for a thread by some mechanism other than
1032 PyGILState_Ensure, it's important that the GILState machinery knows about
1033 it so it doesn't try to create another thread state for the thread (this is
1034 a better fix for SF bug #1010677 than the first one attempted).
1035*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001036static void
Michael W. Hudson188d4362005-06-20 16:52:57 +00001037_PyGILState_NoteThreadState(PyThreadState* tstate)
1038{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001039 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001040 threadstate created in Py_Initialize(). Don't do anything for now
1041 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001042 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001044
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001045 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 The only situation where you can legitimately have more than one
1048 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001049 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001050
Victor Stinner590cebe2013-12-13 11:08:56 +01001051 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1052 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001053
Victor Stinner590cebe2013-12-13 11:08:56 +01001054 The first thread state created for that given OS level thread will
1055 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001057 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
1058 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1059 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001060 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001061 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001062 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001063 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 /* PyGILState_Release must not try to delete this thread state. */
1066 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001067}
1068
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001069/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001070PyThreadState *
1071PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001072{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001073 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001075 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001076}
1077
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001078int
1079PyGILState_Check(void)
1080{
Victor Stinner8a1be612016-03-14 22:07:55 +01001081 PyThreadState *tstate;
1082
1083 if (!_PyGILState_check_enabled)
1084 return 1;
1085
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001086 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001087 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001088 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001089
1090 tstate = GET_TSTATE();
1091 if (tstate == NULL)
1092 return 0;
1093
1094 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001095}
1096
Tim Peters19717fa2004-10-09 17:38:29 +00001097PyGILState_STATE
1098PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 int current;
1101 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001102 int need_init_threads = 0;
1103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 /* Note that we do not auto-init Python here - apart from
1105 potential races with 2 threads auto-initializing, pep-311
1106 spells out other issues. Embedders are expected to have
1107 called Py_Initialize() and usually PyEval_InitThreads().
1108 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001109 /* Py_Initialize() hasn't been called! */
1110 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001111
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001112 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001114 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001117 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 if (tcur == NULL)
1119 Py_FatalError("Couldn't create thread-state for new thread");
1120 /* This is our thread state! We'll need to delete it in the
1121 matching call to PyGILState_Release(). */
1122 tcur->gilstate_counter = 0;
1123 current = 0; /* new thread state is never current */
1124 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001125 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001127 }
1128
1129 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001131 }
1132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 /* Update our counter in the thread-state - no need for locks:
1134 - tcur will remain valid as we hold the GIL.
1135 - the counter is safe as we are the only thread "allowed"
1136 to modify this value
1137 */
1138 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001139
1140 if (need_init_threads) {
1141 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1142 called from a new thread for the first time, we need the create the
1143 GIL. */
1144 PyEval_InitThreads();
1145 }
1146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001148}
1149
Tim Peters19717fa2004-10-09 17:38:29 +00001150void
1151PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001152{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001153 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1154 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 if (tcur == NULL)
1156 Py_FatalError("auto-releasing thread-state, "
1157 "but no thread-state for this thread");
1158 /* We must hold the GIL and have our thread state current */
1159 /* XXX - remove the check - the assert should be fine,
1160 but while this is very new (April 2003), the extra check
1161 by release-only users can't hurt.
1162 */
1163 if (! PyThreadState_IsCurrent(tcur))
1164 Py_FatalError("This thread state must be current when releasing");
1165 assert(PyThreadState_IsCurrent(tcur));
1166 --tcur->gilstate_counter;
1167 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 /* If we're going to destroy this thread-state, we must
1170 * clear it while the GIL is held, as destructors may run.
1171 */
1172 if (tcur->gilstate_counter == 0) {
1173 /* can't have been locked when we created it */
1174 assert(oldstate == PyGILState_UNLOCKED);
1175 PyThreadState_Clear(tcur);
1176 /* Delete the thread-state. Note this releases the GIL too!
1177 * It's vital that the GIL be held here, to avoid shutdown
1178 * races; see bugs 225673 and 1061968 (that nasty bug has a
1179 * habit of coming back).
1180 */
1181 PyThreadState_DeleteCurrent();
1182 }
1183 /* Release the lock if necessary */
1184 else if (oldstate == PyGILState_UNLOCKED)
1185 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001186}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001187
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001188
Eric Snow7f8bfc92018-01-29 18:23:44 -07001189/**************************/
1190/* cross-interpreter data */
1191/**************************/
1192
1193/* cross-interpreter data */
1194
1195crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1196
1197/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1198 to keep the registry code separate. */
1199static crossinterpdatafunc
1200_lookup_getdata(PyObject *obj)
1201{
1202 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1203 if (getdata == NULL && PyErr_Occurred() == 0)
1204 PyErr_Format(PyExc_ValueError,
1205 "%S does not support cross-interpreter data", obj);
1206 return getdata;
1207}
1208
1209int
1210_PyObject_CheckCrossInterpreterData(PyObject *obj)
1211{
1212 crossinterpdatafunc getdata = _lookup_getdata(obj);
1213 if (getdata == NULL) {
1214 return -1;
1215 }
1216 return 0;
1217}
1218
1219static int
1220_check_xidata(_PyCrossInterpreterData *data)
1221{
1222 // data->data can be anything, including NULL, so we don't check it.
1223
1224 // data->obj may be NULL, so we don't check it.
1225
1226 if (data->interp < 0) {
1227 PyErr_SetString(PyExc_SystemError, "missing interp");
1228 return -1;
1229 }
1230
1231 if (data->new_object == NULL) {
1232 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1233 return -1;
1234 }
1235
1236 // data->free may be NULL, so we don't check it.
1237
1238 return 0;
1239}
1240
1241int
1242_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1243{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001244 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001245 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001246 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001247
1248 // Reset data before re-populating.
1249 *data = (_PyCrossInterpreterData){0};
1250 data->free = PyMem_RawFree; // Set a default that may be overridden.
1251
1252 // Call the "getdata" func for the object.
1253 Py_INCREF(obj);
1254 crossinterpdatafunc getdata = _lookup_getdata(obj);
1255 if (getdata == NULL) {
1256 Py_DECREF(obj);
1257 return -1;
1258 }
1259 int res = getdata(obj, data);
1260 Py_DECREF(obj);
1261 if (res != 0) {
1262 return -1;
1263 }
1264
1265 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001266 data->interp = interp->id;
1267 if (_check_xidata(data) != 0) {
1268 _PyCrossInterpreterData_Release(data);
1269 return -1;
1270 }
1271
1272 return 0;
1273}
1274
Eric Snow63799132018-06-01 18:45:20 -06001275static void
1276_release_xidata(void *arg)
1277{
1278 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1279 if (data->free != NULL) {
1280 data->free(data->data);
1281 }
1282 Py_XDECREF(data->obj);
1283}
1284
1285static void
1286_call_in_interpreter(PyInterpreterState *interp,
1287 void (*func)(void *), void *arg)
1288{
1289 /* We would use Py_AddPendingCall() if it weren't specific to the
1290 * main interpreter (see bpo-33608). In the meantime we take a
1291 * naive approach.
1292 */
1293 PyThreadState *save_tstate = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001294 if (interp != _PyInterpreterState_Get()) {
Eric Snow63799132018-06-01 18:45:20 -06001295 // XXX Using the "head" thread isn't strictly correct.
1296 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1297 // XXX Possible GILState issues?
1298 save_tstate = PyThreadState_Swap(tstate);
1299 }
1300
1301 func(arg);
1302
1303 // Switch back.
1304 if (save_tstate != NULL) {
1305 PyThreadState_Swap(save_tstate);
1306 }
1307}
1308
Eric Snow7f8bfc92018-01-29 18:23:44 -07001309void
1310_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1311{
1312 if (data->data == NULL && data->obj == NULL) {
1313 // Nothing to release!
1314 return;
1315 }
1316
1317 // Switch to the original interpreter.
1318 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1319 if (interp == NULL) {
1320 // The intepreter was already destroyed.
1321 if (data->free != NULL) {
1322 // XXX Someone leaked some memory...
1323 }
1324 return;
1325 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001326
Eric Snow7f8bfc92018-01-29 18:23:44 -07001327 // "Release" the data and/or the object.
Eric Snow63799132018-06-01 18:45:20 -06001328 _call_in_interpreter(interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001329}
1330
1331PyObject *
1332_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1333{
1334 return data->new_object(data);
1335}
1336
1337/* registry of {type -> crossinterpdatafunc} */
1338
1339/* For now we use a global registry of shareable classes. An
1340 alternative would be to add a tp_* slot for a class's
1341 crossinterpdatafunc. It would be simpler and more efficient. */
1342
1343static int
1344_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1345{
1346 // Note that we effectively replace already registered classes
1347 // rather than failing.
1348 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1349 if (newhead == NULL)
1350 return -1;
1351 newhead->cls = cls;
1352 newhead->getdata = getdata;
1353 newhead->next = _PyRuntime.xidregistry.head;
1354 _PyRuntime.xidregistry.head = newhead;
1355 return 0;
1356}
1357
1358static void _register_builtins_for_crossinterpreter_data(void);
1359
1360int
1361_PyCrossInterpreterData_Register_Class(PyTypeObject *cls,
1362 crossinterpdatafunc getdata)
1363{
1364 if (!PyType_Check(cls)) {
1365 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1366 return -1;
1367 }
1368 if (getdata == NULL) {
1369 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1370 return -1;
1371 }
1372
1373 // Make sure the class isn't ever deallocated.
1374 Py_INCREF((PyObject *)cls);
1375
1376 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1377 if (_PyRuntime.xidregistry.head == NULL) {
1378 _register_builtins_for_crossinterpreter_data();
1379 }
1380 int res = _register_xidata(cls, getdata);
1381 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1382 return res;
1383}
1384
Eric Snow6d2cd902018-05-16 15:04:57 -04001385/* Cross-interpreter objects are looked up by exact match on the class.
1386 We can reassess this policy when we move from a global registry to a
1387 tp_* slot. */
1388
Eric Snow7f8bfc92018-01-29 18:23:44 -07001389crossinterpdatafunc
1390_PyCrossInterpreterData_Lookup(PyObject *obj)
1391{
1392 PyObject *cls = PyObject_Type(obj);
1393 crossinterpdatafunc getdata = NULL;
1394 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1395 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1396 if (cur == NULL) {
1397 _register_builtins_for_crossinterpreter_data();
1398 cur = _PyRuntime.xidregistry.head;
1399 }
1400 for(; cur != NULL; cur = cur->next) {
1401 if (cur->cls == (PyTypeObject *)cls) {
1402 getdata = cur->getdata;
1403 break;
1404 }
1405 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001406 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001407 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1408 return getdata;
1409}
1410
1411/* cross-interpreter data for builtin types */
1412
Eric Snow6d2cd902018-05-16 15:04:57 -04001413struct _shared_bytes_data {
1414 char *bytes;
1415 Py_ssize_t len;
1416};
1417
Eric Snow7f8bfc92018-01-29 18:23:44 -07001418static PyObject *
1419_new_bytes_object(_PyCrossInterpreterData *data)
1420{
Eric Snow6d2cd902018-05-16 15:04:57 -04001421 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1422 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001423}
1424
1425static int
1426_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1427{
Eric Snow6d2cd902018-05-16 15:04:57 -04001428 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1429 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1430 return -1;
1431 }
1432 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001433 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001434 data->obj = obj; // Will be "released" (decref'ed) when data released.
1435 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001436 data->free = PyMem_Free;
1437 return 0;
1438}
1439
1440struct _shared_str_data {
1441 int kind;
1442 const void *buffer;
1443 Py_ssize_t len;
1444};
1445
1446static PyObject *
1447_new_str_object(_PyCrossInterpreterData *data)
1448{
1449 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1450 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1451}
1452
1453static int
1454_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1455{
1456 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1457 shared->kind = PyUnicode_KIND(obj);
1458 shared->buffer = PyUnicode_DATA(obj);
1459 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1460 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001461 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001462 data->obj = obj; // Will be "released" (decref'ed) when data released.
1463 data->new_object = _new_str_object;
1464 data->free = PyMem_Free;
1465 return 0;
1466}
1467
1468static PyObject *
1469_new_long_object(_PyCrossInterpreterData *data)
1470{
1471 return PyLong_FromLongLong((int64_t)(data->data));
1472}
1473
1474static int
1475_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1476{
1477 int64_t value = PyLong_AsLongLong(obj);
1478 if (value == -1 && PyErr_Occurred()) {
1479 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1480 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1481 }
1482 return -1;
1483 }
1484 data->data = (void *)value;
1485 data->obj = NULL;
1486 data->new_object = _new_long_object;
1487 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001488 return 0;
1489}
1490
1491static PyObject *
1492_new_none_object(_PyCrossInterpreterData *data)
1493{
1494 // XXX Singleton refcounts are problematic across interpreters...
1495 Py_INCREF(Py_None);
1496 return Py_None;
1497}
1498
1499static int
1500_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1501{
1502 data->data = NULL;
1503 // data->obj remains NULL
1504 data->new_object = _new_none_object;
1505 data->free = NULL; // There is nothing to free.
1506 return 0;
1507}
1508
1509static void
1510_register_builtins_for_crossinterpreter_data(void)
1511{
1512 // None
1513 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1514 Py_FatalError("could not register None for cross-interpreter sharing");
1515 }
1516
Eric Snow6d2cd902018-05-16 15:04:57 -04001517 // int
1518 if (_register_xidata(&PyLong_Type, _long_shared) != 0) {
1519 Py_FatalError("could not register int for cross-interpreter sharing");
1520 }
1521
Eric Snow7f8bfc92018-01-29 18:23:44 -07001522 // bytes
1523 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1524 Py_FatalError("could not register bytes for cross-interpreter sharing");
1525 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001526
1527 // str
1528 if (_register_xidata(&PyUnicode_Type, _str_shared) != 0) {
1529 Py_FatalError("could not register str for cross-interpreter sharing");
1530 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001531}
1532
1533
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001534#ifdef __cplusplus
1535}
1536#endif