blob: 909d831465d4e68ac08eb85a8c4613d3783d5512 [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 }
57
Eric Snow2ebc5ce2017-09-07 23:51:28 -060058 runtime->interpreters.next_id = -1;
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;
101 /* Since we only call _PyRuntimeState_Init() once per process
102 (see _PyRuntime_Initialize()), we make sure the mutex is
103 initialized here. */
104 if (runtime->interpreters.mutex == NULL) {
105 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnera7368ac2017-11-15 18:11:45 -0800106 if (runtime->interpreters.mutex == NULL) {
107 return _Py_INIT_ERR("Can't initialize threads for interpreter");
108 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600109 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800110 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700111}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000112
113PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000114PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200117 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000118
Victor Stinnerd4341102017-11-23 00:12:09 +0100119 if (interp == NULL) {
120 return NULL;
121 }
122
123
124 interp->modules = NULL;
125 interp->modules_by_index = NULL;
126 interp->sysdict = NULL;
127 interp->builtins = NULL;
128 interp->builtins_copy = NULL;
129 interp->tstate_head = NULL;
130 interp->check_interval = 100;
131 interp->num_threads = 0;
132 interp->pythread_stacksize = 0;
133 interp->codec_search_path = NULL;
134 interp->codec_search_cache = NULL;
135 interp->codec_error_registry = NULL;
136 interp->codecs_initialized = 0;
137 interp->fscodec_initialized = 0;
138 interp->core_config = _PyCoreConfig_INIT;
139 interp->config = _PyMainInterpreterConfig_INIT;
140 interp->importlib = NULL;
141 interp->import_func = NULL;
142 interp->eval_frame = _PyEval_EvalFrameDefault;
143 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000144#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300145#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100146 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000147#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100148 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000149#endif
150#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200151#ifdef HAVE_FORK
Victor Stinnerd4341102017-11-23 00:12:09 +0100152 interp->before_forkers = NULL;
153 interp->after_forkers_parent = NULL;
154 interp->after_forkers_child = NULL;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200155#endif
Marcel Plch776407f2017-12-20 11:17:58 +0100156 interp->pyexitfunc = NULL;
157 interp->pyexitmodule = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000158
Victor Stinnerd4341102017-11-23 00:12:09 +0100159 HEAD_LOCK();
160 interp->next = _PyRuntime.interpreters.head;
161 if (_PyRuntime.interpreters.main == NULL) {
162 _PyRuntime.interpreters.main = interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 }
Victor Stinnerd4341102017-11-23 00:12:09 +0100164 _PyRuntime.interpreters.head = interp;
165 if (_PyRuntime.interpreters.next_id < 0) {
166 /* overflow or Py_Initialize() not called! */
167 PyErr_SetString(PyExc_RuntimeError,
168 "failed to get an interpreter ID");
169 interp = NULL;
170 } else {
171 interp->id = _PyRuntime.interpreters.next_id;
172 _PyRuntime.interpreters.next_id += 1;
173 }
174 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000175
Yury Selivanovf23746a2018-01-22 19:11:18 -0500176 interp->tstate_next_unique_id = 0;
177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000179}
180
181
182void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000183PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 PyThreadState *p;
186 HEAD_LOCK();
187 for (p = interp->tstate_head; p != NULL; p = p->next)
188 PyThreadState_Clear(p);
189 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100190 _PyCoreConfig_Clear(&interp->core_config);
191 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 Py_CLEAR(interp->codec_search_path);
193 Py_CLEAR(interp->codec_search_cache);
194 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700195 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 Py_CLEAR(interp->sysdict);
198 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200199 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400200 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300201 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200202#ifdef HAVE_FORK
203 Py_CLEAR(interp->before_forkers);
204 Py_CLEAR(interp->after_forkers_parent);
205 Py_CLEAR(interp->after_forkers_child);
206#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000207}
208
209
210static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000211zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 PyThreadState *p;
214 /* No need to lock the mutex here because this should only happen
215 when the threads are all really dead (XXX famous last words). */
216 while ((p = interp->tstate_head) != NULL) {
217 PyThreadState_Delete(p);
218 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000219}
220
221
222void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000223PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 PyInterpreterState **p;
226 zapthreads(interp);
227 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600228 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 if (*p == NULL)
230 Py_FatalError(
231 "PyInterpreterState_Delete: invalid interp");
232 if (*p == interp)
233 break;
234 }
235 if (interp->tstate_head != NULL)
236 Py_FatalError("PyInterpreterState_Delete: remaining threads");
237 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600238 if (_PyRuntime.interpreters.main == interp) {
239 _PyRuntime.interpreters.main = NULL;
240 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700241 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
242 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200244 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000245}
246
247
Eric Snowe3774162017-05-22 19:46:40 -0700248int64_t
249PyInterpreterState_GetID(PyInterpreterState *interp)
250{
251 if (interp == NULL) {
252 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
253 return -1;
254 }
255 return interp->id;
256}
257
258
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000259/* Default implementation for _PyThreadState_GetFrame */
260static struct _frame *
261threadstate_getframe(PyThreadState *self)
262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000264}
265
Victor Stinner45b9be52010-03-03 23:28:07 +0000266static PyThreadState *
267new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000268{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200269 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (_PyThreadState_GetFrame == NULL)
272 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 if (tstate != NULL) {
275 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 tstate->frame = NULL;
278 tstate->recursion_depth = 0;
279 tstate->overflowed = 0;
280 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700281 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 tstate->tracing = 0;
283 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 tstate->gilstate_counter = 0;
285 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 tstate->curexc_type = NULL;
291 tstate->curexc_value = NULL;
292 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000293
Mark Shannonae3087c2017-10-22 22:41:51 +0100294 tstate->exc_state.exc_type = NULL;
295 tstate->exc_state.exc_value = NULL;
296 tstate->exc_state.exc_traceback = NULL;
297 tstate->exc_state.previous_item = NULL;
298 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 tstate->c_profilefunc = NULL;
301 tstate->c_tracefunc = NULL;
302 tstate->c_profileobj = NULL;
303 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000304
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200305 tstate->trash_delete_nesting = 0;
306 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200307 tstate->on_delete = NULL;
308 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200309
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800310 tstate->coroutine_origin_tracking_depth = 0;
311
Yury Selivanov75445082015-05-11 22:57:16 -0400312 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400313 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400314
Yury Selivanoveb636452016-09-08 22:01:51 -0700315 tstate->async_gen_firstiter = NULL;
316 tstate->async_gen_finalizer = NULL;
317
Yury Selivanovf23746a2018-01-22 19:11:18 -0500318 tstate->context = NULL;
319 tstate->context_ver = 1;
320
321 tstate->id = ++interp->tstate_next_unique_id;
322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 if (init)
324 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200327 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200329 if (tstate->next)
330 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 interp->tstate_head = tstate;
332 HEAD_UNLOCK();
333 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000336}
337
Victor Stinner45b9be52010-03-03 23:28:07 +0000338PyThreadState *
339PyThreadState_New(PyInterpreterState *interp)
340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000342}
343
344PyThreadState *
345_PyThreadState_Prealloc(PyInterpreterState *interp)
346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000348}
349
350void
351_PyThreadState_Init(PyThreadState *tstate)
352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000354}
355
Martin v. Löwis1a214512008-06-11 05:26:20 +0000356PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200357PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000358{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200359 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100360 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000362 if (module->m_slots) {
363 return NULL;
364 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (index == 0)
366 return NULL;
367 if (state->modules_by_index == NULL)
368 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200369 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 return NULL;
371 res = PyList_GET_ITEM(state->modules_by_index, index);
372 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000373}
374
375int
376_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
377{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000378 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300379 if (!def) {
380 assert(PyErr_Occurred());
381 return -1;
382 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000383 if (def->m_slots) {
384 PyErr_SetString(PyExc_SystemError,
385 "PyState_AddModule called on module with slots");
386 return -1;
387 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100388 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 if (!state->modules_by_index) {
390 state->modules_by_index = PyList_New(0);
391 if (!state->modules_by_index)
392 return -1;
393 }
394 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
395 if (PyList_Append(state->modules_by_index, Py_None) < 0)
396 return -1;
397 Py_INCREF(module);
398 return PyList_SetItem(state->modules_by_index,
399 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000400}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000401
Martin v. Löwis7800f752012-06-22 12:20:55 +0200402int
403PyState_AddModule(PyObject* module, struct PyModuleDef* def)
404{
405 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100406 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200407 if (!def) {
408 Py_FatalError("PyState_AddModule: Module Definition is NULL");
409 return -1;
410 }
411 index = def->m_base.m_index;
412 if (state->modules_by_index) {
413 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
414 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
415 Py_FatalError("PyState_AddModule: Module already added!");
416 return -1;
417 }
418 }
419 }
420 return _PyState_AddModule(module, def);
421}
422
423int
424PyState_RemoveModule(struct PyModuleDef* def)
425{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000426 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200427 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000428 if (def->m_slots) {
429 PyErr_SetString(PyExc_SystemError,
430 "PyState_RemoveModule called on module with slots");
431 return -1;
432 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100433 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200434 if (index == 0) {
435 Py_FatalError("PyState_RemoveModule: Module index invalid.");
436 return -1;
437 }
438 if (state->modules_by_index == NULL) {
439 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
440 return -1;
441 }
442 if (index > PyList_GET_SIZE(state->modules_by_index)) {
443 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
444 return -1;
445 }
446 return PyList_SetItem(state->modules_by_index, index, Py_None);
447}
448
Antoine Pitrou40322e62013-08-11 00:30:09 +0200449/* used by import.c:PyImport_Cleanup */
450void
451_PyState_ClearModules(void)
452{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100453 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200454 if (state->modules_by_index) {
455 Py_ssize_t i;
456 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
457 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
458 if (PyModule_Check(m)) {
459 /* cleanup the saved copy of module dicts */
460 PyModuleDef *md = PyModule_GetDef(m);
461 if (md)
462 Py_CLEAR(md->m_base.m_copy);
463 }
464 }
465 /* Setting modules_by_index to NULL could be dangerous, so we
466 clear the list instead. */
467 if (PyList_SetSlice(state->modules_by_index,
468 0, PyList_GET_SIZE(state->modules_by_index),
469 NULL))
470 PyErr_WriteUnraisable(state->modules_by_index);
471 }
472}
473
Guido van Rossuma027efa1997-05-05 20:56:21 +0000474void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000475PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 if (Py_VerboseFlag && tstate->frame != NULL)
478 fprintf(stderr,
479 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 Py_CLEAR(tstate->dict);
484 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 Py_CLEAR(tstate->curexc_type);
487 Py_CLEAR(tstate->curexc_value);
488 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000489
Mark Shannonae3087c2017-10-22 22:41:51 +0100490 Py_CLEAR(tstate->exc_state.exc_type);
491 Py_CLEAR(tstate->exc_state.exc_value);
492 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300493
Mark Shannonae3087c2017-10-22 22:41:51 +0100494 /* The stack of exception states should contain just this thread. */
495 assert(tstate->exc_info->previous_item == NULL);
496 if (Py_VerboseFlag && tstate->exc_info != &tstate->exc_state) {
497 fprintf(stderr,
498 "PyThreadState_Clear: warning: thread still has a generator\n");
499 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 tstate->c_profilefunc = NULL;
502 tstate->c_tracefunc = NULL;
503 Py_CLEAR(tstate->c_profileobj);
504 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400505
506 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700507 Py_CLEAR(tstate->async_gen_firstiter);
508 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500509
510 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000511}
512
513
Guido van Rossum29757862001-01-23 01:46:06 +0000514/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
515static void
516tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (tstate == NULL)
520 Py_FatalError("PyThreadState_Delete: NULL tstate");
521 interp = tstate->interp;
522 if (interp == NULL)
523 Py_FatalError("PyThreadState_Delete: NULL interp");
524 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200525 if (tstate->prev)
526 tstate->prev->next = tstate->next;
527 else
528 interp->tstate_head = tstate->next;
529 if (tstate->next)
530 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200532 if (tstate->on_delete != NULL) {
533 tstate->on_delete(tstate->on_delete_data);
534 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200535 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000536}
537
538
Guido van Rossum29757862001-01-23 01:46:06 +0000539void
540PyThreadState_Delete(PyThreadState *tstate)
541{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100542 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600544 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900545 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600546 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900547 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600548 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200549 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000550}
551
552
Guido van Rossum29757862001-01-23 01:46:06 +0000553void
554PyThreadState_DeleteCurrent()
555{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100556 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 if (tstate == NULL)
558 Py_FatalError(
559 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100560 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600561 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900562 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600563 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900564 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600565 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100566 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000568}
Guido van Rossum29757862001-01-23 01:46:06 +0000569
570
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200571/*
572 * Delete all thread states except the one passed as argument.
573 * Note that, if there is a current thread state, it *must* be the one
574 * passed as argument. Also, this won't touch any other interpreters
575 * than the current one, since we don't know which thread state should
576 * be kept in those other interpreteres.
577 */
578void
579_PyThreadState_DeleteExcept(PyThreadState *tstate)
580{
581 PyInterpreterState *interp = tstate->interp;
582 PyThreadState *p, *next, *garbage;
583 HEAD_LOCK();
584 /* Remove all thread states, except tstate, from the linked list of
585 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200586 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200587 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200588 if (garbage == tstate)
589 garbage = tstate->next;
590 if (tstate->prev)
591 tstate->prev->next = tstate->next;
592 if (tstate->next)
593 tstate->next->prev = tstate->prev;
594 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200595 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200596 HEAD_UNLOCK();
597 /* Clear and deallocate all stale thread states. Even if this
598 executes Python code, we should be safe since it executes
599 in the current thread, not one of the stale threads. */
600 for (p = garbage; p; p = next) {
601 next = p->next;
602 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200603 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200604 }
605}
606
607
Guido van Rossuma027efa1997-05-05 20:56:21 +0000608PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100609_PyThreadState_UncheckedGet(void)
610{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100611 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100612}
613
614
615PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000616PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000617{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100618 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (tstate == NULL)
620 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000623}
624
625
626PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000627PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000628{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100629 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000630
Victor Stinnerb02ef712016-01-22 14:09:55 +0100631 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 /* It should not be possible for more than one thread state
633 to be used for a thread. Check this the best we can in debug
634 builds.
635 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200636#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 if (newts) {
638 /* This can be called from PyEval_RestoreThread(). Similar
639 to it, we need to ensure errno doesn't change.
640 */
641 int err = errno;
642 PyThreadState *check = PyGILState_GetThisThreadState();
643 if (check && check->interp == newts->interp && check != newts)
644 Py_FatalError("Invalid thread state for this thread");
645 errno = err;
646 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000647#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000649}
Guido van Rossumede04391998-04-10 20:18:25 +0000650
651/* An extension mechanism to store arbitrary additional per-thread state.
652 PyThreadState_GetDict() returns a dictionary that can be used to hold such
653 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000654 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
655 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000656
657PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000658PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000659{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100660 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 if (tstate == NULL)
662 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000663
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 if (tstate->dict == NULL) {
665 PyObject *d;
666 tstate->dict = d = PyDict_New();
667 if (d == NULL)
668 PyErr_Clear();
669 }
670 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000671}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000672
673
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000674/* Asynchronously raise an exception in a thread.
675 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000676 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000677 to call this, or use ctypes. Must be called with the GIL held.
678 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
679 match any known thread id). Can be called with exc=NULL to clear an
680 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000681
682int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200683PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
684{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100685 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 /* Although the GIL is held, a few C API functions can be called
689 * without the GIL held, and in particular some that create and
690 * destroy thread and interpreter states. Those can mutate the
691 * list of thread states we're traversing, so to prevent that we lock
692 * head_mutex for the duration.
693 */
694 HEAD_LOCK();
695 for (p = interp->tstate_head; p != NULL; p = p->next) {
696 if (p->thread_id == id) {
697 /* Tricky: we need to decref the current value
698 * (if any) in p->async_exc, but that can in turn
699 * allow arbitrary Python code to run, including
700 * perhaps calls to this function. To prevent
701 * deadlock, we need to release head_mutex before
702 * the decref.
703 */
704 PyObject *old_exc = p->async_exc;
705 Py_XINCREF(exc);
706 p->async_exc = exc;
707 HEAD_UNLOCK();
708 Py_XDECREF(old_exc);
709 _PyEval_SignalAsyncExc();
710 return 1;
711 }
712 }
713 HEAD_UNLOCK();
714 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000715}
716
717
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000718/* Routines for advanced debuggers, requested by David Beazley.
719 Don't use unless you know what you are doing! */
720
721PyInterpreterState *
722PyInterpreterState_Head(void)
723{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600724 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000725}
726
727PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700728PyInterpreterState_Main(void)
729{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600730 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700731}
732
733PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000734PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000736}
737
738PyThreadState *
739PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000741}
742
743PyThreadState *
744PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000746}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000747
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000748/* The implementation of sys._current_frames(). This is intended to be
749 called with the GIL held, as it will be when called via
750 sys._current_frames(). It's possible it would work fine even without
751 the GIL held, but haven't thought enough about that.
752*/
753PyObject *
754_PyThread_CurrentFrames(void)
755{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 PyObject *result;
757 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 result = PyDict_New();
760 if (result == NULL)
761 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 /* for i in all interpreters:
764 * for t in all of i's thread states:
765 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200766 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 * need to grab head_mutex for the duration.
768 */
769 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600770 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 PyThreadState *t;
772 for (t = i->tstate_head; t != NULL; t = t->next) {
773 PyObject *id;
774 int stat;
775 struct _frame *frame = t->frame;
776 if (frame == NULL)
777 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200778 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if (id == NULL)
780 goto Fail;
781 stat = PyDict_SetItem(result, id, (PyObject *)frame);
782 Py_DECREF(id);
783 if (stat < 0)
784 goto Fail;
785 }
786 }
787 HEAD_UNLOCK();
788 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000789
790 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 HEAD_UNLOCK();
792 Py_DECREF(result);
793 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000794}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000795
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000796/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000797
798/* Keep this as a static, as it is not reliable! It can only
799 ever be compared to the state for the *current* thread.
800 * If not equal, then it doesn't matter that the actual
801 value may change immediately after comparison, as it can't
802 possibly change to the current thread's state.
803 * If equal, then the current thread holds the lock, so the value can't
804 change until we yield the lock.
805*/
806static int
807PyThreadState_IsCurrent(PyThreadState *tstate)
808{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 /* Must be the tstate for this thread */
810 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100811 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000812}
813
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000814/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000815 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000816*/
Tim Peters19717fa2004-10-09 17:38:29 +0000817void
818_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900821 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
822 Py_FatalError("Could not allocate TSS entry");
823 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600824 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900825 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000827
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000829}
830
Victor Stinner861d9ab2016-03-16 22:45:24 +0100831PyInterpreterState *
832_PyGILState_GetInterpreterStateUnsafe(void)
833{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600834 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100835}
836
Tim Peters19717fa2004-10-09 17:38:29 +0000837void
838_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000839{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900840 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600841 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000842}
843
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900844/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200845 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900846 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200847 */
848void
849_PyGILState_Reinit(void)
850{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600851 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
852 if (_PyRuntime.interpreters.mutex == NULL)
853 Py_FatalError("Can't initialize threads for interpreter");
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200854 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900855 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
856 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
857 Py_FatalError("Could not allocate TSS entry");
858 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200859
Charles-François Natalia233df82011-11-22 19:49:51 +0100860 /* If the thread had an associated auto thread state, reassociate it with
861 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900862 if (tstate &&
863 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
864 {
865 Py_FatalError("Couldn't create autoTSSkey mapping");
866 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200867}
868
Michael W. Hudson188d4362005-06-20 16:52:57 +0000869/* When a thread state is created for a thread by some mechanism other than
870 PyGILState_Ensure, it's important that the GILState machinery knows about
871 it so it doesn't try to create another thread state for the thread (this is
872 a better fix for SF bug #1010677 than the first one attempted).
873*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000874static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000875_PyGILState_NoteThreadState(PyThreadState* tstate)
876{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900877 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +0000878 threadstate created in Py_Initialize(). Don't do anything for now
879 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600880 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000882
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900883 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000884
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 The only situation where you can legitimately have more than one
886 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100887 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000888
Victor Stinner590cebe2013-12-13 11:08:56 +0100889 You shouldn't really be using the PyGILState_ APIs anyway (see issues
890 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000891
Victor Stinner590cebe2013-12-13 11:08:56 +0100892 The first thread state created for that given OS level thread will
893 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900895 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
896 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
897 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600898 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900899 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600900 }
Victor Stinner590cebe2013-12-13 11:08:56 +0100901 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 /* PyGILState_Release must not try to delete this thread state. */
904 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000905}
906
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000907/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000908PyThreadState *
909PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000910{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600911 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900913 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000914}
915
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700916int
917PyGILState_Check(void)
918{
Victor Stinner8a1be612016-03-14 22:07:55 +0100919 PyThreadState *tstate;
920
921 if (!_PyGILState_check_enabled)
922 return 1;
923
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900924 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +0100925 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900926 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100927
928 tstate = GET_TSTATE();
929 if (tstate == NULL)
930 return 0;
931
932 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700933}
934
Tim Peters19717fa2004-10-09 17:38:29 +0000935PyGILState_STATE
936PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 int current;
939 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100940 int need_init_threads = 0;
941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 /* Note that we do not auto-init Python here - apart from
943 potential races with 2 threads auto-initializing, pep-311
944 spells out other issues. Embedders are expected to have
945 called Py_Initialize() and usually PyEval_InitThreads().
946 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600947 /* Py_Initialize() hasn't been called! */
948 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100949
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900950 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100952 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +0100953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600955 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 if (tcur == NULL)
957 Py_FatalError("Couldn't create thread-state for new thread");
958 /* This is our thread state! We'll need to delete it in the
959 matching call to PyGILState_Release(). */
960 tcur->gilstate_counter = 0;
961 current = 0; /* new thread state is never current */
962 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100963 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100965 }
966
967 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100969 }
970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 /* Update our counter in the thread-state - no need for locks:
972 - tcur will remain valid as we hold the GIL.
973 - the counter is safe as we are the only thread "allowed"
974 to modify this value
975 */
976 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100977
978 if (need_init_threads) {
979 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
980 called from a new thread for the first time, we need the create the
981 GIL. */
982 PyEval_InitThreads();
983 }
984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000986}
987
Tim Peters19717fa2004-10-09 17:38:29 +0000988void
989PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000990{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900991 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
992 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 if (tcur == NULL)
994 Py_FatalError("auto-releasing thread-state, "
995 "but no thread-state for this thread");
996 /* We must hold the GIL and have our thread state current */
997 /* XXX - remove the check - the assert should be fine,
998 but while this is very new (April 2003), the extra check
999 by release-only users can't hurt.
1000 */
1001 if (! PyThreadState_IsCurrent(tcur))
1002 Py_FatalError("This thread state must be current when releasing");
1003 assert(PyThreadState_IsCurrent(tcur));
1004 --tcur->gilstate_counter;
1005 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 /* If we're going to destroy this thread-state, we must
1008 * clear it while the GIL is held, as destructors may run.
1009 */
1010 if (tcur->gilstate_counter == 0) {
1011 /* can't have been locked when we created it */
1012 assert(oldstate == PyGILState_UNLOCKED);
1013 PyThreadState_Clear(tcur);
1014 /* Delete the thread-state. Note this releases the GIL too!
1015 * It's vital that the GIL be held here, to avoid shutdown
1016 * races; see bugs 225673 and 1061968 (that nasty bug has a
1017 * habit of coming back).
1018 */
1019 PyThreadState_DeleteCurrent();
1020 }
1021 /* Release the lock if necessary */
1022 else if (oldstate == PyGILState_UNLOCKED)
1023 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001024}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001025
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001026
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001027#ifdef __cplusplus
1028}
1029#endif