blob: 8077a3ee7ab0282c34b2e2b4aad7b416a4cb3fe4 [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
Victor Stinnerf7e5b562017-11-15 15:48:08 -080059 return _Py_INIT_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060060}
Eric Snow05351c12017-09-05 21:43:08 -070061
Victor Stinner5d39e042017-11-29 17:20:38 +010062_PyInitError
63_PyRuntimeState_Init(_PyRuntimeState *runtime)
64{
65 /* Force default allocator, since _PyRuntimeState_Fini() must
66 use the same allocator than this function. */
67 PyMemAllocatorEx old_alloc;
68 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
69
70 _PyInitError err = _PyRuntimeState_Init_impl(runtime);
71
72 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
73 return err;
74}
75
Eric Snow2ebc5ce2017-09-07 23:51:28 -060076void
77_PyRuntimeState_Fini(_PyRuntimeState *runtime)
78{
Victor Stinner5d39e042017-11-29 17:20:38 +010079 /* Force the allocator used by _PyRuntimeState_Init(). */
80 PyMemAllocatorEx old_alloc;
81 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -080082
Eric Snow2ebc5ce2017-09-07 23:51:28 -060083 if (runtime->interpreters.mutex != NULL) {
84 PyThread_free_lock(runtime->interpreters.mutex);
85 runtime->interpreters.mutex = NULL;
86 }
Victor Stinnerccb04422017-11-16 03:20:31 -080087
88 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060089}
90
91#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
92 WAIT_LOCK)
93#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -070094
Michael W. Hudson188d4362005-06-20 16:52:57 +000095static void _PyGILState_NoteThreadState(PyThreadState* tstate);
96
Victor Stinnera7368ac2017-11-15 18:11:45 -080097_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060098_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -070099{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600100 runtime->interpreters.next_id = 0;
Miss Islington (bot)31e2b762018-03-06 05:52:27 -0800101
102 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
103 Create a new mutex if needed. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600104 if (runtime->interpreters.mutex == NULL) {
Miss Islington (bot)31e2b762018-03-06 05:52:27 -0800105 /* Force default allocator, since _PyRuntimeState_Fini() must
106 use the same allocator than this function. */
107 PyMemAllocatorEx old_alloc;
108 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
109
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600110 runtime->interpreters.mutex = PyThread_allocate_lock();
Miss Islington (bot)31e2b762018-03-06 05:52:27 -0800111
112 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
113
Victor Stinnera7368ac2017-11-15 18:11:45 -0800114 if (runtime->interpreters.mutex == NULL) {
115 return _Py_INIT_ERR("Can't initialize threads for interpreter");
116 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600117 }
Miss Islington (bot)31e2b762018-03-06 05:52:27 -0800118
Victor Stinnera7368ac2017-11-15 18:11:45 -0800119 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700120}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000121
122PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000123PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200126 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000127
Victor Stinnerd4341102017-11-23 00:12:09 +0100128 if (interp == NULL) {
129 return NULL;
130 }
131
Miss Islington (bot)3db05a32018-02-16 18:15:24 -0800132 interp->id_refcount = -1;
133 interp->id_mutex = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100134 interp->modules = NULL;
135 interp->modules_by_index = NULL;
136 interp->sysdict = NULL;
137 interp->builtins = NULL;
138 interp->builtins_copy = NULL;
139 interp->tstate_head = NULL;
140 interp->check_interval = 100;
141 interp->num_threads = 0;
142 interp->pythread_stacksize = 0;
143 interp->codec_search_path = NULL;
144 interp->codec_search_cache = NULL;
145 interp->codec_error_registry = NULL;
146 interp->codecs_initialized = 0;
147 interp->fscodec_initialized = 0;
148 interp->core_config = _PyCoreConfig_INIT;
149 interp->config = _PyMainInterpreterConfig_INIT;
150 interp->importlib = NULL;
151 interp->import_func = NULL;
152 interp->eval_frame = _PyEval_EvalFrameDefault;
153 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000154#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300155#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100156 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000157#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100158 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000159#endif
160#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200161#ifdef HAVE_FORK
Victor Stinnerd4341102017-11-23 00:12:09 +0100162 interp->before_forkers = NULL;
163 interp->after_forkers_parent = NULL;
164 interp->after_forkers_child = NULL;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200165#endif
Marcel Plch776407f2017-12-20 11:17:58 +0100166 interp->pyexitfunc = NULL;
167 interp->pyexitmodule = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000168
Victor Stinnerd4341102017-11-23 00:12:09 +0100169 HEAD_LOCK();
170 interp->next = _PyRuntime.interpreters.head;
171 if (_PyRuntime.interpreters.main == NULL) {
172 _PyRuntime.interpreters.main = interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 }
Victor Stinnerd4341102017-11-23 00:12:09 +0100174 _PyRuntime.interpreters.head = interp;
175 if (_PyRuntime.interpreters.next_id < 0) {
176 /* overflow or Py_Initialize() not called! */
177 PyErr_SetString(PyExc_RuntimeError,
178 "failed to get an interpreter ID");
Eric Snow7f8bfc92018-01-29 18:23:44 -0700179 /* XXX deallocate! */
Victor Stinnerd4341102017-11-23 00:12:09 +0100180 interp = NULL;
181 } else {
182 interp->id = _PyRuntime.interpreters.next_id;
183 _PyRuntime.interpreters.next_id += 1;
184 }
185 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000186
Yury Selivanovf23746a2018-01-22 19:11:18 -0500187 interp->tstate_next_unique_id = 0;
188
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000190}
191
192
193void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000194PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 PyThreadState *p;
197 HEAD_LOCK();
198 for (p = interp->tstate_head; p != NULL; p = p->next)
199 PyThreadState_Clear(p);
200 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100201 _PyCoreConfig_Clear(&interp->core_config);
202 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 Py_CLEAR(interp->codec_search_path);
204 Py_CLEAR(interp->codec_search_cache);
205 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700206 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 Py_CLEAR(interp->sysdict);
209 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200210 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400211 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300212 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200213#ifdef HAVE_FORK
214 Py_CLEAR(interp->before_forkers);
215 Py_CLEAR(interp->after_forkers_parent);
216 Py_CLEAR(interp->after_forkers_child);
217#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000218}
219
220
221static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000222zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 PyThreadState *p;
225 /* No need to lock the mutex here because this should only happen
226 when the threads are all really dead (XXX famous last words). */
227 while ((p = interp->tstate_head) != NULL) {
228 PyThreadState_Delete(p);
229 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000230}
231
232
233void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000234PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 PyInterpreterState **p;
237 zapthreads(interp);
238 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600239 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 if (*p == NULL)
241 Py_FatalError(
242 "PyInterpreterState_Delete: invalid interp");
243 if (*p == interp)
244 break;
245 }
246 if (interp->tstate_head != NULL)
247 Py_FatalError("PyInterpreterState_Delete: remaining threads");
248 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600249 if (_PyRuntime.interpreters.main == interp) {
250 _PyRuntime.interpreters.main = NULL;
251 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700252 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
253 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 HEAD_UNLOCK();
Miss Islington (bot)3db05a32018-02-16 18:15:24 -0800255 if (interp->id_mutex != NULL) {
256 PyThread_free_lock(interp->id_mutex);
257 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200258 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000259}
260
261
Eric Snowe3774162017-05-22 19:46:40 -0700262int64_t
263PyInterpreterState_GetID(PyInterpreterState *interp)
264{
265 if (interp == NULL) {
266 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
267 return -1;
268 }
269 return interp->id;
270}
271
272
Eric Snow7f8bfc92018-01-29 18:23:44 -0700273PyInterpreterState *
274_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
275{
276 if (requested_id < 0)
277 goto error;
278
279 PyInterpreterState *interp = PyInterpreterState_Head();
280 while (interp != NULL) {
281 PY_INT64_T id = PyInterpreterState_GetID(interp);
282 if (id < 0)
283 return NULL;
284 if (requested_id == id)
285 return interp;
286 interp = PyInterpreterState_Next(interp);
287 }
288
289error:
290 PyErr_Format(PyExc_RuntimeError,
291 "unrecognized interpreter ID %lld", requested_id);
292 return NULL;
293}
294
Miss Islington (bot)3db05a32018-02-16 18:15:24 -0800295
296int
297_PyInterpreterState_IDInitref(PyInterpreterState *interp)
298{
299 if (interp->id_mutex != NULL) {
300 return 0;
301 }
302 interp->id_mutex = PyThread_allocate_lock();
303 if (interp->id_mutex == NULL) {
304 PyErr_SetString(PyExc_RuntimeError,
305 "failed to create init interpreter ID mutex");
306 return -1;
307 }
308 interp->id_refcount = 0;
309 return 0;
310}
311
312
313void
314_PyInterpreterState_IDIncref(PyInterpreterState *interp)
315{
316 if (interp->id_mutex == NULL) {
317 return;
318 }
319 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
320 interp->id_refcount += 1;
321 PyThread_release_lock(interp->id_mutex);
322}
323
324
325void
326_PyInterpreterState_IDDecref(PyInterpreterState *interp)
327{
328 if (interp->id_mutex == NULL) {
329 return;
330 }
331 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
332 assert(interp->id_refcount != 0);
333 interp->id_refcount -= 1;
334 int64_t refcount = interp->id_refcount;
335 PyThread_release_lock(interp->id_mutex);
336
337 if (refcount == 0) {
Miss Islington (bot)eed3c7a2018-02-20 16:09:41 -0800338 // XXX Using the "head" thread isn't strictly correct.
339 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
340 // XXX Possible GILState issues?
341 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Miss Islington (bot)3db05a32018-02-16 18:15:24 -0800342 Py_EndInterpreter(tstate);
343 PyThreadState_Swap(save_tstate);
344 }
345}
346
347
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000348/* Default implementation for _PyThreadState_GetFrame */
349static struct _frame *
350threadstate_getframe(PyThreadState *self)
351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000353}
354
Victor Stinner45b9be52010-03-03 23:28:07 +0000355static PyThreadState *
356new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000357{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200358 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 if (_PyThreadState_GetFrame == NULL)
361 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 if (tstate != NULL) {
364 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000365
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 tstate->frame = NULL;
367 tstate->recursion_depth = 0;
368 tstate->overflowed = 0;
369 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700370 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 tstate->tracing = 0;
372 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000373 tstate->gilstate_counter = 0;
374 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 tstate->curexc_type = NULL;
380 tstate->curexc_value = NULL;
381 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000382
Mark Shannonae3087c2017-10-22 22:41:51 +0100383 tstate->exc_state.exc_type = NULL;
384 tstate->exc_state.exc_value = NULL;
385 tstate->exc_state.exc_traceback = NULL;
386 tstate->exc_state.previous_item = NULL;
387 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 tstate->c_profilefunc = NULL;
390 tstate->c_tracefunc = NULL;
391 tstate->c_profileobj = NULL;
392 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000393
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200394 tstate->trash_delete_nesting = 0;
395 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200396 tstate->on_delete = NULL;
397 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200398
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800399 tstate->coroutine_origin_tracking_depth = 0;
400
Yury Selivanov75445082015-05-11 22:57:16 -0400401 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400402 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400403
Yury Selivanoveb636452016-09-08 22:01:51 -0700404 tstate->async_gen_firstiter = NULL;
405 tstate->async_gen_finalizer = NULL;
406
Yury Selivanovf23746a2018-01-22 19:11:18 -0500407 tstate->context = NULL;
408 tstate->context_ver = 1;
409
410 tstate->id = ++interp->tstate_next_unique_id;
411
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 if (init)
413 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200416 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200418 if (tstate->next)
419 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 interp->tstate_head = tstate;
421 HEAD_UNLOCK();
422 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000425}
426
Victor Stinner45b9be52010-03-03 23:28:07 +0000427PyThreadState *
428PyThreadState_New(PyInterpreterState *interp)
429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000431}
432
433PyThreadState *
434_PyThreadState_Prealloc(PyInterpreterState *interp)
435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000437}
438
439void
440_PyThreadState_Init(PyThreadState *tstate)
441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000443}
444
Martin v. Löwis1a214512008-06-11 05:26:20 +0000445PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200446PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000447{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200448 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100449 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000451 if (module->m_slots) {
452 return NULL;
453 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 if (index == 0)
455 return NULL;
456 if (state->modules_by_index == NULL)
457 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200458 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 return NULL;
460 res = PyList_GET_ITEM(state->modules_by_index, index);
461 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000462}
463
464int
465_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
466{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000467 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300468 if (!def) {
469 assert(PyErr_Occurred());
470 return -1;
471 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000472 if (def->m_slots) {
473 PyErr_SetString(PyExc_SystemError,
474 "PyState_AddModule called on module with slots");
475 return -1;
476 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100477 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 if (!state->modules_by_index) {
479 state->modules_by_index = PyList_New(0);
480 if (!state->modules_by_index)
481 return -1;
482 }
483 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
484 if (PyList_Append(state->modules_by_index, Py_None) < 0)
485 return -1;
486 Py_INCREF(module);
487 return PyList_SetItem(state->modules_by_index,
488 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000489}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000490
Martin v. Löwis7800f752012-06-22 12:20:55 +0200491int
492PyState_AddModule(PyObject* module, struct PyModuleDef* def)
493{
494 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100495 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200496 if (!def) {
497 Py_FatalError("PyState_AddModule: Module Definition is NULL");
498 return -1;
499 }
500 index = def->m_base.m_index;
501 if (state->modules_by_index) {
502 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
503 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
504 Py_FatalError("PyState_AddModule: Module already added!");
505 return -1;
506 }
507 }
508 }
509 return _PyState_AddModule(module, def);
510}
511
512int
513PyState_RemoveModule(struct PyModuleDef* def)
514{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000515 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200516 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000517 if (def->m_slots) {
518 PyErr_SetString(PyExc_SystemError,
519 "PyState_RemoveModule called on module with slots");
520 return -1;
521 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100522 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200523 if (index == 0) {
524 Py_FatalError("PyState_RemoveModule: Module index invalid.");
525 return -1;
526 }
527 if (state->modules_by_index == NULL) {
528 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
529 return -1;
530 }
531 if (index > PyList_GET_SIZE(state->modules_by_index)) {
532 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
533 return -1;
534 }
Miss Islington (bot)2d594f82018-12-04 23:51:08 -0800535 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200536 return PyList_SetItem(state->modules_by_index, index, Py_None);
537}
538
Antoine Pitrou40322e62013-08-11 00:30:09 +0200539/* used by import.c:PyImport_Cleanup */
540void
541_PyState_ClearModules(void)
542{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100543 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200544 if (state->modules_by_index) {
545 Py_ssize_t i;
546 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
547 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
548 if (PyModule_Check(m)) {
549 /* cleanup the saved copy of module dicts */
550 PyModuleDef *md = PyModule_GetDef(m);
551 if (md)
552 Py_CLEAR(md->m_base.m_copy);
553 }
554 }
555 /* Setting modules_by_index to NULL could be dangerous, so we
556 clear the list instead. */
557 if (PyList_SetSlice(state->modules_by_index,
558 0, PyList_GET_SIZE(state->modules_by_index),
559 NULL))
560 PyErr_WriteUnraisable(state->modules_by_index);
561 }
562}
563
Guido van Rossuma027efa1997-05-05 20:56:21 +0000564void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000565PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 if (Py_VerboseFlag && tstate->frame != NULL)
568 fprintf(stderr,
569 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 Py_CLEAR(tstate->dict);
574 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 Py_CLEAR(tstate->curexc_type);
577 Py_CLEAR(tstate->curexc_value);
578 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579
Mark Shannonae3087c2017-10-22 22:41:51 +0100580 Py_CLEAR(tstate->exc_state.exc_type);
581 Py_CLEAR(tstate->exc_state.exc_value);
582 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300583
Mark Shannonae3087c2017-10-22 22:41:51 +0100584 /* The stack of exception states should contain just this thread. */
Mark Shannonae3087c2017-10-22 22:41:51 +0100585 if (Py_VerboseFlag && tstate->exc_info != &tstate->exc_state) {
586 fprintf(stderr,
587 "PyThreadState_Clear: warning: thread still has a generator\n");
588 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 tstate->c_profilefunc = NULL;
591 tstate->c_tracefunc = NULL;
592 Py_CLEAR(tstate->c_profileobj);
593 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400594
595 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700596 Py_CLEAR(tstate->async_gen_firstiter);
597 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500598
599 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000600}
601
602
Guido van Rossum29757862001-01-23 01:46:06 +0000603/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
604static void
605tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 if (tstate == NULL)
609 Py_FatalError("PyThreadState_Delete: NULL tstate");
610 interp = tstate->interp;
611 if (interp == NULL)
612 Py_FatalError("PyThreadState_Delete: NULL interp");
613 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200614 if (tstate->prev)
615 tstate->prev->next = tstate->next;
616 else
617 interp->tstate_head = tstate->next;
618 if (tstate->next)
619 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200621 if (tstate->on_delete != NULL) {
622 tstate->on_delete(tstate->on_delete_data);
623 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200624 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000625}
626
627
Guido van Rossum29757862001-01-23 01:46:06 +0000628void
629PyThreadState_Delete(PyThreadState *tstate)
630{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100631 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600633 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900634 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600635 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900636 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600637 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200638 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000639}
640
641
Guido van Rossum29757862001-01-23 01:46:06 +0000642void
643PyThreadState_DeleteCurrent()
644{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100645 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 if (tstate == NULL)
647 Py_FatalError(
648 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100649 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600650 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900651 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600652 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900653 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600654 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100655 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000657}
Guido van Rossum29757862001-01-23 01:46:06 +0000658
659
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200660/*
661 * Delete all thread states except the one passed as argument.
662 * Note that, if there is a current thread state, it *must* be the one
663 * passed as argument. Also, this won't touch any other interpreters
664 * than the current one, since we don't know which thread state should
665 * be kept in those other interpreteres.
666 */
667void
668_PyThreadState_DeleteExcept(PyThreadState *tstate)
669{
670 PyInterpreterState *interp = tstate->interp;
671 PyThreadState *p, *next, *garbage;
672 HEAD_LOCK();
673 /* Remove all thread states, except tstate, from the linked list of
674 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200675 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200676 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200677 if (garbage == tstate)
678 garbage = tstate->next;
679 if (tstate->prev)
680 tstate->prev->next = tstate->next;
681 if (tstate->next)
682 tstate->next->prev = tstate->prev;
683 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200684 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200685 HEAD_UNLOCK();
686 /* Clear and deallocate all stale thread states. Even if this
687 executes Python code, we should be safe since it executes
688 in the current thread, not one of the stale threads. */
689 for (p = garbage; p; p = next) {
690 next = p->next;
691 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200692 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200693 }
694}
695
696
Guido van Rossuma027efa1997-05-05 20:56:21 +0000697PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100698_PyThreadState_UncheckedGet(void)
699{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100700 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100701}
702
703
704PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000705PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000706{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100707 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (tstate == NULL)
709 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000712}
713
714
715PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000716PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000717{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100718 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000719
Victor Stinnerb02ef712016-01-22 14:09:55 +0100720 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 /* It should not be possible for more than one thread state
722 to be used for a thread. Check this the best we can in debug
723 builds.
724 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200725#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 if (newts) {
727 /* This can be called from PyEval_RestoreThread(). Similar
728 to it, we need to ensure errno doesn't change.
729 */
730 int err = errno;
731 PyThreadState *check = PyGILState_GetThisThreadState();
732 if (check && check->interp == newts->interp && check != newts)
733 Py_FatalError("Invalid thread state for this thread");
734 errno = err;
735 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000736#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000738}
Guido van Rossumede04391998-04-10 20:18:25 +0000739
740/* An extension mechanism to store arbitrary additional per-thread state.
741 PyThreadState_GetDict() returns a dictionary that can be used to hold such
742 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000743 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
744 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000745
746PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000747PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000748{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100749 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 if (tstate == NULL)
751 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 if (tstate->dict == NULL) {
754 PyObject *d;
755 tstate->dict = d = PyDict_New();
756 if (d == NULL)
757 PyErr_Clear();
758 }
759 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000760}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000761
762
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000763/* Asynchronously raise an exception in a thread.
764 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000765 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000766 to call this, or use ctypes. Must be called with the GIL held.
767 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
768 match any known thread id). Can be called with exc=NULL to clear an
769 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000770
771int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200772PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
773{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100774 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 /* Although the GIL is held, a few C API functions can be called
778 * without the GIL held, and in particular some that create and
779 * destroy thread and interpreter states. Those can mutate the
780 * list of thread states we're traversing, so to prevent that we lock
781 * head_mutex for the duration.
782 */
783 HEAD_LOCK();
784 for (p = interp->tstate_head; p != NULL; p = p->next) {
785 if (p->thread_id == id) {
786 /* Tricky: we need to decref the current value
787 * (if any) in p->async_exc, but that can in turn
788 * allow arbitrary Python code to run, including
789 * perhaps calls to this function. To prevent
790 * deadlock, we need to release head_mutex before
791 * the decref.
792 */
793 PyObject *old_exc = p->async_exc;
794 Py_XINCREF(exc);
795 p->async_exc = exc;
796 HEAD_UNLOCK();
797 Py_XDECREF(old_exc);
798 _PyEval_SignalAsyncExc();
799 return 1;
800 }
801 }
802 HEAD_UNLOCK();
803 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000804}
805
806
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000807/* Routines for advanced debuggers, requested by David Beazley.
808 Don't use unless you know what you are doing! */
809
810PyInterpreterState *
811PyInterpreterState_Head(void)
812{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600813 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000814}
815
816PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700817PyInterpreterState_Main(void)
818{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600819 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700820}
821
822PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000823PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000825}
826
827PyThreadState *
828PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000830}
831
832PyThreadState *
833PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000835}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000836
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000837/* The implementation of sys._current_frames(). This is intended to be
838 called with the GIL held, as it will be when called via
839 sys._current_frames(). It's possible it would work fine even without
840 the GIL held, but haven't thought enough about that.
841*/
842PyObject *
843_PyThread_CurrentFrames(void)
844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 PyObject *result;
846 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 result = PyDict_New();
849 if (result == NULL)
850 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 /* for i in all interpreters:
853 * for t in all of i's thread states:
854 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200855 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 * need to grab head_mutex for the duration.
857 */
858 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600859 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 PyThreadState *t;
861 for (t = i->tstate_head; t != NULL; t = t->next) {
862 PyObject *id;
863 int stat;
864 struct _frame *frame = t->frame;
865 if (frame == NULL)
866 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200867 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (id == NULL)
869 goto Fail;
870 stat = PyDict_SetItem(result, id, (PyObject *)frame);
871 Py_DECREF(id);
872 if (stat < 0)
873 goto Fail;
874 }
875 }
876 HEAD_UNLOCK();
877 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000878
879 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 HEAD_UNLOCK();
881 Py_DECREF(result);
882 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000883}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000884
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000885/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000886
887/* Keep this as a static, as it is not reliable! It can only
888 ever be compared to the state for the *current* thread.
889 * If not equal, then it doesn't matter that the actual
890 value may change immediately after comparison, as it can't
891 possibly change to the current thread's state.
892 * If equal, then the current thread holds the lock, so the value can't
893 change until we yield the lock.
894*/
895static int
896PyThreadState_IsCurrent(PyThreadState *tstate)
897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 /* Must be the tstate for this thread */
899 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100900 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000901}
902
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000903/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000904 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000905*/
Tim Peters19717fa2004-10-09 17:38:29 +0000906void
907_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000908{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900910 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
911 Py_FatalError("Could not allocate TSS entry");
912 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600913 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900914 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000918}
919
Victor Stinner861d9ab2016-03-16 22:45:24 +0100920PyInterpreterState *
921_PyGILState_GetInterpreterStateUnsafe(void)
922{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600923 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100924}
925
Tim Peters19717fa2004-10-09 17:38:29 +0000926void
927_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000928{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900929 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600930 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000931}
932
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900933/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200934 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900935 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200936 */
937void
938_PyGILState_Reinit(void)
939{
Miss Islington (bot)31e2b762018-03-06 05:52:27 -0800940 /* Force default allocator, since _PyRuntimeState_Fini() must
941 use the same allocator than this function. */
942 PyMemAllocatorEx old_alloc;
943 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
944
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600945 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Miss Islington (bot)31e2b762018-03-06 05:52:27 -0800946
947 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
948
949 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600950 Py_FatalError("Can't initialize threads for interpreter");
Miss Islington (bot)31e2b762018-03-06 05:52:27 -0800951 }
952
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200953 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900954 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
955 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
956 Py_FatalError("Could not allocate TSS entry");
957 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200958
Charles-François Natalia233df82011-11-22 19:49:51 +0100959 /* If the thread had an associated auto thread state, reassociate it with
960 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900961 if (tstate &&
962 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
963 {
964 Py_FatalError("Couldn't create autoTSSkey mapping");
965 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200966}
967
Michael W. Hudson188d4362005-06-20 16:52:57 +0000968/* When a thread state is created for a thread by some mechanism other than
969 PyGILState_Ensure, it's important that the GILState machinery knows about
970 it so it doesn't try to create another thread state for the thread (this is
971 a better fix for SF bug #1010677 than the first one attempted).
972*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000973static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000974_PyGILState_NoteThreadState(PyThreadState* tstate)
975{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900976 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +0000977 threadstate created in Py_Initialize(). Don't do anything for now
978 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600979 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000981
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900982 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 The only situation where you can legitimately have more than one
985 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100986 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000987
Victor Stinner590cebe2013-12-13 11:08:56 +0100988 You shouldn't really be using the PyGILState_ APIs anyway (see issues
989 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000990
Victor Stinner590cebe2013-12-13 11:08:56 +0100991 The first thread state created for that given OS level thread will
992 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900994 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
995 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
996 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600997 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900998 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600999 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001000 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 /* PyGILState_Release must not try to delete this thread state. */
1003 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001004}
1005
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001006/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001007PyThreadState *
1008PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001009{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001010 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001012 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001013}
1014
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001015int
1016PyGILState_Check(void)
1017{
Victor Stinner8a1be612016-03-14 22:07:55 +01001018 PyThreadState *tstate;
1019
1020 if (!_PyGILState_check_enabled)
1021 return 1;
1022
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001023 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001024 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001025 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001026
1027 tstate = GET_TSTATE();
1028 if (tstate == NULL)
1029 return 0;
1030
1031 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001032}
1033
Tim Peters19717fa2004-10-09 17:38:29 +00001034PyGILState_STATE
1035PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 int current;
1038 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001039 int need_init_threads = 0;
1040
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 /* Note that we do not auto-init Python here - apart from
1042 potential races with 2 threads auto-initializing, pep-311
1043 spells out other issues. Embedders are expected to have
1044 called Py_Initialize() and usually PyEval_InitThreads().
1045 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001046 /* Py_Initialize() hasn't been called! */
1047 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001048
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001049 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001051 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001054 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 if (tcur == NULL)
1056 Py_FatalError("Couldn't create thread-state for new thread");
1057 /* This is our thread state! We'll need to delete it in the
1058 matching call to PyGILState_Release(). */
1059 tcur->gilstate_counter = 0;
1060 current = 0; /* new thread state is never current */
1061 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001062 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001064 }
1065
1066 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001068 }
1069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 /* Update our counter in the thread-state - no need for locks:
1071 - tcur will remain valid as we hold the GIL.
1072 - the counter is safe as we are the only thread "allowed"
1073 to modify this value
1074 */
1075 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001076
1077 if (need_init_threads) {
1078 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1079 called from a new thread for the first time, we need the create the
1080 GIL. */
1081 PyEval_InitThreads();
1082 }
1083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001085}
1086
Tim Peters19717fa2004-10-09 17:38:29 +00001087void
1088PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001089{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001090 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1091 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 if (tcur == NULL)
1093 Py_FatalError("auto-releasing thread-state, "
1094 "but no thread-state for this thread");
1095 /* We must hold the GIL and have our thread state current */
1096 /* XXX - remove the check - the assert should be fine,
1097 but while this is very new (April 2003), the extra check
1098 by release-only users can't hurt.
1099 */
1100 if (! PyThreadState_IsCurrent(tcur))
1101 Py_FatalError("This thread state must be current when releasing");
1102 assert(PyThreadState_IsCurrent(tcur));
1103 --tcur->gilstate_counter;
1104 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 /* If we're going to destroy this thread-state, we must
1107 * clear it while the GIL is held, as destructors may run.
1108 */
1109 if (tcur->gilstate_counter == 0) {
1110 /* can't have been locked when we created it */
1111 assert(oldstate == PyGILState_UNLOCKED);
1112 PyThreadState_Clear(tcur);
1113 /* Delete the thread-state. Note this releases the GIL too!
1114 * It's vital that the GIL be held here, to avoid shutdown
1115 * races; see bugs 225673 and 1061968 (that nasty bug has a
1116 * habit of coming back).
1117 */
1118 PyThreadState_DeleteCurrent();
1119 }
1120 /* Release the lock if necessary */
1121 else if (oldstate == PyGILState_UNLOCKED)
1122 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001123}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001124
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001125
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001126#ifdef __cplusplus
1127}
1128#endif