blob: fc695c62a3300ebfc989e5630d229846f79e48e4 [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();
Victor Stinnerd4341102017-11-23 00:12:09 +0100170 if (_PyRuntime.interpreters.next_id < 0) {
171 /* overflow or Py_Initialize() not called! */
172 PyErr_SetString(PyExc_RuntimeError,
173 "failed to get an interpreter ID");
Pablo Galindo34ed40f2019-05-10 21:16:19 +0100174 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100175 interp = NULL;
176 } else {
177 interp->id = _PyRuntime.interpreters.next_id;
178 _PyRuntime.interpreters.next_id += 1;
Pablo Galindo34ed40f2019-05-10 21:16:19 +0100179 interp->next = _PyRuntime.interpreters.head;
180 if (_PyRuntime.interpreters.main == NULL) {
181 _PyRuntime.interpreters.main = interp;
182 }
183 _PyRuntime.interpreters.head = interp;
Victor Stinnerd4341102017-11-23 00:12:09 +0100184 }
185 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000186
Pablo Galindo34ed40f2019-05-10 21:16:19 +0100187 if (interp == NULL) {
188 return NULL;
189 }
190
Yury Selivanovf23746a2018-01-22 19:11:18 -0500191 interp->tstate_next_unique_id = 0;
192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000194}
195
196
197void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000198PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 PyThreadState *p;
201 HEAD_LOCK();
202 for (p = interp->tstate_head; p != NULL; p = p->next)
203 PyThreadState_Clear(p);
204 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100205 _PyCoreConfig_Clear(&interp->core_config);
206 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 Py_CLEAR(interp->codec_search_path);
208 Py_CLEAR(interp->codec_search_cache);
209 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700210 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 Py_CLEAR(interp->sysdict);
213 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200214 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400215 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300216 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200217#ifdef HAVE_FORK
218 Py_CLEAR(interp->before_forkers);
219 Py_CLEAR(interp->after_forkers_parent);
220 Py_CLEAR(interp->after_forkers_child);
221#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000222}
223
224
225static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000226zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 PyThreadState *p;
229 /* No need to lock the mutex here because this should only happen
230 when the threads are all really dead (XXX famous last words). */
231 while ((p = interp->tstate_head) != NULL) {
232 PyThreadState_Delete(p);
233 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000234}
235
236
237void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000238PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 PyInterpreterState **p;
241 zapthreads(interp);
242 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600243 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 if (*p == NULL)
245 Py_FatalError(
246 "PyInterpreterState_Delete: invalid interp");
247 if (*p == interp)
248 break;
249 }
250 if (interp->tstate_head != NULL)
251 Py_FatalError("PyInterpreterState_Delete: remaining threads");
252 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600253 if (_PyRuntime.interpreters.main == interp) {
254 _PyRuntime.interpreters.main = NULL;
255 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700256 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
257 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 HEAD_UNLOCK();
Miss Islington (bot)3db05a32018-02-16 18:15:24 -0800259 if (interp->id_mutex != NULL) {
260 PyThread_free_lock(interp->id_mutex);
261 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200262 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000263}
264
265
Eric Snowe3774162017-05-22 19:46:40 -0700266int64_t
267PyInterpreterState_GetID(PyInterpreterState *interp)
268{
269 if (interp == NULL) {
270 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
271 return -1;
272 }
273 return interp->id;
274}
275
276
Eric Snow7f8bfc92018-01-29 18:23:44 -0700277PyInterpreterState *
278_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
279{
280 if (requested_id < 0)
281 goto error;
282
283 PyInterpreterState *interp = PyInterpreterState_Head();
284 while (interp != NULL) {
285 PY_INT64_T id = PyInterpreterState_GetID(interp);
286 if (id < 0)
287 return NULL;
288 if (requested_id == id)
289 return interp;
290 interp = PyInterpreterState_Next(interp);
291 }
292
293error:
294 PyErr_Format(PyExc_RuntimeError,
295 "unrecognized interpreter ID %lld", requested_id);
296 return NULL;
297}
298
Miss Islington (bot)3db05a32018-02-16 18:15:24 -0800299
300int
301_PyInterpreterState_IDInitref(PyInterpreterState *interp)
302{
303 if (interp->id_mutex != NULL) {
304 return 0;
305 }
306 interp->id_mutex = PyThread_allocate_lock();
307 if (interp->id_mutex == NULL) {
308 PyErr_SetString(PyExc_RuntimeError,
309 "failed to create init interpreter ID mutex");
310 return -1;
311 }
312 interp->id_refcount = 0;
313 return 0;
314}
315
316
317void
318_PyInterpreterState_IDIncref(PyInterpreterState *interp)
319{
320 if (interp->id_mutex == NULL) {
321 return;
322 }
323 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
324 interp->id_refcount += 1;
325 PyThread_release_lock(interp->id_mutex);
326}
327
328
329void
330_PyInterpreterState_IDDecref(PyInterpreterState *interp)
331{
332 if (interp->id_mutex == NULL) {
333 return;
334 }
335 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
336 assert(interp->id_refcount != 0);
337 interp->id_refcount -= 1;
338 int64_t refcount = interp->id_refcount;
339 PyThread_release_lock(interp->id_mutex);
340
341 if (refcount == 0) {
Miss Islington (bot)eed3c7a2018-02-20 16:09:41 -0800342 // XXX Using the "head" thread isn't strictly correct.
343 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
344 // XXX Possible GILState issues?
345 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Miss Islington (bot)3db05a32018-02-16 18:15:24 -0800346 Py_EndInterpreter(tstate);
347 PyThreadState_Swap(save_tstate);
348 }
349}
350
351
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000352/* Default implementation for _PyThreadState_GetFrame */
353static struct _frame *
354threadstate_getframe(PyThreadState *self)
355{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000357}
358
Victor Stinner45b9be52010-03-03 23:28:07 +0000359static PyThreadState *
360new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000361{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200362 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (_PyThreadState_GetFrame == NULL)
365 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 if (tstate != NULL) {
368 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 tstate->frame = NULL;
371 tstate->recursion_depth = 0;
372 tstate->overflowed = 0;
373 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700374 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 tstate->tracing = 0;
376 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 tstate->gilstate_counter = 0;
378 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 tstate->curexc_type = NULL;
384 tstate->curexc_value = NULL;
385 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000386
Mark Shannonae3087c2017-10-22 22:41:51 +0100387 tstate->exc_state.exc_type = NULL;
388 tstate->exc_state.exc_value = NULL;
389 tstate->exc_state.exc_traceback = NULL;
390 tstate->exc_state.previous_item = NULL;
391 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 tstate->c_profilefunc = NULL;
394 tstate->c_tracefunc = NULL;
395 tstate->c_profileobj = NULL;
396 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000397
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200398 tstate->trash_delete_nesting = 0;
399 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200400 tstate->on_delete = NULL;
401 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200402
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800403 tstate->coroutine_origin_tracking_depth = 0;
404
Yury Selivanov75445082015-05-11 22:57:16 -0400405 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400406 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400407
Yury Selivanoveb636452016-09-08 22:01:51 -0700408 tstate->async_gen_firstiter = NULL;
409 tstate->async_gen_finalizer = NULL;
410
Yury Selivanovf23746a2018-01-22 19:11:18 -0500411 tstate->context = NULL;
412 tstate->context_ver = 1;
413
414 tstate->id = ++interp->tstate_next_unique_id;
415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 if (init)
417 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200420 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200422 if (tstate->next)
423 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 interp->tstate_head = tstate;
425 HEAD_UNLOCK();
426 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000429}
430
Victor Stinner45b9be52010-03-03 23:28:07 +0000431PyThreadState *
432PyThreadState_New(PyInterpreterState *interp)
433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000435}
436
437PyThreadState *
438_PyThreadState_Prealloc(PyInterpreterState *interp)
439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000441}
442
443void
444_PyThreadState_Init(PyThreadState *tstate)
445{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000447}
448
Martin v. Löwis1a214512008-06-11 05:26:20 +0000449PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200450PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000451{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200452 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100453 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000455 if (module->m_slots) {
456 return NULL;
457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 if (index == 0)
459 return NULL;
460 if (state->modules_by_index == NULL)
461 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200462 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 return NULL;
464 res = PyList_GET_ITEM(state->modules_by_index, index);
465 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000466}
467
468int
469_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
470{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000471 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300472 if (!def) {
473 assert(PyErr_Occurred());
474 return -1;
475 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000476 if (def->m_slots) {
477 PyErr_SetString(PyExc_SystemError,
478 "PyState_AddModule called on module with slots");
479 return -1;
480 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100481 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (!state->modules_by_index) {
483 state->modules_by_index = PyList_New(0);
484 if (!state->modules_by_index)
485 return -1;
486 }
487 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
488 if (PyList_Append(state->modules_by_index, Py_None) < 0)
489 return -1;
490 Py_INCREF(module);
491 return PyList_SetItem(state->modules_by_index,
492 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000493}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000494
Martin v. Löwis7800f752012-06-22 12:20:55 +0200495int
496PyState_AddModule(PyObject* module, struct PyModuleDef* def)
497{
498 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100499 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200500 if (!def) {
501 Py_FatalError("PyState_AddModule: Module Definition is NULL");
502 return -1;
503 }
504 index = def->m_base.m_index;
505 if (state->modules_by_index) {
506 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
507 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
508 Py_FatalError("PyState_AddModule: Module already added!");
509 return -1;
510 }
511 }
512 }
513 return _PyState_AddModule(module, def);
514}
515
516int
517PyState_RemoveModule(struct PyModuleDef* def)
518{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000519 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200520 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000521 if (def->m_slots) {
522 PyErr_SetString(PyExc_SystemError,
523 "PyState_RemoveModule called on module with slots");
524 return -1;
525 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100526 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200527 if (index == 0) {
528 Py_FatalError("PyState_RemoveModule: Module index invalid.");
529 return -1;
530 }
531 if (state->modules_by_index == NULL) {
532 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
533 return -1;
534 }
535 if (index > PyList_GET_SIZE(state->modules_by_index)) {
536 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
537 return -1;
538 }
Miss Islington (bot)2d594f82018-12-04 23:51:08 -0800539 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200540 return PyList_SetItem(state->modules_by_index, index, Py_None);
541}
542
Antoine Pitrou40322e62013-08-11 00:30:09 +0200543/* used by import.c:PyImport_Cleanup */
544void
545_PyState_ClearModules(void)
546{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100547 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200548 if (state->modules_by_index) {
549 Py_ssize_t i;
550 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
551 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
552 if (PyModule_Check(m)) {
553 /* cleanup the saved copy of module dicts */
554 PyModuleDef *md = PyModule_GetDef(m);
555 if (md)
556 Py_CLEAR(md->m_base.m_copy);
557 }
558 }
559 /* Setting modules_by_index to NULL could be dangerous, so we
560 clear the list instead. */
561 if (PyList_SetSlice(state->modules_by_index,
562 0, PyList_GET_SIZE(state->modules_by_index),
563 NULL))
564 PyErr_WriteUnraisable(state->modules_by_index);
565 }
566}
567
Guido van Rossuma027efa1997-05-05 20:56:21 +0000568void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000569PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 if (Py_VerboseFlag && tstate->frame != NULL)
572 fprintf(stderr,
573 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 Py_CLEAR(tstate->dict);
578 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 Py_CLEAR(tstate->curexc_type);
581 Py_CLEAR(tstate->curexc_value);
582 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000583
Mark Shannonae3087c2017-10-22 22:41:51 +0100584 Py_CLEAR(tstate->exc_state.exc_type);
585 Py_CLEAR(tstate->exc_state.exc_value);
586 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300587
Mark Shannonae3087c2017-10-22 22:41:51 +0100588 /* The stack of exception states should contain just this thread. */
Mark Shannonae3087c2017-10-22 22:41:51 +0100589 if (Py_VerboseFlag && tstate->exc_info != &tstate->exc_state) {
590 fprintf(stderr,
591 "PyThreadState_Clear: warning: thread still has a generator\n");
592 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 tstate->c_profilefunc = NULL;
595 tstate->c_tracefunc = NULL;
596 Py_CLEAR(tstate->c_profileobj);
597 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400598
599 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700600 Py_CLEAR(tstate->async_gen_firstiter);
601 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500602
603 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000604}
605
606
Guido van Rossum29757862001-01-23 01:46:06 +0000607/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
608static void
609tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (tstate == NULL)
613 Py_FatalError("PyThreadState_Delete: NULL tstate");
614 interp = tstate->interp;
615 if (interp == NULL)
616 Py_FatalError("PyThreadState_Delete: NULL interp");
617 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200618 if (tstate->prev)
619 tstate->prev->next = tstate->next;
620 else
621 interp->tstate_head = tstate->next;
622 if (tstate->next)
623 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200625 if (tstate->on_delete != NULL) {
626 tstate->on_delete(tstate->on_delete_data);
627 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200628 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000629}
630
631
Guido van Rossum29757862001-01-23 01:46:06 +0000632void
633PyThreadState_Delete(PyThreadState *tstate)
634{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100635 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600637 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900638 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600639 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900640 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600641 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200642 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000643}
644
645
Guido van Rossum29757862001-01-23 01:46:06 +0000646void
647PyThreadState_DeleteCurrent()
648{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100649 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 if (tstate == NULL)
651 Py_FatalError(
652 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100653 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600654 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900655 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600656 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900657 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600658 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100659 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000661}
Guido van Rossum29757862001-01-23 01:46:06 +0000662
663
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200664/*
665 * Delete all thread states except the one passed as argument.
666 * Note that, if there is a current thread state, it *must* be the one
667 * passed as argument. Also, this won't touch any other interpreters
668 * than the current one, since we don't know which thread state should
669 * be kept in those other interpreteres.
670 */
671void
672_PyThreadState_DeleteExcept(PyThreadState *tstate)
673{
674 PyInterpreterState *interp = tstate->interp;
675 PyThreadState *p, *next, *garbage;
676 HEAD_LOCK();
677 /* Remove all thread states, except tstate, from the linked list of
678 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200679 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200680 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200681 if (garbage == tstate)
682 garbage = tstate->next;
683 if (tstate->prev)
684 tstate->prev->next = tstate->next;
685 if (tstate->next)
686 tstate->next->prev = tstate->prev;
687 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200688 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200689 HEAD_UNLOCK();
690 /* Clear and deallocate all stale thread states. Even if this
691 executes Python code, we should be safe since it executes
692 in the current thread, not one of the stale threads. */
693 for (p = garbage; p; p = next) {
694 next = p->next;
695 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200696 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200697 }
698}
699
700
Guido van Rossuma027efa1997-05-05 20:56:21 +0000701PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100702_PyThreadState_UncheckedGet(void)
703{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100704 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100705}
706
707
708PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000709PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000710{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100711 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 if (tstate == NULL)
713 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000716}
717
718
719PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000720PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000721{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100722 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000723
Victor Stinnerb02ef712016-01-22 14:09:55 +0100724 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 /* It should not be possible for more than one thread state
726 to be used for a thread. Check this the best we can in debug
727 builds.
728 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200729#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 if (newts) {
731 /* This can be called from PyEval_RestoreThread(). Similar
732 to it, we need to ensure errno doesn't change.
733 */
734 int err = errno;
735 PyThreadState *check = PyGILState_GetThisThreadState();
736 if (check && check->interp == newts->interp && check != newts)
737 Py_FatalError("Invalid thread state for this thread");
738 errno = err;
739 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000740#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000742}
Guido van Rossumede04391998-04-10 20:18:25 +0000743
744/* An extension mechanism to store arbitrary additional per-thread state.
745 PyThreadState_GetDict() returns a dictionary that can be used to hold such
746 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000747 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
748 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000749
750PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000751PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000752{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100753 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (tstate == NULL)
755 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 if (tstate->dict == NULL) {
758 PyObject *d;
759 tstate->dict = d = PyDict_New();
760 if (d == NULL)
761 PyErr_Clear();
762 }
763 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000764}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000765
766
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000767/* Asynchronously raise an exception in a thread.
768 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000769 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000770 to call this, or use ctypes. Must be called with the GIL held.
771 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
772 match any known thread id). Can be called with exc=NULL to clear an
773 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000774
775int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200776PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
777{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100778 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 /* Although the GIL is held, a few C API functions can be called
782 * without the GIL held, and in particular some that create and
783 * destroy thread and interpreter states. Those can mutate the
784 * list of thread states we're traversing, so to prevent that we lock
785 * head_mutex for the duration.
786 */
787 HEAD_LOCK();
788 for (p = interp->tstate_head; p != NULL; p = p->next) {
789 if (p->thread_id == id) {
790 /* Tricky: we need to decref the current value
791 * (if any) in p->async_exc, but that can in turn
792 * allow arbitrary Python code to run, including
793 * perhaps calls to this function. To prevent
794 * deadlock, we need to release head_mutex before
795 * the decref.
796 */
797 PyObject *old_exc = p->async_exc;
798 Py_XINCREF(exc);
799 p->async_exc = exc;
800 HEAD_UNLOCK();
801 Py_XDECREF(old_exc);
802 _PyEval_SignalAsyncExc();
803 return 1;
804 }
805 }
806 HEAD_UNLOCK();
807 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000808}
809
810
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000811/* Routines for advanced debuggers, requested by David Beazley.
812 Don't use unless you know what you are doing! */
813
814PyInterpreterState *
815PyInterpreterState_Head(void)
816{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600817 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000818}
819
820PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700821PyInterpreterState_Main(void)
822{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600823 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700824}
825
826PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000827PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000829}
830
831PyThreadState *
832PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000834}
835
836PyThreadState *
837PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000838 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000839}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000840
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000841/* The implementation of sys._current_frames(). This is intended to be
842 called with the GIL held, as it will be when called via
843 sys._current_frames(). It's possible it would work fine even without
844 the GIL held, but haven't thought enough about that.
845*/
846PyObject *
847_PyThread_CurrentFrames(void)
848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 PyObject *result;
850 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 result = PyDict_New();
853 if (result == NULL)
854 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 /* for i in all interpreters:
857 * for t in all of i's thread states:
858 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200859 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 * need to grab head_mutex for the duration.
861 */
862 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600863 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 PyThreadState *t;
865 for (t = i->tstate_head; t != NULL; t = t->next) {
866 PyObject *id;
867 int stat;
868 struct _frame *frame = t->frame;
869 if (frame == NULL)
870 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200871 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 if (id == NULL)
873 goto Fail;
874 stat = PyDict_SetItem(result, id, (PyObject *)frame);
875 Py_DECREF(id);
876 if (stat < 0)
877 goto Fail;
878 }
879 }
880 HEAD_UNLOCK();
881 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000882
883 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 HEAD_UNLOCK();
885 Py_DECREF(result);
886 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000887}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000888
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000889/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000890
891/* Keep this as a static, as it is not reliable! It can only
892 ever be compared to the state for the *current* thread.
893 * If not equal, then it doesn't matter that the actual
894 value may change immediately after comparison, as it can't
895 possibly change to the current thread's state.
896 * If equal, then the current thread holds the lock, so the value can't
897 change until we yield the lock.
898*/
899static int
900PyThreadState_IsCurrent(PyThreadState *tstate)
901{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 /* Must be the tstate for this thread */
903 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100904 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000905}
906
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000907/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000908 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000909*/
Tim Peters19717fa2004-10-09 17:38:29 +0000910void
911_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900914 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
915 Py_FatalError("Could not allocate TSS entry");
916 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600917 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900918 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000922}
923
Victor Stinner861d9ab2016-03-16 22:45:24 +0100924PyInterpreterState *
925_PyGILState_GetInterpreterStateUnsafe(void)
926{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600927 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100928}
929
Tim Peters19717fa2004-10-09 17:38:29 +0000930void
931_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000932{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900933 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600934 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000935}
936
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900937/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200938 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900939 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200940 */
941void
942_PyGILState_Reinit(void)
943{
Miss Islington (bot)31e2b762018-03-06 05:52:27 -0800944 /* Force default allocator, since _PyRuntimeState_Fini() must
945 use the same allocator than this function. */
946 PyMemAllocatorEx old_alloc;
947 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
948
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600949 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Miss Islington (bot)31e2b762018-03-06 05:52:27 -0800950
951 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
952
953 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600954 Py_FatalError("Can't initialize threads for interpreter");
Miss Islington (bot)31e2b762018-03-06 05:52:27 -0800955 }
956
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200957 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900958 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
959 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
960 Py_FatalError("Could not allocate TSS entry");
961 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200962
Charles-François Natalia233df82011-11-22 19:49:51 +0100963 /* If the thread had an associated auto thread state, reassociate it with
964 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900965 if (tstate &&
966 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
967 {
968 Py_FatalError("Couldn't create autoTSSkey mapping");
969 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200970}
971
Michael W. Hudson188d4362005-06-20 16:52:57 +0000972/* When a thread state is created for a thread by some mechanism other than
973 PyGILState_Ensure, it's important that the GILState machinery knows about
974 it so it doesn't try to create another thread state for the thread (this is
975 a better fix for SF bug #1010677 than the first one attempted).
976*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000977static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000978_PyGILState_NoteThreadState(PyThreadState* tstate)
979{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900980 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +0000981 threadstate created in Py_Initialize(). Don't do anything for now
982 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600983 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000985
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900986 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 The only situation where you can legitimately have more than one
989 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100990 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000991
Victor Stinner590cebe2013-12-13 11:08:56 +0100992 You shouldn't really be using the PyGILState_ APIs anyway (see issues
993 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000994
Victor Stinner590cebe2013-12-13 11:08:56 +0100995 The first thread state created for that given OS level thread will
996 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900998 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
999 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1000 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001001 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001002 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001003 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001004 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001005
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 /* PyGILState_Release must not try to delete this thread state. */
1007 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001008}
1009
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001010/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001011PyThreadState *
1012PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001013{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001014 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001016 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001017}
1018
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001019int
1020PyGILState_Check(void)
1021{
Victor Stinner8a1be612016-03-14 22:07:55 +01001022 PyThreadState *tstate;
1023
1024 if (!_PyGILState_check_enabled)
1025 return 1;
1026
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001027 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001028 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001029 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001030
1031 tstate = GET_TSTATE();
1032 if (tstate == NULL)
1033 return 0;
1034
1035 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001036}
1037
Tim Peters19717fa2004-10-09 17:38:29 +00001038PyGILState_STATE
1039PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 int current;
1042 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001043 int need_init_threads = 0;
1044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 /* Note that we do not auto-init Python here - apart from
1046 potential races with 2 threads auto-initializing, pep-311
1047 spells out other issues. Embedders are expected to have
1048 called Py_Initialize() and usually PyEval_InitThreads().
1049 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001050 /* Py_Initialize() hasn't been called! */
1051 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001052
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001053 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001055 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001056
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001058 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 if (tcur == NULL)
1060 Py_FatalError("Couldn't create thread-state for new thread");
1061 /* This is our thread state! We'll need to delete it in the
1062 matching call to PyGILState_Release(). */
1063 tcur->gilstate_counter = 0;
1064 current = 0; /* new thread state is never current */
1065 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001066 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001068 }
1069
1070 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001072 }
1073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 /* Update our counter in the thread-state - no need for locks:
1075 - tcur will remain valid as we hold the GIL.
1076 - the counter is safe as we are the only thread "allowed"
1077 to modify this value
1078 */
1079 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001080
1081 if (need_init_threads) {
1082 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1083 called from a new thread for the first time, we need the create the
1084 GIL. */
1085 PyEval_InitThreads();
1086 }
1087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001089}
1090
Tim Peters19717fa2004-10-09 17:38:29 +00001091void
1092PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001093{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001094 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1095 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 if (tcur == NULL)
1097 Py_FatalError("auto-releasing thread-state, "
1098 "but no thread-state for this thread");
1099 /* We must hold the GIL and have our thread state current */
1100 /* XXX - remove the check - the assert should be fine,
1101 but while this is very new (April 2003), the extra check
1102 by release-only users can't hurt.
1103 */
1104 if (! PyThreadState_IsCurrent(tcur))
1105 Py_FatalError("This thread state must be current when releasing");
1106 assert(PyThreadState_IsCurrent(tcur));
1107 --tcur->gilstate_counter;
1108 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001110 /* If we're going to destroy this thread-state, we must
1111 * clear it while the GIL is held, as destructors may run.
1112 */
1113 if (tcur->gilstate_counter == 0) {
1114 /* can't have been locked when we created it */
1115 assert(oldstate == PyGILState_UNLOCKED);
1116 PyThreadState_Clear(tcur);
1117 /* Delete the thread-state. Note this releases the GIL too!
1118 * It's vital that the GIL be held here, to avoid shutdown
1119 * races; see bugs 225673 and 1061968 (that nasty bug has a
1120 * habit of coming back).
1121 */
1122 PyThreadState_DeleteCurrent();
1123 }
1124 /* Release the lock if necessary */
1125 else if (oldstate == PyGILState_UNLOCKED)
1126 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001127}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001128
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001129
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001130#ifdef __cplusplus
1131}
1132#endif