blob: a87801f5692242bb4045704af8720b9503bffad4 [file] [log] [blame]
Guido van Rossuma027efa1997-05-05 20:56:21 +00001
2/* Thread and interpreter state structures and their interfaces */
3
4#include "Python.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06005#include "internal/pystate.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +00006
Victor Stinnerb02ef712016-01-22 14:09:55 +01007#define GET_TSTATE() \
8 ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current))
9#define SET_TSTATE(value) \
Benjamin Petersonca470632016-09-06 13:47:26 -070010 _Py_atomic_store_relaxed(&_PyThreadState_Current, (uintptr_t)(value))
Victor Stinnerb02ef712016-01-22 14:09:55 +010011#define GET_INTERP_STATE() \
12 (GET_TSTATE()->interp)
13
Victor Stinnerbfd316e2016-01-20 11:12:38 +010014
Tim Peters84705582004-10-10 02:47:33 +000015/* --------------------------------------------------------------------------
16CAUTION
17
Victor Stinner1a7425f2013-07-07 16:25:15 +020018Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
19number of these functions are advertised as safe to call when the GIL isn't
20held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
21debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
22to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000023-------------------------------------------------------------------------- */
24
Martin v. Löwisf0473d52001-07-18 16:17:16 +000025#ifdef HAVE_DLOPEN
26#ifdef HAVE_DLFCN_H
27#include <dlfcn.h>
28#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030029#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000030#define RTLD_LAZY 1
31#endif
32#endif
33
Benjamin Peterson43162b82012-04-13 11:58:27 -040034#ifdef __cplusplus
35extern "C" {
36#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000037
Victor Stinner5d39e042017-11-29 17:20:38 +010038static _PyInitError
39_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060040{
41 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010042
Eric Snow2ebc5ce2017-09-07 23:51:28 -060043 _PyGC_Initialize(&runtime->gc);
44 _PyEval_Initialize(&runtime->ceval);
Michael W. Hudson188d4362005-06-20 16:52:57 +000045
Eric Snow2ebc5ce2017-09-07 23:51:28 -060046 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080047
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090048 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
49 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080050 Py_tss_t initial = Py_tss_NEEDS_INIT;
51 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000052
Eric Snow2ebc5ce2017-09-07 23:51:28 -060053 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080054 if (runtime->interpreters.mutex == NULL) {
55 return _Py_INIT_ERR("Can't initialize threads for interpreter");
56 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060057 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070058
59 runtime->xidregistry.mutex = PyThread_allocate_lock();
60 if (runtime->xidregistry.mutex == NULL) {
61 return _Py_INIT_ERR("Can't initialize threads for cross-interpreter data registry");
62 }
63
Victor Stinnerf7e5b562017-11-15 15:48:08 -080064 return _Py_INIT_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060065}
Eric Snow05351c12017-09-05 21:43:08 -070066
Victor Stinner5d39e042017-11-29 17:20:38 +010067_PyInitError
68_PyRuntimeState_Init(_PyRuntimeState *runtime)
69{
70 /* Force default allocator, since _PyRuntimeState_Fini() must
71 use the same allocator than this function. */
72 PyMemAllocatorEx old_alloc;
73 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
74
75 _PyInitError err = _PyRuntimeState_Init_impl(runtime);
76
77 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
78 return err;
79}
80
Eric Snow2ebc5ce2017-09-07 23:51:28 -060081void
82_PyRuntimeState_Fini(_PyRuntimeState *runtime)
83{
Victor Stinner5d39e042017-11-29 17:20:38 +010084 /* Force the allocator used by _PyRuntimeState_Init(). */
85 PyMemAllocatorEx old_alloc;
86 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -080087
Eric Snow2ebc5ce2017-09-07 23:51:28 -060088 if (runtime->interpreters.mutex != NULL) {
89 PyThread_free_lock(runtime->interpreters.mutex);
90 runtime->interpreters.mutex = NULL;
91 }
Victor Stinnerccb04422017-11-16 03:20:31 -080092
93 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060094}
95
96#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
97 WAIT_LOCK)
98#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -070099
Michael W. Hudson188d4362005-06-20 16:52:57 +0000100static void _PyGILState_NoteThreadState(PyThreadState* tstate);
101
Victor Stinnera7368ac2017-11-15 18:11:45 -0800102_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600103_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700104{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600105 runtime->interpreters.next_id = 0;
106 /* Since we only call _PyRuntimeState_Init() once per process
107 (see _PyRuntime_Initialize()), we make sure the mutex is
108 initialized here. */
109 if (runtime->interpreters.mutex == NULL) {
110 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnera7368ac2017-11-15 18:11:45 -0800111 if (runtime->interpreters.mutex == NULL) {
112 return _Py_INIT_ERR("Can't initialize threads for interpreter");
113 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600114 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800115 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700116}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000117
118PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000119PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200122 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123
Victor Stinnerd4341102017-11-23 00:12:09 +0100124 if (interp == NULL) {
125 return NULL;
126 }
127
Miss Islington (bot)3db05a32018-02-16 18:15:24 -0800128 interp->id_refcount = -1;
129 interp->id_mutex = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100130 interp->modules = NULL;
131 interp->modules_by_index = NULL;
132 interp->sysdict = NULL;
133 interp->builtins = NULL;
134 interp->builtins_copy = NULL;
135 interp->tstate_head = NULL;
136 interp->check_interval = 100;
137 interp->num_threads = 0;
138 interp->pythread_stacksize = 0;
139 interp->codec_search_path = NULL;
140 interp->codec_search_cache = NULL;
141 interp->codec_error_registry = NULL;
142 interp->codecs_initialized = 0;
143 interp->fscodec_initialized = 0;
144 interp->core_config = _PyCoreConfig_INIT;
145 interp->config = _PyMainInterpreterConfig_INIT;
146 interp->importlib = NULL;
147 interp->import_func = NULL;
148 interp->eval_frame = _PyEval_EvalFrameDefault;
149 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000150#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300151#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100152 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000153#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100154 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000155#endif
156#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200157#ifdef HAVE_FORK
Victor Stinnerd4341102017-11-23 00:12:09 +0100158 interp->before_forkers = NULL;
159 interp->after_forkers_parent = NULL;
160 interp->after_forkers_child = NULL;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200161#endif
Marcel Plch776407f2017-12-20 11:17:58 +0100162 interp->pyexitfunc = NULL;
163 interp->pyexitmodule = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000164
Victor Stinnerd4341102017-11-23 00:12:09 +0100165 HEAD_LOCK();
166 interp->next = _PyRuntime.interpreters.head;
167 if (_PyRuntime.interpreters.main == NULL) {
168 _PyRuntime.interpreters.main = interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 }
Victor Stinnerd4341102017-11-23 00:12:09 +0100170 _PyRuntime.interpreters.head = interp;
171 if (_PyRuntime.interpreters.next_id < 0) {
172 /* overflow or Py_Initialize() not called! */
173 PyErr_SetString(PyExc_RuntimeError,
174 "failed to get an interpreter ID");
Eric Snow7f8bfc92018-01-29 18:23:44 -0700175 /* XXX deallocate! */
Victor Stinnerd4341102017-11-23 00:12:09 +0100176 interp = NULL;
177 } else {
178 interp->id = _PyRuntime.interpreters.next_id;
179 _PyRuntime.interpreters.next_id += 1;
180 }
181 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000182
Yury Selivanovf23746a2018-01-22 19:11:18 -0500183 interp->tstate_next_unique_id = 0;
184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000186}
187
188
189void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000190PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 PyThreadState *p;
193 HEAD_LOCK();
194 for (p = interp->tstate_head; p != NULL; p = p->next)
195 PyThreadState_Clear(p);
196 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100197 _PyCoreConfig_Clear(&interp->core_config);
198 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 Py_CLEAR(interp->codec_search_path);
200 Py_CLEAR(interp->codec_search_cache);
201 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700202 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 Py_CLEAR(interp->sysdict);
205 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200206 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400207 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300208 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200209#ifdef HAVE_FORK
210 Py_CLEAR(interp->before_forkers);
211 Py_CLEAR(interp->after_forkers_parent);
212 Py_CLEAR(interp->after_forkers_child);
213#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000214}
215
216
217static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000218zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 PyThreadState *p;
221 /* No need to lock the mutex here because this should only happen
222 when the threads are all really dead (XXX famous last words). */
223 while ((p = interp->tstate_head) != NULL) {
224 PyThreadState_Delete(p);
225 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000226}
227
228
229void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000230PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 PyInterpreterState **p;
233 zapthreads(interp);
234 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600235 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 if (*p == NULL)
237 Py_FatalError(
238 "PyInterpreterState_Delete: invalid interp");
239 if (*p == interp)
240 break;
241 }
242 if (interp->tstate_head != NULL)
243 Py_FatalError("PyInterpreterState_Delete: remaining threads");
244 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600245 if (_PyRuntime.interpreters.main == interp) {
246 _PyRuntime.interpreters.main = NULL;
247 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700248 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
249 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 HEAD_UNLOCK();
Miss Islington (bot)3db05a32018-02-16 18:15:24 -0800251 if (interp->id_mutex != NULL) {
252 PyThread_free_lock(interp->id_mutex);
253 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200254 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000255}
256
257
Eric Snowe3774162017-05-22 19:46:40 -0700258int64_t
259PyInterpreterState_GetID(PyInterpreterState *interp)
260{
261 if (interp == NULL) {
262 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
263 return -1;
264 }
265 return interp->id;
266}
267
268
Eric Snow7f8bfc92018-01-29 18:23:44 -0700269PyInterpreterState *
270_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
271{
272 if (requested_id < 0)
273 goto error;
274
275 PyInterpreterState *interp = PyInterpreterState_Head();
276 while (interp != NULL) {
277 PY_INT64_T id = PyInterpreterState_GetID(interp);
278 if (id < 0)
279 return NULL;
280 if (requested_id == id)
281 return interp;
282 interp = PyInterpreterState_Next(interp);
283 }
284
285error:
286 PyErr_Format(PyExc_RuntimeError,
287 "unrecognized interpreter ID %lld", requested_id);
288 return NULL;
289}
290
Miss Islington (bot)3db05a32018-02-16 18:15:24 -0800291
292int
293_PyInterpreterState_IDInitref(PyInterpreterState *interp)
294{
295 if (interp->id_mutex != NULL) {
296 return 0;
297 }
298 interp->id_mutex = PyThread_allocate_lock();
299 if (interp->id_mutex == NULL) {
300 PyErr_SetString(PyExc_RuntimeError,
301 "failed to create init interpreter ID mutex");
302 return -1;
303 }
304 interp->id_refcount = 0;
305 return 0;
306}
307
308
309void
310_PyInterpreterState_IDIncref(PyInterpreterState *interp)
311{
312 if (interp->id_mutex == NULL) {
313 return;
314 }
315 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
316 interp->id_refcount += 1;
317 PyThread_release_lock(interp->id_mutex);
318}
319
320
321void
322_PyInterpreterState_IDDecref(PyInterpreterState *interp)
323{
324 if (interp->id_mutex == NULL) {
325 return;
326 }
327 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
328 assert(interp->id_refcount != 0);
329 interp->id_refcount -= 1;
330 int64_t refcount = interp->id_refcount;
331 PyThread_release_lock(interp->id_mutex);
332
333 if (refcount == 0) {
Miss Islington (bot)eed3c7a2018-02-20 16:09:41 -0800334 // XXX Using the "head" thread isn't strictly correct.
335 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
336 // XXX Possible GILState issues?
337 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Miss Islington (bot)3db05a32018-02-16 18:15:24 -0800338 Py_EndInterpreter(tstate);
339 PyThreadState_Swap(save_tstate);
340 }
341}
342
343
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000344/* Default implementation for _PyThreadState_GetFrame */
345static struct _frame *
346threadstate_getframe(PyThreadState *self)
347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000349}
350
Victor Stinner45b9be52010-03-03 23:28:07 +0000351static PyThreadState *
352new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000353{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200354 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 if (_PyThreadState_GetFrame == NULL)
357 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 if (tstate != NULL) {
360 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 tstate->frame = NULL;
363 tstate->recursion_depth = 0;
364 tstate->overflowed = 0;
365 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700366 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 tstate->tracing = 0;
368 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 tstate->gilstate_counter = 0;
370 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 tstate->curexc_type = NULL;
376 tstate->curexc_value = NULL;
377 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000378
Mark Shannonae3087c2017-10-22 22:41:51 +0100379 tstate->exc_state.exc_type = NULL;
380 tstate->exc_state.exc_value = NULL;
381 tstate->exc_state.exc_traceback = NULL;
382 tstate->exc_state.previous_item = NULL;
383 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 tstate->c_profilefunc = NULL;
386 tstate->c_tracefunc = NULL;
387 tstate->c_profileobj = NULL;
388 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000389
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200390 tstate->trash_delete_nesting = 0;
391 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200392 tstate->on_delete = NULL;
393 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200394
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800395 tstate->coroutine_origin_tracking_depth = 0;
396
Yury Selivanov75445082015-05-11 22:57:16 -0400397 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400398 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400399
Yury Selivanoveb636452016-09-08 22:01:51 -0700400 tstate->async_gen_firstiter = NULL;
401 tstate->async_gen_finalizer = NULL;
402
Yury Selivanovf23746a2018-01-22 19:11:18 -0500403 tstate->context = NULL;
404 tstate->context_ver = 1;
405
406 tstate->id = ++interp->tstate_next_unique_id;
407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (init)
409 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200412 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200414 if (tstate->next)
415 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 interp->tstate_head = tstate;
417 HEAD_UNLOCK();
418 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000421}
422
Victor Stinner45b9be52010-03-03 23:28:07 +0000423PyThreadState *
424PyThreadState_New(PyInterpreterState *interp)
425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000427}
428
429PyThreadState *
430_PyThreadState_Prealloc(PyInterpreterState *interp)
431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000433}
434
435void
436_PyThreadState_Init(PyThreadState *tstate)
437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000439}
440
Martin v. Löwis1a214512008-06-11 05:26:20 +0000441PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200442PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000443{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200444 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100445 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000447 if (module->m_slots) {
448 return NULL;
449 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 if (index == 0)
451 return NULL;
452 if (state->modules_by_index == NULL)
453 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200454 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 return NULL;
456 res = PyList_GET_ITEM(state->modules_by_index, index);
457 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000458}
459
460int
461_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
462{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000463 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300464 if (!def) {
465 assert(PyErr_Occurred());
466 return -1;
467 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000468 if (def->m_slots) {
469 PyErr_SetString(PyExc_SystemError,
470 "PyState_AddModule called on module with slots");
471 return -1;
472 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100473 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (!state->modules_by_index) {
475 state->modules_by_index = PyList_New(0);
476 if (!state->modules_by_index)
477 return -1;
478 }
479 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
480 if (PyList_Append(state->modules_by_index, Py_None) < 0)
481 return -1;
482 Py_INCREF(module);
483 return PyList_SetItem(state->modules_by_index,
484 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000485}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000486
Martin v. Löwis7800f752012-06-22 12:20:55 +0200487int
488PyState_AddModule(PyObject* module, struct PyModuleDef* def)
489{
490 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100491 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200492 if (!def) {
493 Py_FatalError("PyState_AddModule: Module Definition is NULL");
494 return -1;
495 }
496 index = def->m_base.m_index;
497 if (state->modules_by_index) {
498 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
499 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
500 Py_FatalError("PyState_AddModule: Module already added!");
501 return -1;
502 }
503 }
504 }
505 return _PyState_AddModule(module, def);
506}
507
508int
509PyState_RemoveModule(struct PyModuleDef* def)
510{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000511 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200512 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000513 if (def->m_slots) {
514 PyErr_SetString(PyExc_SystemError,
515 "PyState_RemoveModule called on module with slots");
516 return -1;
517 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100518 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200519 if (index == 0) {
520 Py_FatalError("PyState_RemoveModule: Module index invalid.");
521 return -1;
522 }
523 if (state->modules_by_index == NULL) {
524 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
525 return -1;
526 }
527 if (index > PyList_GET_SIZE(state->modules_by_index)) {
528 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
529 return -1;
530 }
531 return PyList_SetItem(state->modules_by_index, index, Py_None);
532}
533
Antoine Pitrou40322e62013-08-11 00:30:09 +0200534/* used by import.c:PyImport_Cleanup */
535void
536_PyState_ClearModules(void)
537{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100538 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200539 if (state->modules_by_index) {
540 Py_ssize_t i;
541 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
542 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
543 if (PyModule_Check(m)) {
544 /* cleanup the saved copy of module dicts */
545 PyModuleDef *md = PyModule_GetDef(m);
546 if (md)
547 Py_CLEAR(md->m_base.m_copy);
548 }
549 }
550 /* Setting modules_by_index to NULL could be dangerous, so we
551 clear the list instead. */
552 if (PyList_SetSlice(state->modules_by_index,
553 0, PyList_GET_SIZE(state->modules_by_index),
554 NULL))
555 PyErr_WriteUnraisable(state->modules_by_index);
556 }
557}
558
Guido van Rossuma027efa1997-05-05 20:56:21 +0000559void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000560PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 if (Py_VerboseFlag && tstate->frame != NULL)
563 fprintf(stderr,
564 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000565
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 Py_CLEAR(tstate->dict);
569 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 Py_CLEAR(tstate->curexc_type);
572 Py_CLEAR(tstate->curexc_value);
573 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574
Mark Shannonae3087c2017-10-22 22:41:51 +0100575 Py_CLEAR(tstate->exc_state.exc_type);
576 Py_CLEAR(tstate->exc_state.exc_value);
577 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300578
Mark Shannonae3087c2017-10-22 22:41:51 +0100579 /* The stack of exception states should contain just this thread. */
580 assert(tstate->exc_info->previous_item == NULL);
581 if (Py_VerboseFlag && tstate->exc_info != &tstate->exc_state) {
582 fprintf(stderr,
583 "PyThreadState_Clear: warning: thread still has a generator\n");
584 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 tstate->c_profilefunc = NULL;
587 tstate->c_tracefunc = NULL;
588 Py_CLEAR(tstate->c_profileobj);
589 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400590
591 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700592 Py_CLEAR(tstate->async_gen_firstiter);
593 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500594
595 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000596}
597
598
Guido van Rossum29757862001-01-23 01:46:06 +0000599/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
600static void
601tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 if (tstate == NULL)
605 Py_FatalError("PyThreadState_Delete: NULL tstate");
606 interp = tstate->interp;
607 if (interp == NULL)
608 Py_FatalError("PyThreadState_Delete: NULL interp");
609 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200610 if (tstate->prev)
611 tstate->prev->next = tstate->next;
612 else
613 interp->tstate_head = tstate->next;
614 if (tstate->next)
615 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200617 if (tstate->on_delete != NULL) {
618 tstate->on_delete(tstate->on_delete_data);
619 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200620 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000621}
622
623
Guido van Rossum29757862001-01-23 01:46:06 +0000624void
625PyThreadState_Delete(PyThreadState *tstate)
626{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100627 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600629 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900630 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600631 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900632 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600633 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200634 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000635}
636
637
Guido van Rossum29757862001-01-23 01:46:06 +0000638void
639PyThreadState_DeleteCurrent()
640{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100641 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 if (tstate == NULL)
643 Py_FatalError(
644 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100645 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600646 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900647 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600648 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900649 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600650 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100651 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000653}
Guido van Rossum29757862001-01-23 01:46:06 +0000654
655
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200656/*
657 * Delete all thread states except the one passed as argument.
658 * Note that, if there is a current thread state, it *must* be the one
659 * passed as argument. Also, this won't touch any other interpreters
660 * than the current one, since we don't know which thread state should
661 * be kept in those other interpreteres.
662 */
663void
664_PyThreadState_DeleteExcept(PyThreadState *tstate)
665{
666 PyInterpreterState *interp = tstate->interp;
667 PyThreadState *p, *next, *garbage;
668 HEAD_LOCK();
669 /* Remove all thread states, except tstate, from the linked list of
670 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200671 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200672 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200673 if (garbage == tstate)
674 garbage = tstate->next;
675 if (tstate->prev)
676 tstate->prev->next = tstate->next;
677 if (tstate->next)
678 tstate->next->prev = tstate->prev;
679 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200680 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200681 HEAD_UNLOCK();
682 /* Clear and deallocate all stale thread states. Even if this
683 executes Python code, we should be safe since it executes
684 in the current thread, not one of the stale threads. */
685 for (p = garbage; p; p = next) {
686 next = p->next;
687 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200688 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200689 }
690}
691
692
Guido van Rossuma027efa1997-05-05 20:56:21 +0000693PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100694_PyThreadState_UncheckedGet(void)
695{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100696 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100697}
698
699
700PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000701PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000702{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100703 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 if (tstate == NULL)
705 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000708}
709
710
711PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000712PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000713{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100714 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000715
Victor Stinnerb02ef712016-01-22 14:09:55 +0100716 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 /* It should not be possible for more than one thread state
718 to be used for a thread. Check this the best we can in debug
719 builds.
720 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200721#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 if (newts) {
723 /* This can be called from PyEval_RestoreThread(). Similar
724 to it, we need to ensure errno doesn't change.
725 */
726 int err = errno;
727 PyThreadState *check = PyGILState_GetThisThreadState();
728 if (check && check->interp == newts->interp && check != newts)
729 Py_FatalError("Invalid thread state for this thread");
730 errno = err;
731 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000732#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000734}
Guido van Rossumede04391998-04-10 20:18:25 +0000735
736/* An extension mechanism to store arbitrary additional per-thread state.
737 PyThreadState_GetDict() returns a dictionary that can be used to hold such
738 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000739 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
740 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000741
742PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000743PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000744{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100745 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 if (tstate == NULL)
747 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 if (tstate->dict == NULL) {
750 PyObject *d;
751 tstate->dict = d = PyDict_New();
752 if (d == NULL)
753 PyErr_Clear();
754 }
755 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000756}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000757
758
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000759/* Asynchronously raise an exception in a thread.
760 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000761 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000762 to call this, or use ctypes. Must be called with the GIL held.
763 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
764 match any known thread id). Can be called with exc=NULL to clear an
765 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000766
767int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200768PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
769{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100770 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 /* Although the GIL is held, a few C API functions can be called
774 * without the GIL held, and in particular some that create and
775 * destroy thread and interpreter states. Those can mutate the
776 * list of thread states we're traversing, so to prevent that we lock
777 * head_mutex for the duration.
778 */
779 HEAD_LOCK();
780 for (p = interp->tstate_head; p != NULL; p = p->next) {
781 if (p->thread_id == id) {
782 /* Tricky: we need to decref the current value
783 * (if any) in p->async_exc, but that can in turn
784 * allow arbitrary Python code to run, including
785 * perhaps calls to this function. To prevent
786 * deadlock, we need to release head_mutex before
787 * the decref.
788 */
789 PyObject *old_exc = p->async_exc;
790 Py_XINCREF(exc);
791 p->async_exc = exc;
792 HEAD_UNLOCK();
793 Py_XDECREF(old_exc);
794 _PyEval_SignalAsyncExc();
795 return 1;
796 }
797 }
798 HEAD_UNLOCK();
799 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000800}
801
802
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000803/* Routines for advanced debuggers, requested by David Beazley.
804 Don't use unless you know what you are doing! */
805
806PyInterpreterState *
807PyInterpreterState_Head(void)
808{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600809 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000810}
811
812PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700813PyInterpreterState_Main(void)
814{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600815 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700816}
817
818PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000819PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000821}
822
823PyThreadState *
824PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000826}
827
828PyThreadState *
829PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000831}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000832
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000833/* The implementation of sys._current_frames(). This is intended to be
834 called with the GIL held, as it will be when called via
835 sys._current_frames(). It's possible it would work fine even without
836 the GIL held, but haven't thought enough about that.
837*/
838PyObject *
839_PyThread_CurrentFrames(void)
840{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 PyObject *result;
842 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 result = PyDict_New();
845 if (result == NULL)
846 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 /* for i in all interpreters:
849 * for t in all of i's thread states:
850 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200851 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 * need to grab head_mutex for the duration.
853 */
854 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600855 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 PyThreadState *t;
857 for (t = i->tstate_head; t != NULL; t = t->next) {
858 PyObject *id;
859 int stat;
860 struct _frame *frame = t->frame;
861 if (frame == NULL)
862 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200863 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (id == NULL)
865 goto Fail;
866 stat = PyDict_SetItem(result, id, (PyObject *)frame);
867 Py_DECREF(id);
868 if (stat < 0)
869 goto Fail;
870 }
871 }
872 HEAD_UNLOCK();
873 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000874
875 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 HEAD_UNLOCK();
877 Py_DECREF(result);
878 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000879}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000880
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000881/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000882
883/* Keep this as a static, as it is not reliable! It can only
884 ever be compared to the state for the *current* thread.
885 * If not equal, then it doesn't matter that the actual
886 value may change immediately after comparison, as it can't
887 possibly change to the current thread's state.
888 * If equal, then the current thread holds the lock, so the value can't
889 change until we yield the lock.
890*/
891static int
892PyThreadState_IsCurrent(PyThreadState *tstate)
893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 /* Must be the tstate for this thread */
895 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100896 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000897}
898
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000899/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000900 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000901*/
Tim Peters19717fa2004-10-09 17:38:29 +0000902void
903_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900906 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
907 Py_FatalError("Could not allocate TSS entry");
908 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600909 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900910 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000914}
915
Victor Stinner861d9ab2016-03-16 22:45:24 +0100916PyInterpreterState *
917_PyGILState_GetInterpreterStateUnsafe(void)
918{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600919 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100920}
921
Tim Peters19717fa2004-10-09 17:38:29 +0000922void
923_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000924{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900925 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600926 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000927}
928
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900929/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200930 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900931 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200932 */
933void
934_PyGILState_Reinit(void)
935{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600936 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
937 if (_PyRuntime.interpreters.mutex == NULL)
938 Py_FatalError("Can't initialize threads for interpreter");
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200939 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900940 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
941 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
942 Py_FatalError("Could not allocate TSS entry");
943 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200944
Charles-François Natalia233df82011-11-22 19:49:51 +0100945 /* If the thread had an associated auto thread state, reassociate it with
946 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900947 if (tstate &&
948 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
949 {
950 Py_FatalError("Couldn't create autoTSSkey mapping");
951 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200952}
953
Michael W. Hudson188d4362005-06-20 16:52:57 +0000954/* When a thread state is created for a thread by some mechanism other than
955 PyGILState_Ensure, it's important that the GILState machinery knows about
956 it so it doesn't try to create another thread state for the thread (this is
957 a better fix for SF bug #1010677 than the first one attempted).
958*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000959static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000960_PyGILState_NoteThreadState(PyThreadState* tstate)
961{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900962 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +0000963 threadstate created in Py_Initialize(). Don't do anything for now
964 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600965 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000967
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900968 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 The only situation where you can legitimately have more than one
971 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100972 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000973
Victor Stinner590cebe2013-12-13 11:08:56 +0100974 You shouldn't really be using the PyGILState_ APIs anyway (see issues
975 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000976
Victor Stinner590cebe2013-12-13 11:08:56 +0100977 The first thread state created for that given OS level thread will
978 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900980 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
981 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
982 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600983 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900984 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600985 }
Victor Stinner590cebe2013-12-13 11:08:56 +0100986 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 /* PyGILState_Release must not try to delete this thread state. */
989 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000990}
991
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000992/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000993PyThreadState *
994PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000995{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600996 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900998 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000999}
1000
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001001int
1002PyGILState_Check(void)
1003{
Victor Stinner8a1be612016-03-14 22:07:55 +01001004 PyThreadState *tstate;
1005
1006 if (!_PyGILState_check_enabled)
1007 return 1;
1008
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001009 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001010 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001011 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001012
1013 tstate = GET_TSTATE();
1014 if (tstate == NULL)
1015 return 0;
1016
1017 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001018}
1019
Tim Peters19717fa2004-10-09 17:38:29 +00001020PyGILState_STATE
1021PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001022{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 int current;
1024 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001025 int need_init_threads = 0;
1026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 /* Note that we do not auto-init Python here - apart from
1028 potential races with 2 threads auto-initializing, pep-311
1029 spells out other issues. Embedders are expected to have
1030 called Py_Initialize() and usually PyEval_InitThreads().
1031 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001032 /* Py_Initialize() hasn't been called! */
1033 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001034
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001035 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001037 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001040 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 if (tcur == NULL)
1042 Py_FatalError("Couldn't create thread-state for new thread");
1043 /* This is our thread state! We'll need to delete it in the
1044 matching call to PyGILState_Release(). */
1045 tcur->gilstate_counter = 0;
1046 current = 0; /* new thread state is never current */
1047 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001048 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001050 }
1051
1052 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001054 }
1055
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 /* Update our counter in the thread-state - no need for locks:
1057 - tcur will remain valid as we hold the GIL.
1058 - the counter is safe as we are the only thread "allowed"
1059 to modify this value
1060 */
1061 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001062
1063 if (need_init_threads) {
1064 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1065 called from a new thread for the first time, we need the create the
1066 GIL. */
1067 PyEval_InitThreads();
1068 }
1069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001071}
1072
Tim Peters19717fa2004-10-09 17:38:29 +00001073void
1074PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001075{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001076 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1077 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 if (tcur == NULL)
1079 Py_FatalError("auto-releasing thread-state, "
1080 "but no thread-state for this thread");
1081 /* We must hold the GIL and have our thread state current */
1082 /* XXX - remove the check - the assert should be fine,
1083 but while this is very new (April 2003), the extra check
1084 by release-only users can't hurt.
1085 */
1086 if (! PyThreadState_IsCurrent(tcur))
1087 Py_FatalError("This thread state must be current when releasing");
1088 assert(PyThreadState_IsCurrent(tcur));
1089 --tcur->gilstate_counter;
1090 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 /* If we're going to destroy this thread-state, we must
1093 * clear it while the GIL is held, as destructors may run.
1094 */
1095 if (tcur->gilstate_counter == 0) {
1096 /* can't have been locked when we created it */
1097 assert(oldstate == PyGILState_UNLOCKED);
1098 PyThreadState_Clear(tcur);
1099 /* Delete the thread-state. Note this releases the GIL too!
1100 * It's vital that the GIL be held here, to avoid shutdown
1101 * races; see bugs 225673 and 1061968 (that nasty bug has a
1102 * habit of coming back).
1103 */
1104 PyThreadState_DeleteCurrent();
1105 }
1106 /* Release the lock if necessary */
1107 else if (oldstate == PyGILState_UNLOCKED)
1108 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001109}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001110
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001111
Eric Snow7f8bfc92018-01-29 18:23:44 -07001112/**************************/
1113/* cross-interpreter data */
1114/**************************/
1115
1116/* cross-interpreter data */
1117
1118crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1119
1120/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1121 to keep the registry code separate. */
1122static crossinterpdatafunc
1123_lookup_getdata(PyObject *obj)
1124{
1125 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1126 if (getdata == NULL && PyErr_Occurred() == 0)
1127 PyErr_Format(PyExc_ValueError,
1128 "%S does not support cross-interpreter data", obj);
1129 return getdata;
1130}
1131
1132int
1133_PyObject_CheckCrossInterpreterData(PyObject *obj)
1134{
1135 crossinterpdatafunc getdata = _lookup_getdata(obj);
1136 if (getdata == NULL) {
1137 return -1;
1138 }
1139 return 0;
1140}
1141
1142static int
1143_check_xidata(_PyCrossInterpreterData *data)
1144{
1145 // data->data can be anything, including NULL, so we don't check it.
1146
1147 // data->obj may be NULL, so we don't check it.
1148
1149 if (data->interp < 0) {
1150 PyErr_SetString(PyExc_SystemError, "missing interp");
1151 return -1;
1152 }
1153
1154 if (data->new_object == NULL) {
1155 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1156 return -1;
1157 }
1158
1159 // data->free may be NULL, so we don't check it.
1160
1161 return 0;
1162}
1163
1164int
1165_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1166{
1167 PyThreadState *tstate = PyThreadState_Get();
1168 // PyThreadState_Get() aborts if lookup fails, so we don't need
1169 // to check the result for NULL.
1170 PyInterpreterState *interp = tstate->interp;
1171
1172 // Reset data before re-populating.
1173 *data = (_PyCrossInterpreterData){0};
1174 data->free = PyMem_RawFree; // Set a default that may be overridden.
1175
1176 // Call the "getdata" func for the object.
1177 Py_INCREF(obj);
1178 crossinterpdatafunc getdata = _lookup_getdata(obj);
1179 if (getdata == NULL) {
1180 Py_DECREF(obj);
1181 return -1;
1182 }
1183 int res = getdata(obj, data);
1184 Py_DECREF(obj);
1185 if (res != 0) {
1186 return -1;
1187 }
1188
1189 // Fill in the blanks and validate the result.
1190 Py_XINCREF(data->obj);
1191 data->interp = interp->id;
1192 if (_check_xidata(data) != 0) {
1193 _PyCrossInterpreterData_Release(data);
1194 return -1;
1195 }
1196
1197 return 0;
1198}
1199
1200void
1201_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1202{
1203 if (data->data == NULL && data->obj == NULL) {
1204 // Nothing to release!
1205 return;
1206 }
1207
1208 // Switch to the original interpreter.
1209 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1210 if (interp == NULL) {
1211 // The intepreter was already destroyed.
1212 if (data->free != NULL) {
1213 // XXX Someone leaked some memory...
1214 }
1215 return;
1216 }
Miss Islington (bot)eed3c7a2018-02-20 16:09:41 -08001217
1218 PyThreadState *save_tstate = NULL;
1219 if (interp != PyThreadState_Get()->interp) {
1220 // XXX Using the "head" thread isn't strictly correct.
1221 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1222 // XXX Possible GILState issues?
1223 save_tstate = PyThreadState_Swap(tstate);
1224 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001225
1226 // "Release" the data and/or the object.
1227 if (data->free != NULL) {
1228 data->free(data->data);
1229 }
1230 Py_XDECREF(data->obj);
1231
1232 // Switch back.
Miss Islington (bot)eed3c7a2018-02-20 16:09:41 -08001233 if (save_tstate != NULL) {
Eric Snow7f8bfc92018-01-29 18:23:44 -07001234 PyThreadState_Swap(save_tstate);
Miss Islington (bot)eed3c7a2018-02-20 16:09:41 -08001235 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001236}
1237
1238PyObject *
1239_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1240{
1241 return data->new_object(data);
1242}
1243
1244/* registry of {type -> crossinterpdatafunc} */
1245
1246/* For now we use a global registry of shareable classes. An
1247 alternative would be to add a tp_* slot for a class's
1248 crossinterpdatafunc. It would be simpler and more efficient. */
1249
1250static int
1251_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1252{
1253 // Note that we effectively replace already registered classes
1254 // rather than failing.
1255 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1256 if (newhead == NULL)
1257 return -1;
1258 newhead->cls = cls;
1259 newhead->getdata = getdata;
1260 newhead->next = _PyRuntime.xidregistry.head;
1261 _PyRuntime.xidregistry.head = newhead;
1262 return 0;
1263}
1264
1265static void _register_builtins_for_crossinterpreter_data(void);
1266
1267int
1268_PyCrossInterpreterData_Register_Class(PyTypeObject *cls,
1269 crossinterpdatafunc getdata)
1270{
1271 if (!PyType_Check(cls)) {
1272 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1273 return -1;
1274 }
1275 if (getdata == NULL) {
1276 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1277 return -1;
1278 }
1279
1280 // Make sure the class isn't ever deallocated.
1281 Py_INCREF((PyObject *)cls);
1282
1283 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1284 if (_PyRuntime.xidregistry.head == NULL) {
1285 _register_builtins_for_crossinterpreter_data();
1286 }
1287 int res = _register_xidata(cls, getdata);
1288 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1289 return res;
1290}
1291
1292crossinterpdatafunc
1293_PyCrossInterpreterData_Lookup(PyObject *obj)
1294{
1295 PyObject *cls = PyObject_Type(obj);
1296 crossinterpdatafunc getdata = NULL;
1297 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1298 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1299 if (cur == NULL) {
1300 _register_builtins_for_crossinterpreter_data();
1301 cur = _PyRuntime.xidregistry.head;
1302 }
1303 for(; cur != NULL; cur = cur->next) {
1304 if (cur->cls == (PyTypeObject *)cls) {
1305 getdata = cur->getdata;
1306 break;
1307 }
1308 }
Miss Islington (bot)f33eced2018-02-02 21:38:57 -08001309 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001310 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1311 return getdata;
1312}
1313
1314/* cross-interpreter data for builtin types */
1315
1316static PyObject *
1317_new_bytes_object(_PyCrossInterpreterData *data)
1318{
1319 return PyBytes_FromString((char *)(data->data));
1320}
1321
1322static int
1323_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1324{
1325 data->data = (void *)(PyBytes_AS_STRING(obj));
1326 data->obj = obj; // Will be "released" (decref'ed) when data released.
1327 data->new_object = _new_bytes_object;
1328 data->free = NULL; // Do not free the data (it belongs to the object).
1329 return 0;
1330}
1331
1332static PyObject *
1333_new_none_object(_PyCrossInterpreterData *data)
1334{
1335 // XXX Singleton refcounts are problematic across interpreters...
1336 Py_INCREF(Py_None);
1337 return Py_None;
1338}
1339
1340static int
1341_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1342{
1343 data->data = NULL;
1344 // data->obj remains NULL
1345 data->new_object = _new_none_object;
1346 data->free = NULL; // There is nothing to free.
1347 return 0;
1348}
1349
1350static void
1351_register_builtins_for_crossinterpreter_data(void)
1352{
1353 // None
1354 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1355 Py_FatalError("could not register None for cross-interpreter sharing");
1356 }
1357
1358 // bytes
1359 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1360 Py_FatalError("could not register bytes for cross-interpreter sharing");
1361 }
1362}
1363
1364
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001365#ifdef __cplusplus
1366}
1367#endif