blob: 98e954d9d91db6995cebb7d5ceae44cbd6899dc2 [file] [log] [blame]
Guido van Rossuma027efa1997-05-05 20:56:21 +00001
2/* Thread and interpreter state structures and their interfaces */
3
4#include "Python.h"
Victor Stinner2be00d92018-10-31 20:19:24 +01005#include "internal/mem.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06006#include "internal/pystate.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +00007
Victor Stinner9204fb82018-10-30 15:13:17 +01008#define _PyThreadState_SET(value) \
9 _Py_atomic_store_relaxed(&_PyRuntime.gilstate.tstate_current, \
10 (uintptr_t)(value))
Victor Stinnerb02ef712016-01-22 14:09:55 +010011
Victor Stinnerbfd316e2016-01-20 11:12:38 +010012
Tim Peters84705582004-10-10 02:47:33 +000013/* --------------------------------------------------------------------------
14CAUTION
15
Victor Stinner1a7425f2013-07-07 16:25:15 +020016Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
17number of these functions are advertised as safe to call when the GIL isn't
18held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
19debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
20to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000021-------------------------------------------------------------------------- */
22
Martin v. Löwisf0473d52001-07-18 16:17:16 +000023#ifdef HAVE_DLOPEN
24#ifdef HAVE_DLFCN_H
25#include <dlfcn.h>
26#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030027#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000028#define RTLD_LAZY 1
29#endif
30#endif
31
Benjamin Peterson43162b82012-04-13 11:58:27 -040032#ifdef __cplusplus
33extern "C" {
34#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000035
Victor Stinner5d39e042017-11-29 17:20:38 +010036static _PyInitError
37_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060038{
39 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010040
Eric Snow2ebc5ce2017-09-07 23:51:28 -060041 _PyGC_Initialize(&runtime->gc);
42 _PyEval_Initialize(&runtime->ceval);
Michael W. Hudson188d4362005-06-20 16:52:57 +000043
Eric Snow2ebc5ce2017-09-07 23:51:28 -060044 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080045
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090046 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
47 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080048 Py_tss_t initial = Py_tss_NEEDS_INIT;
49 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000050
Eric Snow2ebc5ce2017-09-07 23:51:28 -060051 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080052 if (runtime->interpreters.mutex == NULL) {
53 return _Py_INIT_ERR("Can't initialize threads for interpreter");
54 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060055 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070056
57 runtime->xidregistry.mutex = PyThread_allocate_lock();
58 if (runtime->xidregistry.mutex == NULL) {
59 return _Py_INIT_ERR("Can't initialize threads for cross-interpreter data registry");
60 }
61
Victor Stinnerf7e5b562017-11-15 15:48:08 -080062 return _Py_INIT_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060063}
Eric Snow05351c12017-09-05 21:43:08 -070064
Victor Stinner5d39e042017-11-29 17:20:38 +010065_PyInitError
66_PyRuntimeState_Init(_PyRuntimeState *runtime)
67{
68 /* Force default allocator, since _PyRuntimeState_Fini() must
69 use the same allocator than this function. */
70 PyMemAllocatorEx old_alloc;
71 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
72
73 _PyInitError err = _PyRuntimeState_Init_impl(runtime);
74
75 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
76 return err;
77}
78
Eric Snow2ebc5ce2017-09-07 23:51:28 -060079void
80_PyRuntimeState_Fini(_PyRuntimeState *runtime)
81{
Victor Stinner5d39e042017-11-29 17:20:38 +010082 /* Force the allocator used by _PyRuntimeState_Init(). */
83 PyMemAllocatorEx old_alloc;
84 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -080085
Eric Snow2ebc5ce2017-09-07 23:51:28 -060086 if (runtime->interpreters.mutex != NULL) {
87 PyThread_free_lock(runtime->interpreters.mutex);
88 runtime->interpreters.mutex = NULL;
89 }
Victor Stinnerccb04422017-11-16 03:20:31 -080090
91 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060092}
93
94#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
95 WAIT_LOCK)
96#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -070097
Michael W. Hudson188d4362005-06-20 16:52:57 +000098static void _PyGILState_NoteThreadState(PyThreadState* tstate);
99
Victor Stinnera7368ac2017-11-15 18:11:45 -0800100_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600101_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700102{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600103 runtime->interpreters.next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100104
105 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
106 Create a new mutex if needed. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600107 if (runtime->interpreters.mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100108 /* Force default allocator, since _PyRuntimeState_Fini() must
109 use the same allocator than this function. */
110 PyMemAllocatorEx old_alloc;
111 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
112
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600113 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100114
115 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
116
Victor Stinnera7368ac2017-11-15 18:11:45 -0800117 if (runtime->interpreters.mutex == NULL) {
118 return _Py_INIT_ERR("Can't initialize threads for interpreter");
119 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600120 }
Victor Stinner5d926472018-03-06 14:31:37 +0100121
Victor Stinnera7368ac2017-11-15 18:11:45 -0800122 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700123}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000124
125PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000126PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200129 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000130
Victor Stinnerd4341102017-11-23 00:12:09 +0100131 if (interp == NULL) {
132 return NULL;
133 }
134
Eric Snow4c6955e2018-02-16 18:53:40 -0700135 interp->id_refcount = -1;
136 interp->id_mutex = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100137 interp->modules = NULL;
138 interp->modules_by_index = NULL;
139 interp->sysdict = NULL;
140 interp->builtins = NULL;
141 interp->builtins_copy = NULL;
142 interp->tstate_head = NULL;
143 interp->check_interval = 100;
144 interp->num_threads = 0;
145 interp->pythread_stacksize = 0;
146 interp->codec_search_path = NULL;
147 interp->codec_search_cache = NULL;
148 interp->codec_error_registry = NULL;
149 interp->codecs_initialized = 0;
150 interp->fscodec_initialized = 0;
151 interp->core_config = _PyCoreConfig_INIT;
152 interp->config = _PyMainInterpreterConfig_INIT;
153 interp->importlib = NULL;
154 interp->import_func = NULL;
155 interp->eval_frame = _PyEval_EvalFrameDefault;
156 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000157#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300158#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100159 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000160#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100161 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000162#endif
163#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200164#ifdef HAVE_FORK
Victor Stinnerd4341102017-11-23 00:12:09 +0100165 interp->before_forkers = NULL;
166 interp->after_forkers_parent = NULL;
167 interp->after_forkers_child = NULL;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200168#endif
Marcel Plch776407f2017-12-20 11:17:58 +0100169 interp->pyexitfunc = NULL;
170 interp->pyexitmodule = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000171
Victor Stinnerd4341102017-11-23 00:12:09 +0100172 HEAD_LOCK();
Victor Stinnerd4341102017-11-23 00:12:09 +0100173 if (_PyRuntime.interpreters.next_id < 0) {
174 /* overflow or Py_Initialize() not called! */
175 PyErr_SetString(PyExc_RuntimeError,
176 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100177 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100178 interp = NULL;
179 } else {
180 interp->id = _PyRuntime.interpreters.next_id;
181 _PyRuntime.interpreters.next_id += 1;
Pablo Galindo95d630e2018-08-31 22:49:29 +0100182 interp->next = _PyRuntime.interpreters.head;
183 if (_PyRuntime.interpreters.main == NULL) {
184 _PyRuntime.interpreters.main = interp;
185 }
186 _PyRuntime.interpreters.head = interp;
Victor Stinnerd4341102017-11-23 00:12:09 +0100187 }
188 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000189
Pablo Galindo95d630e2018-08-31 22:49:29 +0100190 if (interp == NULL) {
191 return NULL;
192 }
193
Yury Selivanovf23746a2018-01-22 19:11:18 -0500194 interp->tstate_next_unique_id = 0;
195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000197}
198
199
200void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000201PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 PyThreadState *p;
204 HEAD_LOCK();
205 for (p = interp->tstate_head; p != NULL; p = p->next)
206 PyThreadState_Clear(p);
207 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100208 _PyCoreConfig_Clear(&interp->core_config);
209 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 Py_CLEAR(interp->codec_search_path);
211 Py_CLEAR(interp->codec_search_cache);
212 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700213 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 Py_CLEAR(interp->sysdict);
216 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200217 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400218 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300219 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200220#ifdef HAVE_FORK
221 Py_CLEAR(interp->before_forkers);
222 Py_CLEAR(interp->after_forkers_parent);
223 Py_CLEAR(interp->after_forkers_child);
224#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000225}
226
227
228static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000229zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 PyThreadState *p;
232 /* No need to lock the mutex here because this should only happen
233 when the threads are all really dead (XXX famous last words). */
234 while ((p = interp->tstate_head) != NULL) {
235 PyThreadState_Delete(p);
236 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000237}
238
239
240void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000241PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 PyInterpreterState **p;
244 zapthreads(interp);
245 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600246 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 if (*p == NULL)
248 Py_FatalError(
249 "PyInterpreterState_Delete: invalid interp");
250 if (*p == interp)
251 break;
252 }
253 if (interp->tstate_head != NULL)
254 Py_FatalError("PyInterpreterState_Delete: remaining threads");
255 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600256 if (_PyRuntime.interpreters.main == interp) {
257 _PyRuntime.interpreters.main = NULL;
258 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700259 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
260 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 HEAD_UNLOCK();
Eric Snow4c6955e2018-02-16 18:53:40 -0700262 if (interp->id_mutex != NULL) {
263 PyThread_free_lock(interp->id_mutex);
264 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200265 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000266}
267
268
Eric Snow59032962018-09-14 14:17:20 -0700269/*
270 * Delete all interpreter states except the main interpreter. If there
271 * is a current interpreter state, it *must* be the main interpreter.
272 */
273void
274_PyInterpreterState_DeleteExceptMain()
275{
276 PyThreadState *tstate = PyThreadState_Swap(NULL);
277 if (tstate != NULL && tstate->interp != _PyRuntime.interpreters.main) {
278 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
279 }
280
281 HEAD_LOCK();
282 PyInterpreterState *interp = _PyRuntime.interpreters.head;
283 _PyRuntime.interpreters.head = NULL;
284 for (; interp != NULL; interp = interp->next) {
285 if (interp == _PyRuntime.interpreters.main) {
286 _PyRuntime.interpreters.main->next = NULL;
287 _PyRuntime.interpreters.head = interp;
288 continue;
289 }
290
291 PyInterpreterState_Clear(interp); // XXX must activate?
292 zapthreads(interp);
293 if (interp->id_mutex != NULL) {
294 PyThread_free_lock(interp->id_mutex);
295 }
296 PyMem_RawFree(interp);
297 }
298 HEAD_UNLOCK();
299
300 if (_PyRuntime.interpreters.head == NULL) {
301 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
302 }
303 PyThreadState_Swap(tstate);
304}
305
306
Victor Stinnercaba55b2018-08-03 15:33:52 +0200307PyInterpreterState *
308_PyInterpreterState_Get(void)
309{
Victor Stinner9204fb82018-10-30 15:13:17 +0100310 PyThreadState *tstate = PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200311 if (tstate == NULL) {
312 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
313 }
314 PyInterpreterState *interp = tstate->interp;
315 if (interp == NULL) {
316 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
317 }
318 return interp;
319}
320
321
Eric Snowe3774162017-05-22 19:46:40 -0700322int64_t
323PyInterpreterState_GetID(PyInterpreterState *interp)
324{
325 if (interp == NULL) {
326 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
327 return -1;
328 }
329 return interp->id;
330}
331
332
Eric Snow7f8bfc92018-01-29 18:23:44 -0700333PyInterpreterState *
334_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
335{
336 if (requested_id < 0)
337 goto error;
338
339 PyInterpreterState *interp = PyInterpreterState_Head();
340 while (interp != NULL) {
341 PY_INT64_T id = PyInterpreterState_GetID(interp);
342 if (id < 0)
343 return NULL;
344 if (requested_id == id)
345 return interp;
346 interp = PyInterpreterState_Next(interp);
347 }
348
349error:
350 PyErr_Format(PyExc_RuntimeError,
351 "unrecognized interpreter ID %lld", requested_id);
352 return NULL;
353}
354
Eric Snow4c6955e2018-02-16 18:53:40 -0700355
356int
357_PyInterpreterState_IDInitref(PyInterpreterState *interp)
358{
359 if (interp->id_mutex != NULL) {
360 return 0;
361 }
362 interp->id_mutex = PyThread_allocate_lock();
363 if (interp->id_mutex == NULL) {
364 PyErr_SetString(PyExc_RuntimeError,
365 "failed to create init interpreter ID mutex");
366 return -1;
367 }
368 interp->id_refcount = 0;
369 return 0;
370}
371
372
373void
374_PyInterpreterState_IDIncref(PyInterpreterState *interp)
375{
376 if (interp->id_mutex == NULL) {
377 return;
378 }
379 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
380 interp->id_refcount += 1;
381 PyThread_release_lock(interp->id_mutex);
382}
383
384
385void
386_PyInterpreterState_IDDecref(PyInterpreterState *interp)
387{
388 if (interp->id_mutex == NULL) {
389 return;
390 }
391 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
392 assert(interp->id_refcount != 0);
393 interp->id_refcount -= 1;
394 int64_t refcount = interp->id_refcount;
395 PyThread_release_lock(interp->id_mutex);
396
397 if (refcount == 0) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700398 // XXX Using the "head" thread isn't strictly correct.
399 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
400 // XXX Possible GILState issues?
401 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700402 Py_EndInterpreter(tstate);
403 PyThreadState_Swap(save_tstate);
404 }
405}
406
407
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000408/* Default implementation for _PyThreadState_GetFrame */
409static struct _frame *
410threadstate_getframe(PyThreadState *self)
411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000413}
414
Victor Stinner45b9be52010-03-03 23:28:07 +0000415static PyThreadState *
416new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000417{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200418 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 if (_PyThreadState_GetFrame == NULL)
421 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 if (tstate != NULL) {
424 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 tstate->frame = NULL;
427 tstate->recursion_depth = 0;
428 tstate->overflowed = 0;
429 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700430 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 tstate->tracing = 0;
432 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 tstate->gilstate_counter = 0;
434 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 tstate->curexc_type = NULL;
440 tstate->curexc_value = NULL;
441 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000442
Mark Shannonae3087c2017-10-22 22:41:51 +0100443 tstate->exc_state.exc_type = NULL;
444 tstate->exc_state.exc_value = NULL;
445 tstate->exc_state.exc_traceback = NULL;
446 tstate->exc_state.previous_item = NULL;
447 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 tstate->c_profilefunc = NULL;
450 tstate->c_tracefunc = NULL;
451 tstate->c_profileobj = NULL;
452 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000453
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200454 tstate->trash_delete_nesting = 0;
455 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200456 tstate->on_delete = NULL;
457 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200458
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800459 tstate->coroutine_origin_tracking_depth = 0;
460
Yury Selivanov75445082015-05-11 22:57:16 -0400461 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400462 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400463
Yury Selivanoveb636452016-09-08 22:01:51 -0700464 tstate->async_gen_firstiter = NULL;
465 tstate->async_gen_finalizer = NULL;
466
Yury Selivanovf23746a2018-01-22 19:11:18 -0500467 tstate->context = NULL;
468 tstate->context_ver = 1;
469
470 tstate->id = ++interp->tstate_next_unique_id;
471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 if (init)
473 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200476 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200478 if (tstate->next)
479 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 interp->tstate_head = tstate;
481 HEAD_UNLOCK();
482 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000485}
486
Victor Stinner45b9be52010-03-03 23:28:07 +0000487PyThreadState *
488PyThreadState_New(PyInterpreterState *interp)
489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000491}
492
493PyThreadState *
494_PyThreadState_Prealloc(PyInterpreterState *interp)
495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000497}
498
499void
500_PyThreadState_Init(PyThreadState *tstate)
501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000503}
504
Martin v. Löwis1a214512008-06-11 05:26:20 +0000505PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200506PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000507{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200508 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100509 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000511 if (module->m_slots) {
512 return NULL;
513 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 if (index == 0)
515 return NULL;
516 if (state->modules_by_index == NULL)
517 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200518 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 return NULL;
520 res = PyList_GET_ITEM(state->modules_by_index, index);
521 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000522}
523
524int
525_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
526{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000527 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300528 if (!def) {
529 assert(PyErr_Occurred());
530 return -1;
531 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000532 if (def->m_slots) {
533 PyErr_SetString(PyExc_SystemError,
534 "PyState_AddModule called on module with slots");
535 return -1;
536 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100537 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (!state->modules_by_index) {
539 state->modules_by_index = PyList_New(0);
540 if (!state->modules_by_index)
541 return -1;
542 }
543 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
544 if (PyList_Append(state->modules_by_index, Py_None) < 0)
545 return -1;
546 Py_INCREF(module);
547 return PyList_SetItem(state->modules_by_index,
548 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000549}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000550
Martin v. Löwis7800f752012-06-22 12:20:55 +0200551int
552PyState_AddModule(PyObject* module, struct PyModuleDef* def)
553{
554 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100555 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200556 if (!def) {
557 Py_FatalError("PyState_AddModule: Module Definition is NULL");
558 return -1;
559 }
560 index = def->m_base.m_index;
561 if (state->modules_by_index) {
562 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
563 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
564 Py_FatalError("PyState_AddModule: Module already added!");
565 return -1;
566 }
567 }
568 }
569 return _PyState_AddModule(module, def);
570}
571
572int
573PyState_RemoveModule(struct PyModuleDef* def)
574{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000575 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200576 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000577 if (def->m_slots) {
578 PyErr_SetString(PyExc_SystemError,
579 "PyState_RemoveModule called on module with slots");
580 return -1;
581 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100582 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200583 if (index == 0) {
584 Py_FatalError("PyState_RemoveModule: Module index invalid.");
585 return -1;
586 }
587 if (state->modules_by_index == NULL) {
588 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
589 return -1;
590 }
591 if (index > PyList_GET_SIZE(state->modules_by_index)) {
592 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
593 return -1;
594 }
595 return PyList_SetItem(state->modules_by_index, index, Py_None);
596}
597
Antoine Pitrou40322e62013-08-11 00:30:09 +0200598/* used by import.c:PyImport_Cleanup */
599void
600_PyState_ClearModules(void)
601{
Victor Stinner9204fb82018-10-30 15:13:17 +0100602 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200603 if (state->modules_by_index) {
604 Py_ssize_t i;
605 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
606 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
607 if (PyModule_Check(m)) {
608 /* cleanup the saved copy of module dicts */
609 PyModuleDef *md = PyModule_GetDef(m);
610 if (md)
611 Py_CLEAR(md->m_base.m_copy);
612 }
613 }
614 /* Setting modules_by_index to NULL could be dangerous, so we
615 clear the list instead. */
616 if (PyList_SetSlice(state->modules_by_index,
617 0, PyList_GET_SIZE(state->modules_by_index),
618 NULL))
619 PyErr_WriteUnraisable(state->modules_by_index);
620 }
621}
622
Guido van Rossuma027efa1997-05-05 20:56:21 +0000623void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000624PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000625{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200626 int verbose = tstate->interp->core_config.verbose;
627
628 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 fprintf(stderr,
630 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 Py_CLEAR(tstate->dict);
635 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 Py_CLEAR(tstate->curexc_type);
638 Py_CLEAR(tstate->curexc_value);
639 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000640
Mark Shannonae3087c2017-10-22 22:41:51 +0100641 Py_CLEAR(tstate->exc_state.exc_type);
642 Py_CLEAR(tstate->exc_state.exc_value);
643 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300644
Mark Shannonae3087c2017-10-22 22:41:51 +0100645 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200646 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100647 fprintf(stderr,
648 "PyThreadState_Clear: warning: thread still has a generator\n");
649 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 tstate->c_profilefunc = NULL;
652 tstate->c_tracefunc = NULL;
653 Py_CLEAR(tstate->c_profileobj);
654 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400655
656 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700657 Py_CLEAR(tstate->async_gen_firstiter);
658 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500659
660 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000661}
662
663
Guido van Rossum29757862001-01-23 01:46:06 +0000664/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
665static void
666tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if (tstate == NULL)
670 Py_FatalError("PyThreadState_Delete: NULL tstate");
671 interp = tstate->interp;
672 if (interp == NULL)
673 Py_FatalError("PyThreadState_Delete: NULL interp");
674 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200675 if (tstate->prev)
676 tstate->prev->next = tstate->next;
677 else
678 interp->tstate_head = tstate->next;
679 if (tstate->next)
680 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200682 if (tstate->on_delete != NULL) {
683 tstate->on_delete(tstate->on_delete_data);
684 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200685 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000686}
687
688
Guido van Rossum29757862001-01-23 01:46:06 +0000689void
690PyThreadState_Delete(PyThreadState *tstate)
691{
Victor Stinner9204fb82018-10-30 15:13:17 +0100692 if (tstate == PyThreadState_GET())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600694 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900695 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600696 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900697 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600698 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200699 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000700}
701
702
Guido van Rossum29757862001-01-23 01:46:06 +0000703void
704PyThreadState_DeleteCurrent()
705{
Victor Stinner9204fb82018-10-30 15:13:17 +0100706 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (tstate == NULL)
708 Py_FatalError(
709 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100710 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600711 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900712 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600713 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900714 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600715 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100716 _PyThreadState_SET(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000718}
Guido van Rossum29757862001-01-23 01:46:06 +0000719
720
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200721/*
722 * Delete all thread states except the one passed as argument.
723 * Note that, if there is a current thread state, it *must* be the one
724 * passed as argument. Also, this won't touch any other interpreters
725 * than the current one, since we don't know which thread state should
726 * be kept in those other interpreteres.
727 */
728void
729_PyThreadState_DeleteExcept(PyThreadState *tstate)
730{
731 PyInterpreterState *interp = tstate->interp;
732 PyThreadState *p, *next, *garbage;
733 HEAD_LOCK();
734 /* Remove all thread states, except tstate, from the linked list of
735 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200736 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200737 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200738 if (garbage == tstate)
739 garbage = tstate->next;
740 if (tstate->prev)
741 tstate->prev->next = tstate->next;
742 if (tstate->next)
743 tstate->next->prev = tstate->prev;
744 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200745 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200746 HEAD_UNLOCK();
747 /* Clear and deallocate all stale thread states. Even if this
748 executes Python code, we should be safe since it executes
749 in the current thread, not one of the stale threads. */
750 for (p = garbage; p; p = next) {
751 next = p->next;
752 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200753 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200754 }
755}
756
757
Guido van Rossuma027efa1997-05-05 20:56:21 +0000758PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100759_PyThreadState_UncheckedGet(void)
760{
Victor Stinner9204fb82018-10-30 15:13:17 +0100761 return PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100762}
763
764
765PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000766PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000767{
Victor Stinner9204fb82018-10-30 15:13:17 +0100768 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 if (tstate == NULL)
770 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000773}
774
775
776PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000777PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000778{
Victor Stinner9204fb82018-10-30 15:13:17 +0100779 PyThreadState *oldts = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000780
Victor Stinner9204fb82018-10-30 15:13:17 +0100781 _PyThreadState_SET(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 /* It should not be possible for more than one thread state
783 to be used for a thread. Check this the best we can in debug
784 builds.
785 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200786#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (newts) {
788 /* This can be called from PyEval_RestoreThread(). Similar
789 to it, we need to ensure errno doesn't change.
790 */
791 int err = errno;
792 PyThreadState *check = PyGILState_GetThisThreadState();
793 if (check && check->interp == newts->interp && check != newts)
794 Py_FatalError("Invalid thread state for this thread");
795 errno = err;
796 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000797#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000799}
Guido van Rossumede04391998-04-10 20:18:25 +0000800
801/* An extension mechanism to store arbitrary additional per-thread state.
802 PyThreadState_GetDict() returns a dictionary that can be used to hold such
803 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000804 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
805 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000806
807PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000808PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000809{
Victor Stinner9204fb82018-10-30 15:13:17 +0100810 PyThreadState *tstate = PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 if (tstate == NULL)
812 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 if (tstate->dict == NULL) {
815 PyObject *d;
816 tstate->dict = d = PyDict_New();
817 if (d == NULL)
818 PyErr_Clear();
819 }
820 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000821}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000822
823
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000824/* Asynchronously raise an exception in a thread.
825 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000826 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000827 to call this, or use ctypes. Must be called with the GIL held.
828 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
829 match any known thread id). Can be called with exc=NULL to clear an
830 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000831
832int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200833PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
834{
Victor Stinner9204fb82018-10-30 15:13:17 +0100835 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000837
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 /* Although the GIL is held, a few C API functions can be called
839 * without the GIL held, and in particular some that create and
840 * destroy thread and interpreter states. Those can mutate the
841 * list of thread states we're traversing, so to prevent that we lock
842 * head_mutex for the duration.
843 */
844 HEAD_LOCK();
845 for (p = interp->tstate_head; p != NULL; p = p->next) {
846 if (p->thread_id == id) {
847 /* Tricky: we need to decref the current value
848 * (if any) in p->async_exc, but that can in turn
849 * allow arbitrary Python code to run, including
850 * perhaps calls to this function. To prevent
851 * deadlock, we need to release head_mutex before
852 * the decref.
853 */
854 PyObject *old_exc = p->async_exc;
855 Py_XINCREF(exc);
856 p->async_exc = exc;
857 HEAD_UNLOCK();
858 Py_XDECREF(old_exc);
859 _PyEval_SignalAsyncExc();
860 return 1;
861 }
862 }
863 HEAD_UNLOCK();
864 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000865}
866
867
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000868/* Routines for advanced debuggers, requested by David Beazley.
869 Don't use unless you know what you are doing! */
870
871PyInterpreterState *
872PyInterpreterState_Head(void)
873{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600874 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000875}
876
877PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700878PyInterpreterState_Main(void)
879{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600880 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700881}
882
883PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000884PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000886}
887
888PyThreadState *
889PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000891}
892
893PyThreadState *
894PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000896}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000897
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000898/* The implementation of sys._current_frames(). This is intended to be
899 called with the GIL held, as it will be when called via
900 sys._current_frames(). It's possible it would work fine even without
901 the GIL held, but haven't thought enough about that.
902*/
903PyObject *
904_PyThread_CurrentFrames(void)
905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 PyObject *result;
907 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 result = PyDict_New();
910 if (result == NULL)
911 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 /* for i in all interpreters:
914 * for t in all of i's thread states:
915 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200916 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 * need to grab head_mutex for the duration.
918 */
919 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600920 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyThreadState *t;
922 for (t = i->tstate_head; t != NULL; t = t->next) {
923 PyObject *id;
924 int stat;
925 struct _frame *frame = t->frame;
926 if (frame == NULL)
927 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200928 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 if (id == NULL)
930 goto Fail;
931 stat = PyDict_SetItem(result, id, (PyObject *)frame);
932 Py_DECREF(id);
933 if (stat < 0)
934 goto Fail;
935 }
936 }
937 HEAD_UNLOCK();
938 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000939
940 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 HEAD_UNLOCK();
942 Py_DECREF(result);
943 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000944}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000945
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000946/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000947
948/* Keep this as a static, as it is not reliable! It can only
949 ever be compared to the state for the *current* thread.
950 * If not equal, then it doesn't matter that the actual
951 value may change immediately after comparison, as it can't
952 possibly change to the current thread's state.
953 * If equal, then the current thread holds the lock, so the value can't
954 change until we yield the lock.
955*/
956static int
957PyThreadState_IsCurrent(PyThreadState *tstate)
958{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 /* Must be the tstate for this thread */
960 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinner9204fb82018-10-30 15:13:17 +0100961 return tstate == PyThreadState_GET();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000962}
963
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000964/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000965 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000966*/
Tim Peters19717fa2004-10-09 17:38:29 +0000967void
968_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000969{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900971 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
972 Py_FatalError("Could not allocate TSS entry");
973 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600974 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900975 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000979}
980
Victor Stinner861d9ab2016-03-16 22:45:24 +0100981PyInterpreterState *
982_PyGILState_GetInterpreterStateUnsafe(void)
983{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600984 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100985}
986
Tim Peters19717fa2004-10-09 17:38:29 +0000987void
988_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000989{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900990 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600991 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000992}
993
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900994/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200995 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900996 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200997 */
998void
999_PyGILState_Reinit(void)
1000{
Victor Stinner5d926472018-03-06 14:31:37 +01001001 /* Force default allocator, since _PyRuntimeState_Fini() must
1002 use the same allocator than this function. */
1003 PyMemAllocatorEx old_alloc;
1004 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1005
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001006 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +01001007
1008 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1009
1010 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001011 Py_FatalError("Can't initialize threads for interpreter");
Victor Stinner5d926472018-03-06 14:31:37 +01001012 }
1013
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001014 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001015 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
1016 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1017 Py_FatalError("Could not allocate TSS entry");
1018 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001019
Charles-François Natalia233df82011-11-22 19:49:51 +01001020 /* If the thread had an associated auto thread state, reassociate it with
1021 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001022 if (tstate &&
1023 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
1024 {
1025 Py_FatalError("Couldn't create autoTSSkey mapping");
1026 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001027}
1028
Michael W. Hudson188d4362005-06-20 16:52:57 +00001029/* When a thread state is created for a thread by some mechanism other than
1030 PyGILState_Ensure, it's important that the GILState machinery knows about
1031 it so it doesn't try to create another thread state for the thread (this is
1032 a better fix for SF bug #1010677 than the first one attempted).
1033*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001034static void
Michael W. Hudson188d4362005-06-20 16:52:57 +00001035_PyGILState_NoteThreadState(PyThreadState* tstate)
1036{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001037 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001038 threadstate created in Py_Initialize(). Don't do anything for now
1039 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001040 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001042
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001043 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 The only situation where you can legitimately have more than one
1046 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001047 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001048
Victor Stinner590cebe2013-12-13 11:08:56 +01001049 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1050 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001051
Victor Stinner590cebe2013-12-13 11:08:56 +01001052 The first thread state created for that given OS level thread will
1053 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001055 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
1056 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1057 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001058 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001059 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001060 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001061 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 /* PyGILState_Release must not try to delete this thread state. */
1064 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001065}
1066
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001067/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001068PyThreadState *
1069PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001070{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001071 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001073 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001074}
1075
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001076int
1077PyGILState_Check(void)
1078{
Victor Stinner8a1be612016-03-14 22:07:55 +01001079 PyThreadState *tstate;
1080
1081 if (!_PyGILState_check_enabled)
1082 return 1;
1083
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001084 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001085 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001086 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001087
Victor Stinner9204fb82018-10-30 15:13:17 +01001088 tstate = PyThreadState_GET();
Victor Stinner8a1be612016-03-14 22:07:55 +01001089 if (tstate == NULL)
1090 return 0;
1091
1092 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001093}
1094
Tim Peters19717fa2004-10-09 17:38:29 +00001095PyGILState_STATE
1096PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 int current;
1099 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001100 int need_init_threads = 0;
1101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 /* Note that we do not auto-init Python here - apart from
1103 potential races with 2 threads auto-initializing, pep-311
1104 spells out other issues. Embedders are expected to have
1105 called Py_Initialize() and usually PyEval_InitThreads().
1106 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001107 /* Py_Initialize() hasn't been called! */
1108 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001109
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001110 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001112 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001115 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (tcur == NULL)
1117 Py_FatalError("Couldn't create thread-state for new thread");
1118 /* This is our thread state! We'll need to delete it in the
1119 matching call to PyGILState_Release(). */
1120 tcur->gilstate_counter = 0;
1121 current = 0; /* new thread state is never current */
1122 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001123 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001125 }
1126
1127 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001129 }
1130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 /* Update our counter in the thread-state - no need for locks:
1132 - tcur will remain valid as we hold the GIL.
1133 - the counter is safe as we are the only thread "allowed"
1134 to modify this value
1135 */
1136 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001137
1138 if (need_init_threads) {
1139 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1140 called from a new thread for the first time, we need the create the
1141 GIL. */
1142 PyEval_InitThreads();
1143 }
1144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001146}
1147
Tim Peters19717fa2004-10-09 17:38:29 +00001148void
1149PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001150{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001151 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1152 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 if (tcur == NULL)
1154 Py_FatalError("auto-releasing thread-state, "
1155 "but no thread-state for this thread");
1156 /* We must hold the GIL and have our thread state current */
1157 /* XXX - remove the check - the assert should be fine,
1158 but while this is very new (April 2003), the extra check
1159 by release-only users can't hurt.
1160 */
1161 if (! PyThreadState_IsCurrent(tcur))
1162 Py_FatalError("This thread state must be current when releasing");
1163 assert(PyThreadState_IsCurrent(tcur));
1164 --tcur->gilstate_counter;
1165 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 /* If we're going to destroy this thread-state, we must
1168 * clear it while the GIL is held, as destructors may run.
1169 */
1170 if (tcur->gilstate_counter == 0) {
1171 /* can't have been locked when we created it */
1172 assert(oldstate == PyGILState_UNLOCKED);
1173 PyThreadState_Clear(tcur);
1174 /* Delete the thread-state. Note this releases the GIL too!
1175 * It's vital that the GIL be held here, to avoid shutdown
1176 * races; see bugs 225673 and 1061968 (that nasty bug has a
1177 * habit of coming back).
1178 */
1179 PyThreadState_DeleteCurrent();
1180 }
1181 /* Release the lock if necessary */
1182 else if (oldstate == PyGILState_UNLOCKED)
1183 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001184}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001185
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001186
Eric Snow7f8bfc92018-01-29 18:23:44 -07001187/**************************/
1188/* cross-interpreter data */
1189/**************************/
1190
1191/* cross-interpreter data */
1192
1193crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1194
1195/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1196 to keep the registry code separate. */
1197static crossinterpdatafunc
1198_lookup_getdata(PyObject *obj)
1199{
1200 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1201 if (getdata == NULL && PyErr_Occurred() == 0)
1202 PyErr_Format(PyExc_ValueError,
1203 "%S does not support cross-interpreter data", obj);
1204 return getdata;
1205}
1206
1207int
1208_PyObject_CheckCrossInterpreterData(PyObject *obj)
1209{
1210 crossinterpdatafunc getdata = _lookup_getdata(obj);
1211 if (getdata == NULL) {
1212 return -1;
1213 }
1214 return 0;
1215}
1216
1217static int
1218_check_xidata(_PyCrossInterpreterData *data)
1219{
1220 // data->data can be anything, including NULL, so we don't check it.
1221
1222 // data->obj may be NULL, so we don't check it.
1223
1224 if (data->interp < 0) {
1225 PyErr_SetString(PyExc_SystemError, "missing interp");
1226 return -1;
1227 }
1228
1229 if (data->new_object == NULL) {
1230 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1231 return -1;
1232 }
1233
1234 // data->free may be NULL, so we don't check it.
1235
1236 return 0;
1237}
1238
1239int
1240_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1241{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001242 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001243 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001244 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001245
1246 // Reset data before re-populating.
1247 *data = (_PyCrossInterpreterData){0};
1248 data->free = PyMem_RawFree; // Set a default that may be overridden.
1249
1250 // Call the "getdata" func for the object.
1251 Py_INCREF(obj);
1252 crossinterpdatafunc getdata = _lookup_getdata(obj);
1253 if (getdata == NULL) {
1254 Py_DECREF(obj);
1255 return -1;
1256 }
1257 int res = getdata(obj, data);
1258 Py_DECREF(obj);
1259 if (res != 0) {
1260 return -1;
1261 }
1262
1263 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001264 data->interp = interp->id;
1265 if (_check_xidata(data) != 0) {
1266 _PyCrossInterpreterData_Release(data);
1267 return -1;
1268 }
1269
1270 return 0;
1271}
1272
Eric Snow63799132018-06-01 18:45:20 -06001273static void
1274_release_xidata(void *arg)
1275{
1276 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1277 if (data->free != NULL) {
1278 data->free(data->data);
1279 }
1280 Py_XDECREF(data->obj);
1281}
1282
1283static void
1284_call_in_interpreter(PyInterpreterState *interp,
1285 void (*func)(void *), void *arg)
1286{
1287 /* We would use Py_AddPendingCall() if it weren't specific to the
1288 * main interpreter (see bpo-33608). In the meantime we take a
1289 * naive approach.
1290 */
1291 PyThreadState *save_tstate = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001292 if (interp != _PyInterpreterState_Get()) {
Eric Snow63799132018-06-01 18:45:20 -06001293 // XXX Using the "head" thread isn't strictly correct.
1294 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1295 // XXX Possible GILState issues?
1296 save_tstate = PyThreadState_Swap(tstate);
1297 }
1298
1299 func(arg);
1300
1301 // Switch back.
1302 if (save_tstate != NULL) {
1303 PyThreadState_Swap(save_tstate);
1304 }
1305}
1306
Eric Snow7f8bfc92018-01-29 18:23:44 -07001307void
1308_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1309{
1310 if (data->data == NULL && data->obj == NULL) {
1311 // Nothing to release!
1312 return;
1313 }
1314
1315 // Switch to the original interpreter.
1316 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1317 if (interp == NULL) {
1318 // The intepreter was already destroyed.
1319 if (data->free != NULL) {
1320 // XXX Someone leaked some memory...
1321 }
1322 return;
1323 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001324
Eric Snow7f8bfc92018-01-29 18:23:44 -07001325 // "Release" the data and/or the object.
Eric Snow63799132018-06-01 18:45:20 -06001326 _call_in_interpreter(interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001327}
1328
1329PyObject *
1330_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1331{
1332 return data->new_object(data);
1333}
1334
1335/* registry of {type -> crossinterpdatafunc} */
1336
1337/* For now we use a global registry of shareable classes. An
1338 alternative would be to add a tp_* slot for a class's
1339 crossinterpdatafunc. It would be simpler and more efficient. */
1340
1341static int
1342_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1343{
1344 // Note that we effectively replace already registered classes
1345 // rather than failing.
1346 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1347 if (newhead == NULL)
1348 return -1;
1349 newhead->cls = cls;
1350 newhead->getdata = getdata;
1351 newhead->next = _PyRuntime.xidregistry.head;
1352 _PyRuntime.xidregistry.head = newhead;
1353 return 0;
1354}
1355
1356static void _register_builtins_for_crossinterpreter_data(void);
1357
1358int
1359_PyCrossInterpreterData_Register_Class(PyTypeObject *cls,
1360 crossinterpdatafunc getdata)
1361{
1362 if (!PyType_Check(cls)) {
1363 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1364 return -1;
1365 }
1366 if (getdata == NULL) {
1367 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1368 return -1;
1369 }
1370
1371 // Make sure the class isn't ever deallocated.
1372 Py_INCREF((PyObject *)cls);
1373
1374 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1375 if (_PyRuntime.xidregistry.head == NULL) {
1376 _register_builtins_for_crossinterpreter_data();
1377 }
1378 int res = _register_xidata(cls, getdata);
1379 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1380 return res;
1381}
1382
Eric Snow6d2cd902018-05-16 15:04:57 -04001383/* Cross-interpreter objects are looked up by exact match on the class.
1384 We can reassess this policy when we move from a global registry to a
1385 tp_* slot. */
1386
Eric Snow7f8bfc92018-01-29 18:23:44 -07001387crossinterpdatafunc
1388_PyCrossInterpreterData_Lookup(PyObject *obj)
1389{
1390 PyObject *cls = PyObject_Type(obj);
1391 crossinterpdatafunc getdata = NULL;
1392 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1393 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1394 if (cur == NULL) {
1395 _register_builtins_for_crossinterpreter_data();
1396 cur = _PyRuntime.xidregistry.head;
1397 }
1398 for(; cur != NULL; cur = cur->next) {
1399 if (cur->cls == (PyTypeObject *)cls) {
1400 getdata = cur->getdata;
1401 break;
1402 }
1403 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001404 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001405 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1406 return getdata;
1407}
1408
1409/* cross-interpreter data for builtin types */
1410
Eric Snow6d2cd902018-05-16 15:04:57 -04001411struct _shared_bytes_data {
1412 char *bytes;
1413 Py_ssize_t len;
1414};
1415
Eric Snow7f8bfc92018-01-29 18:23:44 -07001416static PyObject *
1417_new_bytes_object(_PyCrossInterpreterData *data)
1418{
Eric Snow6d2cd902018-05-16 15:04:57 -04001419 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1420 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001421}
1422
1423static int
1424_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1425{
Eric Snow6d2cd902018-05-16 15:04:57 -04001426 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1427 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1428 return -1;
1429 }
1430 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001431 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001432 data->obj = obj; // Will be "released" (decref'ed) when data released.
1433 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001434 data->free = PyMem_Free;
1435 return 0;
1436}
1437
1438struct _shared_str_data {
1439 int kind;
1440 const void *buffer;
1441 Py_ssize_t len;
1442};
1443
1444static PyObject *
1445_new_str_object(_PyCrossInterpreterData *data)
1446{
1447 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1448 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1449}
1450
1451static int
1452_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1453{
1454 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1455 shared->kind = PyUnicode_KIND(obj);
1456 shared->buffer = PyUnicode_DATA(obj);
1457 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1458 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001459 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001460 data->obj = obj; // Will be "released" (decref'ed) when data released.
1461 data->new_object = _new_str_object;
1462 data->free = PyMem_Free;
1463 return 0;
1464}
1465
1466static PyObject *
1467_new_long_object(_PyCrossInterpreterData *data)
1468{
1469 return PyLong_FromLongLong((int64_t)(data->data));
1470}
1471
1472static int
1473_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1474{
1475 int64_t value = PyLong_AsLongLong(obj);
1476 if (value == -1 && PyErr_Occurred()) {
1477 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1478 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1479 }
1480 return -1;
1481 }
1482 data->data = (void *)value;
1483 data->obj = NULL;
1484 data->new_object = _new_long_object;
1485 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001486 return 0;
1487}
1488
1489static PyObject *
1490_new_none_object(_PyCrossInterpreterData *data)
1491{
1492 // XXX Singleton refcounts are problematic across interpreters...
1493 Py_INCREF(Py_None);
1494 return Py_None;
1495}
1496
1497static int
1498_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1499{
1500 data->data = NULL;
1501 // data->obj remains NULL
1502 data->new_object = _new_none_object;
1503 data->free = NULL; // There is nothing to free.
1504 return 0;
1505}
1506
1507static void
1508_register_builtins_for_crossinterpreter_data(void)
1509{
1510 // None
1511 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1512 Py_FatalError("could not register None for cross-interpreter sharing");
1513 }
1514
Eric Snow6d2cd902018-05-16 15:04:57 -04001515 // int
1516 if (_register_xidata(&PyLong_Type, _long_shared) != 0) {
1517 Py_FatalError("could not register int for cross-interpreter sharing");
1518 }
1519
Eric Snow7f8bfc92018-01-29 18:23:44 -07001520 // bytes
1521 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1522 Py_FatalError("could not register bytes for cross-interpreter sharing");
1523 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001524
1525 // str
1526 if (_register_xidata(&PyUnicode_Type, _str_shared) != 0) {
1527 Py_FatalError("could not register str for cross-interpreter sharing");
1528 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001529}
1530
1531
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001532#ifdef __cplusplus
1533}
1534#endif