blob: 6fe947d36466e51e0192fe24d52f98eaec21ac02 [file] [log] [blame]
Guido van Rossuma027efa1997-05-05 20:56:21 +00001
2/* Thread and interpreter state structures and their interfaces */
3
4#include "Python.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01005#include "pycore_pymem.h"
6#include "pycore_pystate.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +00007
Victor Stinner9204fb82018-10-30 15:13:17 +01008#define _PyThreadState_SET(value) \
9 _Py_atomic_store_relaxed(&_PyRuntime.gilstate.tstate_current, \
10 (uintptr_t)(value))
Victor Stinnerb02ef712016-01-22 14:09:55 +010011
Victor Stinnerbfd316e2016-01-20 11:12:38 +010012
Tim Peters84705582004-10-10 02:47:33 +000013/* --------------------------------------------------------------------------
14CAUTION
15
Victor Stinner1a7425f2013-07-07 16:25:15 +020016Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
17number of these functions are advertised as safe to call when the GIL isn't
18held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
19debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
20to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000021-------------------------------------------------------------------------- */
22
Martin v. Löwisf0473d52001-07-18 16:17:16 +000023#ifdef HAVE_DLOPEN
24#ifdef HAVE_DLFCN_H
25#include <dlfcn.h>
26#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030027#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000028#define RTLD_LAZY 1
29#endif
30#endif
31
Benjamin Peterson43162b82012-04-13 11:58:27 -040032#ifdef __cplusplus
33extern "C" {
34#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000035
Victor Stinner5d39e042017-11-29 17:20:38 +010036static _PyInitError
37_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060038{
39 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010040
Eric Snow2ebc5ce2017-09-07 23:51:28 -060041 _PyGC_Initialize(&runtime->gc);
42 _PyEval_Initialize(&runtime->ceval);
Michael W. Hudson188d4362005-06-20 16:52:57 +000043
Eric Snow2ebc5ce2017-09-07 23:51:28 -060044 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080045
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090046 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
47 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080048 Py_tss_t initial = Py_tss_NEEDS_INIT;
49 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000050
Eric Snow2ebc5ce2017-09-07 23:51:28 -060051 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080052 if (runtime->interpreters.mutex == NULL) {
53 return _Py_INIT_ERR("Can't initialize threads for interpreter");
54 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060055 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070056
57 runtime->xidregistry.mutex = PyThread_allocate_lock();
58 if (runtime->xidregistry.mutex == NULL) {
59 return _Py_INIT_ERR("Can't initialize threads for cross-interpreter data registry");
60 }
61
Victor Stinnerf7e5b562017-11-15 15:48:08 -080062 return _Py_INIT_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060063}
Eric Snow05351c12017-09-05 21:43:08 -070064
Victor Stinner5d39e042017-11-29 17:20:38 +010065_PyInitError
66_PyRuntimeState_Init(_PyRuntimeState *runtime)
67{
68 /* Force default allocator, since _PyRuntimeState_Fini() must
69 use the same allocator than this function. */
70 PyMemAllocatorEx old_alloc;
71 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
72
73 _PyInitError err = _PyRuntimeState_Init_impl(runtime);
74
75 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
76 return err;
77}
78
Eric Snow2ebc5ce2017-09-07 23:51:28 -060079void
80_PyRuntimeState_Fini(_PyRuntimeState *runtime)
81{
Victor Stinner5d39e042017-11-29 17:20:38 +010082 /* Force the allocator used by _PyRuntimeState_Init(). */
83 PyMemAllocatorEx old_alloc;
84 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -080085
Eric Snow2ebc5ce2017-09-07 23:51:28 -060086 if (runtime->interpreters.mutex != NULL) {
87 PyThread_free_lock(runtime->interpreters.mutex);
88 runtime->interpreters.mutex = NULL;
89 }
Victor Stinnerccb04422017-11-16 03:20:31 -080090
91 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060092}
93
94#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
95 WAIT_LOCK)
96#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -070097
Michael W. Hudson188d4362005-06-20 16:52:57 +000098static void _PyGILState_NoteThreadState(PyThreadState* tstate);
99
Victor Stinnera7368ac2017-11-15 18:11:45 -0800100_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600101_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700102{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600103 runtime->interpreters.next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100104
105 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
106 Create a new mutex if needed. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600107 if (runtime->interpreters.mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100108 /* Force default allocator, since _PyRuntimeState_Fini() must
109 use the same allocator than this function. */
110 PyMemAllocatorEx old_alloc;
111 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
112
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600113 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100114
115 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
116
Victor Stinnera7368ac2017-11-15 18:11:45 -0800117 if (runtime->interpreters.mutex == NULL) {
118 return _Py_INIT_ERR("Can't initialize threads for interpreter");
119 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600120 }
Victor Stinner5d926472018-03-06 14:31:37 +0100121
Victor Stinnera7368ac2017-11-15 18:11:45 -0800122 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700123}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000124
125PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000126PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200129 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000130
Victor Stinnerd4341102017-11-23 00:12:09 +0100131 if (interp == NULL) {
132 return NULL;
133 }
134
Eric Snowef4ac962019-02-24 15:40:47 -0800135 memset(interp, 0, sizeof(*interp));
Eric Snow4c6955e2018-02-16 18:53:40 -0700136 interp->id_refcount = -1;
Victor Stinnerd4341102017-11-23 00:12:09 +0100137 interp->check_interval = 100;
Eric Snowef4ac962019-02-24 15:40:47 -0800138
139 interp->ceval.pending.lock = PyThread_allocate_lock();
140 if (interp->ceval.pending.lock == NULL) {
141 PyErr_SetString(PyExc_RuntimeError,
142 "failed to create interpreter ceval pending mutex");
143 return NULL;
144 }
Victor Stinnerd4341102017-11-23 00:12:09 +0100145 interp->core_config = _PyCoreConfig_INIT;
146 interp->config = _PyMainInterpreterConfig_INIT;
Victor Stinnerd4341102017-11-23 00:12:09 +0100147 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000148#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300149#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100150 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000151#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100152 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000153#endif
154#endif
Eric Snowef4ac962019-02-24 15:40:47 -0800155
156 if (_PyRuntime.main_thread == 0) {
157 _PyRuntime.main_thread = PyThread_get_thread_ident();
158 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000159
Victor Stinnerd4341102017-11-23 00:12:09 +0100160 HEAD_LOCK();
Victor Stinnerd4341102017-11-23 00:12:09 +0100161 if (_PyRuntime.interpreters.next_id < 0) {
162 /* overflow or Py_Initialize() not called! */
163 PyErr_SetString(PyExc_RuntimeError,
164 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100165 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100166 interp = NULL;
167 } else {
168 interp->id = _PyRuntime.interpreters.next_id;
169 _PyRuntime.interpreters.next_id += 1;
Pablo Galindo95d630e2018-08-31 22:49:29 +0100170 interp->next = _PyRuntime.interpreters.head;
171 if (_PyRuntime.interpreters.main == NULL) {
172 _PyRuntime.interpreters.main = interp;
173 }
174 _PyRuntime.interpreters.head = interp;
Victor Stinnerd4341102017-11-23 00:12:09 +0100175 }
176 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000177
Pablo Galindo95d630e2018-08-31 22:49:29 +0100178 if (interp == NULL) {
179 return NULL;
180 }
181
Yury Selivanovf23746a2018-01-22 19:11:18 -0500182 interp->tstate_next_unique_id = 0;
183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000185}
186
187
188void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000189PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 PyThreadState *p;
192 HEAD_LOCK();
193 for (p = interp->tstate_head; p != NULL; p = p->next)
194 PyThreadState_Clear(p);
195 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100196 _PyCoreConfig_Clear(&interp->core_config);
197 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 Py_CLEAR(interp->codec_search_path);
199 Py_CLEAR(interp->codec_search_cache);
200 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700201 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 Py_CLEAR(interp->sysdict);
204 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200205 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400206 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300207 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200208#ifdef HAVE_FORK
209 Py_CLEAR(interp->before_forkers);
210 Py_CLEAR(interp->after_forkers_parent);
211 Py_CLEAR(interp->after_forkers_child);
212#endif
Eric Snowef4ac962019-02-24 15:40:47 -0800213 // XXX Once we have one allocator per interpreter (i.e.
214 // per-interpreter GC) we must ensure that all of the interpreter's
215 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000216}
217
218
219static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000220zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 PyThreadState *p;
223 /* No need to lock the mutex here because this should only happen
224 when the threads are all really dead (XXX famous last words). */
225 while ((p = interp->tstate_head) != NULL) {
226 PyThreadState_Delete(p);
227 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000228}
229
230
231void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000232PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 PyInterpreterState **p;
235 zapthreads(interp);
236 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600237 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 if (*p == NULL)
239 Py_FatalError(
240 "PyInterpreterState_Delete: invalid interp");
241 if (*p == interp)
242 break;
243 }
244 if (interp->tstate_head != NULL)
245 Py_FatalError("PyInterpreterState_Delete: remaining threads");
246 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600247 if (_PyRuntime.interpreters.main == interp) {
248 _PyRuntime.interpreters.main = NULL;
249 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700250 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
251 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 HEAD_UNLOCK();
Eric Snow4c6955e2018-02-16 18:53:40 -0700253 if (interp->id_mutex != NULL) {
254 PyThread_free_lock(interp->id_mutex);
255 }
Eric Snowef4ac962019-02-24 15:40:47 -0800256 if (interp->ceval.pending.lock != NULL) {
257 PyThread_free_lock(interp->ceval.pending.lock);
258 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200259 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000260}
261
262
Eric Snow59032962018-09-14 14:17:20 -0700263/*
264 * Delete all interpreter states except the main interpreter. If there
265 * is a current interpreter state, it *must* be the main interpreter.
266 */
267void
268_PyInterpreterState_DeleteExceptMain()
269{
270 PyThreadState *tstate = PyThreadState_Swap(NULL);
271 if (tstate != NULL && tstate->interp != _PyRuntime.interpreters.main) {
272 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
273 }
274
275 HEAD_LOCK();
276 PyInterpreterState *interp = _PyRuntime.interpreters.head;
277 _PyRuntime.interpreters.head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100278 while (interp != NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700279 if (interp == _PyRuntime.interpreters.main) {
280 _PyRuntime.interpreters.main->next = NULL;
281 _PyRuntime.interpreters.head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100282 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700283 continue;
284 }
285
286 PyInterpreterState_Clear(interp); // XXX must activate?
287 zapthreads(interp);
288 if (interp->id_mutex != NULL) {
289 PyThread_free_lock(interp->id_mutex);
290 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100291 PyInterpreterState *prev_interp = interp;
292 interp = interp->next;
293 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700294 }
295 HEAD_UNLOCK();
296
297 if (_PyRuntime.interpreters.head == NULL) {
298 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
299 }
300 PyThreadState_Swap(tstate);
301}
302
303
Victor Stinnercaba55b2018-08-03 15:33:52 +0200304PyInterpreterState *
305_PyInterpreterState_Get(void)
306{
Victor Stinner50b48572018-11-01 01:51:40 +0100307 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200308 if (tstate == NULL) {
309 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
310 }
311 PyInterpreterState *interp = tstate->interp;
312 if (interp == NULL) {
313 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
314 }
315 return interp;
316}
317
318
Eric Snowe3774162017-05-22 19:46:40 -0700319int64_t
320PyInterpreterState_GetID(PyInterpreterState *interp)
321{
322 if (interp == NULL) {
323 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
324 return -1;
325 }
326 return interp->id;
327}
328
329
Eric Snow7f8bfc92018-01-29 18:23:44 -0700330PyInterpreterState *
331_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
332{
333 if (requested_id < 0)
334 goto error;
335
336 PyInterpreterState *interp = PyInterpreterState_Head();
337 while (interp != NULL) {
338 PY_INT64_T id = PyInterpreterState_GetID(interp);
339 if (id < 0)
340 return NULL;
341 if (requested_id == id)
342 return interp;
343 interp = PyInterpreterState_Next(interp);
344 }
345
346error:
347 PyErr_Format(PyExc_RuntimeError,
348 "unrecognized interpreter ID %lld", requested_id);
349 return NULL;
350}
351
Eric Snow4c6955e2018-02-16 18:53:40 -0700352
353int
354_PyInterpreterState_IDInitref(PyInterpreterState *interp)
355{
356 if (interp->id_mutex != NULL) {
357 return 0;
358 }
359 interp->id_mutex = PyThread_allocate_lock();
360 if (interp->id_mutex == NULL) {
361 PyErr_SetString(PyExc_RuntimeError,
362 "failed to create init interpreter ID mutex");
363 return -1;
364 }
365 interp->id_refcount = 0;
366 return 0;
367}
368
369
370void
371_PyInterpreterState_IDIncref(PyInterpreterState *interp)
372{
373 if (interp->id_mutex == NULL) {
374 return;
375 }
376 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
377 interp->id_refcount += 1;
378 PyThread_release_lock(interp->id_mutex);
379}
380
381
382void
383_PyInterpreterState_IDDecref(PyInterpreterState *interp)
384{
385 if (interp->id_mutex == NULL) {
386 return;
387 }
388 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
389 assert(interp->id_refcount != 0);
390 interp->id_refcount -= 1;
391 int64_t refcount = interp->id_refcount;
392 PyThread_release_lock(interp->id_mutex);
393
394 if (refcount == 0) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700395 // XXX Using the "head" thread isn't strictly correct.
396 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
397 // XXX Possible GILState issues?
398 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700399 Py_EndInterpreter(tstate);
400 PyThreadState_Swap(save_tstate);
401 }
402}
403
Eric Snowbe3b2952019-02-23 11:35:52 -0700404_PyCoreConfig *
405_PyInterpreterState_GetCoreConfig(PyInterpreterState *interp)
406{
407 return &interp->core_config;
408}
409
410_PyMainInterpreterConfig *
411_PyInterpreterState_GetMainConfig(PyInterpreterState *interp)
412{
413 return &interp->config;
414}
Eric Snow4c6955e2018-02-16 18:53:40 -0700415
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000416/* Default implementation for _PyThreadState_GetFrame */
417static struct _frame *
418threadstate_getframe(PyThreadState *self)
419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000421}
422
Victor Stinner45b9be52010-03-03 23:28:07 +0000423static PyThreadState *
424new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000425{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200426 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 if (_PyThreadState_GetFrame == NULL)
429 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 if (tstate != NULL) {
432 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 tstate->frame = NULL;
435 tstate->recursion_depth = 0;
436 tstate->overflowed = 0;
437 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700438 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 tstate->tracing = 0;
440 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 tstate->gilstate_counter = 0;
442 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 tstate->curexc_type = NULL;
448 tstate->curexc_value = NULL;
449 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000450
Mark Shannonae3087c2017-10-22 22:41:51 +0100451 tstate->exc_state.exc_type = NULL;
452 tstate->exc_state.exc_value = NULL;
453 tstate->exc_state.exc_traceback = NULL;
454 tstate->exc_state.previous_item = NULL;
455 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 tstate->c_profilefunc = NULL;
458 tstate->c_tracefunc = NULL;
459 tstate->c_profileobj = NULL;
460 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000461
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200462 tstate->trash_delete_nesting = 0;
463 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200464 tstate->on_delete = NULL;
465 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200466
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800467 tstate->coroutine_origin_tracking_depth = 0;
468
Yury Selivanov75445082015-05-11 22:57:16 -0400469 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400470 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400471
Yury Selivanoveb636452016-09-08 22:01:51 -0700472 tstate->async_gen_firstiter = NULL;
473 tstate->async_gen_finalizer = NULL;
474
Yury Selivanovf23746a2018-01-22 19:11:18 -0500475 tstate->context = NULL;
476 tstate->context_ver = 1;
477
478 tstate->id = ++interp->tstate_next_unique_id;
479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 if (init)
481 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200484 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200486 if (tstate->next)
487 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 interp->tstate_head = tstate;
489 HEAD_UNLOCK();
490 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000493}
494
Victor Stinner45b9be52010-03-03 23:28:07 +0000495PyThreadState *
496PyThreadState_New(PyInterpreterState *interp)
497{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000499}
500
501PyThreadState *
502_PyThreadState_Prealloc(PyInterpreterState *interp)
503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000505}
506
507void
508_PyThreadState_Init(PyThreadState *tstate)
509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000511}
512
Martin v. Löwis1a214512008-06-11 05:26:20 +0000513PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200514PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000515{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200516 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100517 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000519 if (module->m_slots) {
520 return NULL;
521 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 if (index == 0)
523 return NULL;
524 if (state->modules_by_index == NULL)
525 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200526 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 return NULL;
528 res = PyList_GET_ITEM(state->modules_by_index, index);
529 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000530}
531
532int
533_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
534{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000535 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300536 if (!def) {
537 assert(PyErr_Occurred());
538 return -1;
539 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000540 if (def->m_slots) {
541 PyErr_SetString(PyExc_SystemError,
542 "PyState_AddModule called on module with slots");
543 return -1;
544 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100545 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 if (!state->modules_by_index) {
547 state->modules_by_index = PyList_New(0);
548 if (!state->modules_by_index)
549 return -1;
550 }
551 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
552 if (PyList_Append(state->modules_by_index, Py_None) < 0)
553 return -1;
554 Py_INCREF(module);
555 return PyList_SetItem(state->modules_by_index,
556 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000557}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000558
Martin v. Löwis7800f752012-06-22 12:20:55 +0200559int
560PyState_AddModule(PyObject* module, struct PyModuleDef* def)
561{
562 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100563 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200564 if (!def) {
565 Py_FatalError("PyState_AddModule: Module Definition is NULL");
566 return -1;
567 }
568 index = def->m_base.m_index;
569 if (state->modules_by_index) {
570 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
571 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
572 Py_FatalError("PyState_AddModule: Module already added!");
573 return -1;
574 }
575 }
576 }
577 return _PyState_AddModule(module, def);
578}
579
580int
581PyState_RemoveModule(struct PyModuleDef* def)
582{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000583 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200584 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000585 if (def->m_slots) {
586 PyErr_SetString(PyExc_SystemError,
587 "PyState_RemoveModule called on module with slots");
588 return -1;
589 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100590 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200591 if (index == 0) {
592 Py_FatalError("PyState_RemoveModule: Module index invalid.");
593 return -1;
594 }
595 if (state->modules_by_index == NULL) {
596 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
597 return -1;
598 }
599 if (index > PyList_GET_SIZE(state->modules_by_index)) {
600 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
601 return -1;
602 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700603 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200604 return PyList_SetItem(state->modules_by_index, index, Py_None);
605}
606
Antoine Pitrou40322e62013-08-11 00:30:09 +0200607/* used by import.c:PyImport_Cleanup */
608void
609_PyState_ClearModules(void)
610{
Victor Stinner9204fb82018-10-30 15:13:17 +0100611 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200612 if (state->modules_by_index) {
613 Py_ssize_t i;
614 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
615 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
616 if (PyModule_Check(m)) {
617 /* cleanup the saved copy of module dicts */
618 PyModuleDef *md = PyModule_GetDef(m);
619 if (md)
620 Py_CLEAR(md->m_base.m_copy);
621 }
622 }
623 /* Setting modules_by_index to NULL could be dangerous, so we
624 clear the list instead. */
625 if (PyList_SetSlice(state->modules_by_index,
626 0, PyList_GET_SIZE(state->modules_by_index),
627 NULL))
628 PyErr_WriteUnraisable(state->modules_by_index);
629 }
630}
631
Guido van Rossuma027efa1997-05-05 20:56:21 +0000632void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000633PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000634{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200635 int verbose = tstate->interp->core_config.verbose;
636
637 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 fprintf(stderr,
639 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 Py_CLEAR(tstate->dict);
644 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 Py_CLEAR(tstate->curexc_type);
647 Py_CLEAR(tstate->curexc_value);
648 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649
Mark Shannonae3087c2017-10-22 22:41:51 +0100650 Py_CLEAR(tstate->exc_state.exc_type);
651 Py_CLEAR(tstate->exc_state.exc_value);
652 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300653
Mark Shannonae3087c2017-10-22 22:41:51 +0100654 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200655 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100656 fprintf(stderr,
657 "PyThreadState_Clear: warning: thread still has a generator\n");
658 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000659
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 tstate->c_profilefunc = NULL;
661 tstate->c_tracefunc = NULL;
662 Py_CLEAR(tstate->c_profileobj);
663 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400664
665 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700666 Py_CLEAR(tstate->async_gen_firstiter);
667 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500668
669 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000670}
671
672
Guido van Rossum29757862001-01-23 01:46:06 +0000673/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
674static void
675tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000676{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 if (tstate == NULL)
679 Py_FatalError("PyThreadState_Delete: NULL tstate");
680 interp = tstate->interp;
681 if (interp == NULL)
682 Py_FatalError("PyThreadState_Delete: NULL interp");
683 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200684 if (tstate->prev)
685 tstate->prev->next = tstate->next;
686 else
687 interp->tstate_head = tstate->next;
688 if (tstate->next)
689 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200691 if (tstate->on_delete != NULL) {
692 tstate->on_delete(tstate->on_delete_data);
693 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200694 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000695}
696
697
Guido van Rossum29757862001-01-23 01:46:06 +0000698void
699PyThreadState_Delete(PyThreadState *tstate)
700{
Victor Stinner50b48572018-11-01 01:51:40 +0100701 if (tstate == _PyThreadState_GET())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600703 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900704 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600705 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900706 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600707 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200708 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000709}
710
711
Guido van Rossum29757862001-01-23 01:46:06 +0000712void
713PyThreadState_DeleteCurrent()
714{
Victor Stinner50b48572018-11-01 01:51:40 +0100715 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 if (tstate == NULL)
717 Py_FatalError(
718 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100719 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600720 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900721 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600722 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900723 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600724 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100725 _PyThreadState_SET(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000727}
Guido van Rossum29757862001-01-23 01:46:06 +0000728
729
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200730/*
731 * Delete all thread states except the one passed as argument.
732 * Note that, if there is a current thread state, it *must* be the one
733 * passed as argument. Also, this won't touch any other interpreters
734 * than the current one, since we don't know which thread state should
735 * be kept in those other interpreteres.
736 */
737void
738_PyThreadState_DeleteExcept(PyThreadState *tstate)
739{
740 PyInterpreterState *interp = tstate->interp;
741 PyThreadState *p, *next, *garbage;
742 HEAD_LOCK();
743 /* Remove all thread states, except tstate, from the linked list of
744 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200745 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200746 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200747 if (garbage == tstate)
748 garbage = tstate->next;
749 if (tstate->prev)
750 tstate->prev->next = tstate->next;
751 if (tstate->next)
752 tstate->next->prev = tstate->prev;
753 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200754 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200755 HEAD_UNLOCK();
756 /* Clear and deallocate all stale thread states. Even if this
757 executes Python code, we should be safe since it executes
758 in the current thread, not one of the stale threads. */
759 for (p = garbage; p; p = next) {
760 next = p->next;
761 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200762 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200763 }
764}
765
766
Guido van Rossuma027efa1997-05-05 20:56:21 +0000767PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100768_PyThreadState_UncheckedGet(void)
769{
Victor Stinner50b48572018-11-01 01:51:40 +0100770 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100771}
772
773
774PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000775PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000776{
Victor Stinner50b48572018-11-01 01:51:40 +0100777 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 if (tstate == NULL)
779 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000782}
783
784
785PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000786PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000787{
Victor Stinner50b48572018-11-01 01:51:40 +0100788 PyThreadState *oldts = _PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000789
Victor Stinner9204fb82018-10-30 15:13:17 +0100790 _PyThreadState_SET(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 /* It should not be possible for more than one thread state
792 to be used for a thread. Check this the best we can in debug
793 builds.
794 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200795#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 if (newts) {
797 /* This can be called from PyEval_RestoreThread(). Similar
798 to it, we need to ensure errno doesn't change.
799 */
800 int err = errno;
801 PyThreadState *check = PyGILState_GetThisThreadState();
802 if (check && check->interp == newts->interp && check != newts)
803 Py_FatalError("Invalid thread state for this thread");
804 errno = err;
805 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000806#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000808}
Guido van Rossumede04391998-04-10 20:18:25 +0000809
810/* An extension mechanism to store arbitrary additional per-thread state.
811 PyThreadState_GetDict() returns a dictionary that can be used to hold such
812 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000813 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
814 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000815
816PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000817PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000818{
Victor Stinner50b48572018-11-01 01:51:40 +0100819 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (tstate == NULL)
821 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (tstate->dict == NULL) {
824 PyObject *d;
825 tstate->dict = d = PyDict_New();
826 if (d == NULL)
827 PyErr_Clear();
828 }
829 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000830}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000831
832
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000833/* Asynchronously raise an exception in a thread.
834 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000835 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000836 to call this, or use ctypes. Must be called with the GIL held.
837 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
838 match any known thread id). Can be called with exc=NULL to clear an
839 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000840
841int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200842PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
843{
Victor Stinner9204fb82018-10-30 15:13:17 +0100844 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 /* Although the GIL is held, a few C API functions can be called
848 * without the GIL held, and in particular some that create and
849 * destroy thread and interpreter states. Those can mutate the
850 * list of thread states we're traversing, so to prevent that we lock
851 * head_mutex for the duration.
852 */
853 HEAD_LOCK();
854 for (p = interp->tstate_head; p != NULL; p = p->next) {
855 if (p->thread_id == id) {
856 /* Tricky: we need to decref the current value
857 * (if any) in p->async_exc, but that can in turn
858 * allow arbitrary Python code to run, including
859 * perhaps calls to this function. To prevent
860 * deadlock, we need to release head_mutex before
861 * the decref.
862 */
863 PyObject *old_exc = p->async_exc;
864 Py_XINCREF(exc);
865 p->async_exc = exc;
866 HEAD_UNLOCK();
867 Py_XDECREF(old_exc);
Eric Snowef4ac962019-02-24 15:40:47 -0800868 _PyEval_SignalAsyncExc(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 return 1;
870 }
871 }
872 HEAD_UNLOCK();
873 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000874}
875
876
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000877/* Routines for advanced debuggers, requested by David Beazley.
878 Don't use unless you know what you are doing! */
879
880PyInterpreterState *
881PyInterpreterState_Head(void)
882{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600883 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000884}
885
886PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700887PyInterpreterState_Main(void)
888{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600889 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700890}
891
892PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000893PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000895}
896
897PyThreadState *
898PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000900}
901
902PyThreadState *
903PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000905}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000906
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000907/* The implementation of sys._current_frames(). This is intended to be
908 called with the GIL held, as it will be when called via
909 sys._current_frames(). It's possible it would work fine even without
910 the GIL held, but haven't thought enough about that.
911*/
912PyObject *
913_PyThread_CurrentFrames(void)
914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 PyObject *result;
916 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 result = PyDict_New();
919 if (result == NULL)
920 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 /* for i in all interpreters:
923 * for t in all of i's thread states:
924 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200925 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 * need to grab head_mutex for the duration.
927 */
928 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600929 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 PyThreadState *t;
931 for (t = i->tstate_head; t != NULL; t = t->next) {
932 PyObject *id;
933 int stat;
934 struct _frame *frame = t->frame;
935 if (frame == NULL)
936 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200937 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 if (id == NULL)
939 goto Fail;
940 stat = PyDict_SetItem(result, id, (PyObject *)frame);
941 Py_DECREF(id);
942 if (stat < 0)
943 goto Fail;
944 }
945 }
946 HEAD_UNLOCK();
947 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000948
949 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 HEAD_UNLOCK();
951 Py_DECREF(result);
952 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000953}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000954
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000955/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000956
957/* Keep this as a static, as it is not reliable! It can only
958 ever be compared to the state for the *current* thread.
959 * If not equal, then it doesn't matter that the actual
960 value may change immediately after comparison, as it can't
961 possibly change to the current thread's state.
962 * If equal, then the current thread holds the lock, so the value can't
963 change until we yield the lock.
964*/
965static int
966PyThreadState_IsCurrent(PyThreadState *tstate)
967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 /* Must be the tstate for this thread */
969 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinner50b48572018-11-01 01:51:40 +0100970 return tstate == _PyThreadState_GET();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000971}
972
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000973/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000974 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000975*/
Tim Peters19717fa2004-10-09 17:38:29 +0000976void
977_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000978{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900980 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
981 Py_FatalError("Could not allocate TSS entry");
982 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600983 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900984 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000988}
989
Victor Stinner861d9ab2016-03-16 22:45:24 +0100990PyInterpreterState *
991_PyGILState_GetInterpreterStateUnsafe(void)
992{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600993 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100994}
995
Tim Peters19717fa2004-10-09 17:38:29 +0000996void
997_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000998{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900999 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001000 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001001}
1002
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001003/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001004 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001005 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001006 */
1007void
1008_PyGILState_Reinit(void)
1009{
Victor Stinner5d926472018-03-06 14:31:37 +01001010 /* Force default allocator, since _PyRuntimeState_Fini() must
1011 use the same allocator than this function. */
1012 PyMemAllocatorEx old_alloc;
1013 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1014
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001015 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +01001016
1017 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1018
1019 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001020 Py_FatalError("Can't initialize threads for interpreter");
Victor Stinner5d926472018-03-06 14:31:37 +01001021 }
1022
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001023 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001024 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
1025 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1026 Py_FatalError("Could not allocate TSS entry");
1027 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001028
Charles-François Natalia233df82011-11-22 19:49:51 +01001029 /* If the thread had an associated auto thread state, reassociate it with
1030 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001031 if (tstate &&
1032 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
1033 {
1034 Py_FatalError("Couldn't create autoTSSkey mapping");
1035 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001036}
1037
Michael W. Hudson188d4362005-06-20 16:52:57 +00001038/* When a thread state is created for a thread by some mechanism other than
1039 PyGILState_Ensure, it's important that the GILState machinery knows about
1040 it so it doesn't try to create another thread state for the thread (this is
1041 a better fix for SF bug #1010677 than the first one attempted).
1042*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001043static void
Michael W. Hudson188d4362005-06-20 16:52:57 +00001044_PyGILState_NoteThreadState(PyThreadState* tstate)
1045{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001046 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001047 threadstate created in Py_Initialize(). Don't do anything for now
1048 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001049 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001051
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001052 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 The only situation where you can legitimately have more than one
1055 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001056 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001057
Victor Stinner590cebe2013-12-13 11:08:56 +01001058 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1059 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001060
Victor Stinner590cebe2013-12-13 11:08:56 +01001061 The first thread state created for that given OS level thread will
1062 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001064 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
1065 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1066 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001067 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001068 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001069 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001070 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 /* PyGILState_Release must not try to delete this thread state. */
1073 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001074}
1075
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001076/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001077PyThreadState *
1078PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001079{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001080 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001082 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001083}
1084
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001085int
1086PyGILState_Check(void)
1087{
Victor Stinner8a1be612016-03-14 22:07:55 +01001088 PyThreadState *tstate;
1089
1090 if (!_PyGILState_check_enabled)
1091 return 1;
1092
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001093 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001094 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001095 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001096
Victor Stinner50b48572018-11-01 01:51:40 +01001097 tstate = _PyThreadState_GET();
Victor Stinner8a1be612016-03-14 22:07:55 +01001098 if (tstate == NULL)
1099 return 0;
1100
1101 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001102}
1103
Tim Peters19717fa2004-10-09 17:38:29 +00001104PyGILState_STATE
1105PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 int current;
1108 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001109 int need_init_threads = 0;
1110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 /* Note that we do not auto-init Python here - apart from
1112 potential races with 2 threads auto-initializing, pep-311
1113 spells out other issues. Embedders are expected to have
1114 called Py_Initialize() and usually PyEval_InitThreads().
1115 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001116 /* Py_Initialize() hasn't been called! */
1117 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001118
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001119 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001121 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001123 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001124 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 if (tcur == NULL)
1126 Py_FatalError("Couldn't create thread-state for new thread");
1127 /* This is our thread state! We'll need to delete it in the
1128 matching call to PyGILState_Release(). */
1129 tcur->gilstate_counter = 0;
1130 current = 0; /* new thread state is never current */
1131 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001132 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001134 }
1135
1136 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001138 }
1139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 /* Update our counter in the thread-state - no need for locks:
1141 - tcur will remain valid as we hold the GIL.
1142 - the counter is safe as we are the only thread "allowed"
1143 to modify this value
1144 */
1145 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001146
1147 if (need_init_threads) {
1148 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1149 called from a new thread for the first time, we need the create the
1150 GIL. */
1151 PyEval_InitThreads();
1152 }
1153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001155}
1156
Tim Peters19717fa2004-10-09 17:38:29 +00001157void
1158PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001159{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001160 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1161 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 if (tcur == NULL)
1163 Py_FatalError("auto-releasing thread-state, "
1164 "but no thread-state for this thread");
1165 /* We must hold the GIL and have our thread state current */
1166 /* XXX - remove the check - the assert should be fine,
1167 but while this is very new (April 2003), the extra check
1168 by release-only users can't hurt.
1169 */
1170 if (! PyThreadState_IsCurrent(tcur))
1171 Py_FatalError("This thread state must be current when releasing");
1172 assert(PyThreadState_IsCurrent(tcur));
1173 --tcur->gilstate_counter;
1174 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 /* If we're going to destroy this thread-state, we must
1177 * clear it while the GIL is held, as destructors may run.
1178 */
1179 if (tcur->gilstate_counter == 0) {
1180 /* can't have been locked when we created it */
1181 assert(oldstate == PyGILState_UNLOCKED);
1182 PyThreadState_Clear(tcur);
1183 /* Delete the thread-state. Note this releases the GIL too!
1184 * It's vital that the GIL be held here, to avoid shutdown
1185 * races; see bugs 225673 and 1061968 (that nasty bug has a
1186 * habit of coming back).
1187 */
1188 PyThreadState_DeleteCurrent();
1189 }
1190 /* Release the lock if necessary */
1191 else if (oldstate == PyGILState_UNLOCKED)
1192 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001193}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001194
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001195
Eric Snow7f8bfc92018-01-29 18:23:44 -07001196/**************************/
1197/* cross-interpreter data */
1198/**************************/
1199
1200/* cross-interpreter data */
1201
1202crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1203
1204/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1205 to keep the registry code separate. */
1206static crossinterpdatafunc
1207_lookup_getdata(PyObject *obj)
1208{
1209 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1210 if (getdata == NULL && PyErr_Occurred() == 0)
1211 PyErr_Format(PyExc_ValueError,
1212 "%S does not support cross-interpreter data", obj);
1213 return getdata;
1214}
1215
1216int
1217_PyObject_CheckCrossInterpreterData(PyObject *obj)
1218{
1219 crossinterpdatafunc getdata = _lookup_getdata(obj);
1220 if (getdata == NULL) {
1221 return -1;
1222 }
1223 return 0;
1224}
1225
1226static int
1227_check_xidata(_PyCrossInterpreterData *data)
1228{
1229 // data->data can be anything, including NULL, so we don't check it.
1230
1231 // data->obj may be NULL, so we don't check it.
1232
1233 if (data->interp < 0) {
1234 PyErr_SetString(PyExc_SystemError, "missing interp");
1235 return -1;
1236 }
1237
1238 if (data->new_object == NULL) {
1239 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1240 return -1;
1241 }
1242
1243 // data->free may be NULL, so we don't check it.
1244
1245 return 0;
1246}
1247
1248int
1249_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1250{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001251 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001252 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001253 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001254
1255 // Reset data before re-populating.
1256 *data = (_PyCrossInterpreterData){0};
1257 data->free = PyMem_RawFree; // Set a default that may be overridden.
1258
1259 // Call the "getdata" func for the object.
1260 Py_INCREF(obj);
1261 crossinterpdatafunc getdata = _lookup_getdata(obj);
1262 if (getdata == NULL) {
1263 Py_DECREF(obj);
1264 return -1;
1265 }
1266 int res = getdata(obj, data);
1267 Py_DECREF(obj);
1268 if (res != 0) {
1269 return -1;
1270 }
1271
1272 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001273 data->interp = interp->id;
1274 if (_check_xidata(data) != 0) {
1275 _PyCrossInterpreterData_Release(data);
1276 return -1;
1277 }
1278
1279 return 0;
1280}
1281
Eric Snow63799132018-06-01 18:45:20 -06001282static void
1283_release_xidata(void *arg)
1284{
1285 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1286 if (data->free != NULL) {
1287 data->free(data->data);
1288 }
1289 Py_XDECREF(data->obj);
1290}
1291
1292static void
1293_call_in_interpreter(PyInterpreterState *interp,
1294 void (*func)(void *), void *arg)
1295{
1296 /* We would use Py_AddPendingCall() if it weren't specific to the
1297 * main interpreter (see bpo-33608). In the meantime we take a
1298 * naive approach.
1299 */
1300 PyThreadState *save_tstate = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001301 if (interp != _PyInterpreterState_Get()) {
Eric Snow63799132018-06-01 18:45:20 -06001302 // XXX Using the "head" thread isn't strictly correct.
1303 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1304 // XXX Possible GILState issues?
1305 save_tstate = PyThreadState_Swap(tstate);
1306 }
1307
1308 func(arg);
1309
1310 // Switch back.
1311 if (save_tstate != NULL) {
1312 PyThreadState_Swap(save_tstate);
1313 }
1314}
1315
Eric Snow7f8bfc92018-01-29 18:23:44 -07001316void
1317_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1318{
1319 if (data->data == NULL && data->obj == NULL) {
1320 // Nothing to release!
1321 return;
1322 }
1323
1324 // Switch to the original interpreter.
1325 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1326 if (interp == NULL) {
1327 // The intepreter was already destroyed.
1328 if (data->free != NULL) {
1329 // XXX Someone leaked some memory...
1330 }
1331 return;
1332 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001333
Eric Snow7f8bfc92018-01-29 18:23:44 -07001334 // "Release" the data and/or the object.
Eric Snowef4ac962019-02-24 15:40:47 -08001335 // XXX Use _Py_AddPendingCall().
Eric Snow63799132018-06-01 18:45:20 -06001336 _call_in_interpreter(interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001337}
1338
1339PyObject *
1340_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1341{
1342 return data->new_object(data);
1343}
1344
1345/* registry of {type -> crossinterpdatafunc} */
1346
1347/* For now we use a global registry of shareable classes. An
1348 alternative would be to add a tp_* slot for a class's
1349 crossinterpdatafunc. It would be simpler and more efficient. */
1350
1351static int
1352_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1353{
1354 // Note that we effectively replace already registered classes
1355 // rather than failing.
1356 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1357 if (newhead == NULL)
1358 return -1;
1359 newhead->cls = cls;
1360 newhead->getdata = getdata;
1361 newhead->next = _PyRuntime.xidregistry.head;
1362 _PyRuntime.xidregistry.head = newhead;
1363 return 0;
1364}
1365
1366static void _register_builtins_for_crossinterpreter_data(void);
1367
1368int
1369_PyCrossInterpreterData_Register_Class(PyTypeObject *cls,
1370 crossinterpdatafunc getdata)
1371{
1372 if (!PyType_Check(cls)) {
1373 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1374 return -1;
1375 }
1376 if (getdata == NULL) {
1377 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1378 return -1;
1379 }
1380
1381 // Make sure the class isn't ever deallocated.
1382 Py_INCREF((PyObject *)cls);
1383
1384 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1385 if (_PyRuntime.xidregistry.head == NULL) {
1386 _register_builtins_for_crossinterpreter_data();
1387 }
1388 int res = _register_xidata(cls, getdata);
1389 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1390 return res;
1391}
1392
Eric Snow6d2cd902018-05-16 15:04:57 -04001393/* Cross-interpreter objects are looked up by exact match on the class.
1394 We can reassess this policy when we move from a global registry to a
1395 tp_* slot. */
1396
Eric Snow7f8bfc92018-01-29 18:23:44 -07001397crossinterpdatafunc
1398_PyCrossInterpreterData_Lookup(PyObject *obj)
1399{
1400 PyObject *cls = PyObject_Type(obj);
1401 crossinterpdatafunc getdata = NULL;
1402 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1403 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1404 if (cur == NULL) {
1405 _register_builtins_for_crossinterpreter_data();
1406 cur = _PyRuntime.xidregistry.head;
1407 }
1408 for(; cur != NULL; cur = cur->next) {
1409 if (cur->cls == (PyTypeObject *)cls) {
1410 getdata = cur->getdata;
1411 break;
1412 }
1413 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001414 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001415 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1416 return getdata;
1417}
1418
1419/* cross-interpreter data for builtin types */
1420
Eric Snow6d2cd902018-05-16 15:04:57 -04001421struct _shared_bytes_data {
1422 char *bytes;
1423 Py_ssize_t len;
1424};
1425
Eric Snow7f8bfc92018-01-29 18:23:44 -07001426static PyObject *
1427_new_bytes_object(_PyCrossInterpreterData *data)
1428{
Eric Snow6d2cd902018-05-16 15:04:57 -04001429 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1430 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001431}
1432
1433static int
1434_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1435{
Eric Snow6d2cd902018-05-16 15:04:57 -04001436 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1437 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1438 return -1;
1439 }
1440 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001441 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001442 data->obj = obj; // Will be "released" (decref'ed) when data released.
1443 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001444 data->free = PyMem_Free;
1445 return 0;
1446}
1447
1448struct _shared_str_data {
1449 int kind;
1450 const void *buffer;
1451 Py_ssize_t len;
1452};
1453
1454static PyObject *
1455_new_str_object(_PyCrossInterpreterData *data)
1456{
1457 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1458 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1459}
1460
1461static int
1462_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1463{
1464 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1465 shared->kind = PyUnicode_KIND(obj);
1466 shared->buffer = PyUnicode_DATA(obj);
1467 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1468 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001469 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001470 data->obj = obj; // Will be "released" (decref'ed) when data released.
1471 data->new_object = _new_str_object;
1472 data->free = PyMem_Free;
1473 return 0;
1474}
1475
1476static PyObject *
1477_new_long_object(_PyCrossInterpreterData *data)
1478{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001479 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001480}
1481
1482static int
1483_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1484{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001485 /* Note that this means the size of shareable ints is bounded by
1486 * sys.maxsize. Hence on 32-bit architectures that is half the
1487 * size of maximum shareable ints on 64-bit.
1488 */
1489 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001490 if (value == -1 && PyErr_Occurred()) {
1491 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1492 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1493 }
1494 return -1;
1495 }
1496 data->data = (void *)value;
1497 data->obj = NULL;
1498 data->new_object = _new_long_object;
1499 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001500 return 0;
1501}
1502
1503static PyObject *
1504_new_none_object(_PyCrossInterpreterData *data)
1505{
1506 // XXX Singleton refcounts are problematic across interpreters...
1507 Py_INCREF(Py_None);
1508 return Py_None;
1509}
1510
1511static int
1512_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1513{
1514 data->data = NULL;
1515 // data->obj remains NULL
1516 data->new_object = _new_none_object;
1517 data->free = NULL; // There is nothing to free.
1518 return 0;
1519}
1520
1521static void
1522_register_builtins_for_crossinterpreter_data(void)
1523{
1524 // None
1525 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1526 Py_FatalError("could not register None for cross-interpreter sharing");
1527 }
1528
Eric Snow6d2cd902018-05-16 15:04:57 -04001529 // int
1530 if (_register_xidata(&PyLong_Type, _long_shared) != 0) {
1531 Py_FatalError("could not register int for cross-interpreter sharing");
1532 }
1533
Eric Snow7f8bfc92018-01-29 18:23:44 -07001534 // bytes
1535 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1536 Py_FatalError("could not register bytes for cross-interpreter sharing");
1537 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001538
1539 // str
1540 if (_register_xidata(&PyUnicode_Type, _str_shared) != 0) {
1541 Py_FatalError("could not register str for cross-interpreter sharing");
1542 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001543}
1544
1545
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001546#ifdef __cplusplus
1547}
1548#endif