blob: 55ff64951b0b7eb66339aa1fcf4545b90d0647ad [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
Eric Snow2ebc5ce2017-09-07 23:51:28 -060038void
39_PyRuntimeState_Init(_PyRuntimeState *runtime)
40{
41 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010042
Eric Snow2ebc5ce2017-09-07 23:51:28 -060043 _PyObject_Initialize(&runtime->obj);
44 _PyMem_Initialize(&runtime->mem);
45 _PyGC_Initialize(&runtime->gc);
46 _PyEval_Initialize(&runtime->ceval);
Michael W. Hudson188d4362005-06-20 16:52:57 +000047
Eric Snow2ebc5ce2017-09-07 23:51:28 -060048 runtime->gilstate.check_enabled = 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090049 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
50 in accordance with the specification. */
51 {
52 Py_tss_t initial = Py_tss_NEEDS_INIT;
53 runtime->gilstate.autoTSSkey = initial;
54 }
Guido van Rossum1d5ad901999-06-18 14:22:24 +000055
Eric Snow2ebc5ce2017-09-07 23:51:28 -060056 runtime->interpreters.mutex = PyThread_allocate_lock();
57 if (runtime->interpreters.mutex == NULL)
58 Py_FatalError("Can't initialize threads for interpreter");
59 runtime->interpreters.next_id = -1;
60}
Eric Snow05351c12017-09-05 21:43:08 -070061
Eric Snow2ebc5ce2017-09-07 23:51:28 -060062void
63_PyRuntimeState_Fini(_PyRuntimeState *runtime)
64{
65 if (runtime->interpreters.mutex != NULL) {
66 PyThread_free_lock(runtime->interpreters.mutex);
67 runtime->interpreters.mutex = NULL;
68 }
69}
70
71#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
72 WAIT_LOCK)
73#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -070074
Michael W. Hudson188d4362005-06-20 16:52:57 +000075static void _PyGILState_NoteThreadState(PyThreadState* tstate);
76
Eric Snowe3774162017-05-22 19:46:40 -070077void
Eric Snow2ebc5ce2017-09-07 23:51:28 -060078_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -070079{
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080 runtime->interpreters.next_id = 0;
81 /* Since we only call _PyRuntimeState_Init() once per process
82 (see _PyRuntime_Initialize()), we make sure the mutex is
83 initialized here. */
84 if (runtime->interpreters.mutex == NULL) {
85 runtime->interpreters.mutex = PyThread_allocate_lock();
86 if (runtime->interpreters.mutex == NULL)
87 Py_FatalError("Can't initialize threads for interpreter");
88 }
Eric Snowe3774162017-05-22 19:46:40 -070089}
Guido van Rossuma027efa1997-05-05 20:56:21 +000090
91PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000092PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +000093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +020095 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +000096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 if (interp != NULL) {
Eric Snow93c92f72017-09-13 23:46:04 -070098 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 interp->modules_by_index = NULL;
100 interp->sysdict = NULL;
101 interp->builtins = NULL;
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200102 interp->builtins_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 interp->tstate_head = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600104 interp->check_interval = 100;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600105 interp->num_threads = 0;
106 interp->pythread_stacksize = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 interp->codec_search_path = NULL;
108 interp->codec_search_cache = NULL;
109 interp->codec_error_registry = NULL;
110 interp->codecs_initialized = 0;
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200111 interp->fscodec_initialized = 0;
Brett Cannonfd074152012-04-14 14:10:13 -0400112 interp->importlib = NULL;
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300113 interp->import_func = NULL;
Brett Cannon3cebf932016-09-05 15:33:46 -0700114 interp->eval_frame = _PyEval_EvalFrameDefault;
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700115 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000116#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300117#if HAVE_DECL_RTLD_NOW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000119#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000121#endif
122#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200123#ifdef HAVE_FORK
124 interp->before_forkers = NULL;
125 interp->after_forkers_parent = NULL;
126 interp->after_forkers_child = NULL;
127#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600130 interp->next = _PyRuntime.interpreters.head;
131 if (_PyRuntime.interpreters.main == NULL) {
132 _PyRuntime.interpreters.main = interp;
Eric Snow6b4be192017-05-22 21:36:03 -0700133 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600134 _PyRuntime.interpreters.head = interp;
135 if (_PyRuntime.interpreters.next_id < 0) {
Eric Snowe3774162017-05-22 19:46:40 -0700136 /* overflow or Py_Initialize() not called! */
137 PyErr_SetString(PyExc_RuntimeError,
138 "failed to get an interpreter ID");
139 interp = NULL;
140 } else {
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600141 interp->id = _PyRuntime.interpreters.next_id;
142 _PyRuntime.interpreters.next_id += 1;
Eric Snowe3774162017-05-22 19:46:40 -0700143 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 HEAD_UNLOCK();
145 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000148}
149
150
151void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000152PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000154 PyThreadState *p;
155 HEAD_LOCK();
156 for (p = interp->tstate_head; p != NULL; p = p->next)
157 PyThreadState_Clear(p);
158 HEAD_UNLOCK();
159 Py_CLEAR(interp->codec_search_path);
160 Py_CLEAR(interp->codec_search_cache);
161 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700162 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 Py_CLEAR(interp->sysdict);
165 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200166 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400167 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300168 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200169#ifdef HAVE_FORK
170 Py_CLEAR(interp->before_forkers);
171 Py_CLEAR(interp->after_forkers_parent);
172 Py_CLEAR(interp->after_forkers_child);
173#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000174}
175
176
177static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000178zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 PyThreadState *p;
181 /* No need to lock the mutex here because this should only happen
182 when the threads are all really dead (XXX famous last words). */
183 while ((p = interp->tstate_head) != NULL) {
184 PyThreadState_Delete(p);
185 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000186}
187
188
189void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000190PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 PyInterpreterState **p;
193 zapthreads(interp);
194 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600195 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 if (*p == NULL)
197 Py_FatalError(
198 "PyInterpreterState_Delete: invalid interp");
199 if (*p == interp)
200 break;
201 }
202 if (interp->tstate_head != NULL)
203 Py_FatalError("PyInterpreterState_Delete: remaining threads");
204 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600205 if (_PyRuntime.interpreters.main == interp) {
206 _PyRuntime.interpreters.main = NULL;
207 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700208 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
209 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200211 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000212}
213
214
Eric Snowe3774162017-05-22 19:46:40 -0700215int64_t
216PyInterpreterState_GetID(PyInterpreterState *interp)
217{
218 if (interp == NULL) {
219 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
220 return -1;
221 }
222 return interp->id;
223}
224
225
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000226/* Default implementation for _PyThreadState_GetFrame */
227static struct _frame *
228threadstate_getframe(PyThreadState *self)
229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000231}
232
Victor Stinner45b9be52010-03-03 23:28:07 +0000233static PyThreadState *
234new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000235{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200236 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 if (_PyThreadState_GetFrame == NULL)
239 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 if (tstate != NULL) {
242 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 tstate->frame = NULL;
245 tstate->recursion_depth = 0;
246 tstate->overflowed = 0;
247 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700248 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 tstate->tracing = 0;
250 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 tstate->gilstate_counter = 0;
252 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 tstate->curexc_type = NULL;
258 tstate->curexc_value = NULL;
259 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000260
Mark Shannonae3087c2017-10-22 22:41:51 +0100261 tstate->exc_state.exc_type = NULL;
262 tstate->exc_state.exc_value = NULL;
263 tstate->exc_state.exc_traceback = NULL;
264 tstate->exc_state.previous_item = NULL;
265 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 tstate->c_profilefunc = NULL;
268 tstate->c_tracefunc = NULL;
269 tstate->c_profileobj = NULL;
270 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000271
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200272 tstate->trash_delete_nesting = 0;
273 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200274 tstate->on_delete = NULL;
275 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200276
Yury Selivanov75445082015-05-11 22:57:16 -0400277 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400278 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400279
Yury Selivanoveb636452016-09-08 22:01:51 -0700280 tstate->async_gen_firstiter = NULL;
281 tstate->async_gen_finalizer = NULL;
282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 if (init)
284 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200287 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200289 if (tstate->next)
290 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 interp->tstate_head = tstate;
292 HEAD_UNLOCK();
293 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000296}
297
Victor Stinner45b9be52010-03-03 23:28:07 +0000298PyThreadState *
299PyThreadState_New(PyInterpreterState *interp)
300{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000302}
303
304PyThreadState *
305_PyThreadState_Prealloc(PyInterpreterState *interp)
306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000308}
309
310void
311_PyThreadState_Init(PyThreadState *tstate)
312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000314}
315
Martin v. Löwis1a214512008-06-11 05:26:20 +0000316PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200317PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000318{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200319 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100320 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000322 if (module->m_slots) {
323 return NULL;
324 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 if (index == 0)
326 return NULL;
327 if (state->modules_by_index == NULL)
328 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200329 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return NULL;
331 res = PyList_GET_ITEM(state->modules_by_index, index);
332 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000333}
334
335int
336_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
337{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000338 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300339 if (!def) {
340 assert(PyErr_Occurred());
341 return -1;
342 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000343 if (def->m_slots) {
344 PyErr_SetString(PyExc_SystemError,
345 "PyState_AddModule called on module with slots");
346 return -1;
347 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100348 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 if (!state->modules_by_index) {
350 state->modules_by_index = PyList_New(0);
351 if (!state->modules_by_index)
352 return -1;
353 }
354 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
355 if (PyList_Append(state->modules_by_index, Py_None) < 0)
356 return -1;
357 Py_INCREF(module);
358 return PyList_SetItem(state->modules_by_index,
359 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000360}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000361
Martin v. Löwis7800f752012-06-22 12:20:55 +0200362int
363PyState_AddModule(PyObject* module, struct PyModuleDef* def)
364{
365 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100366 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200367 if (!def) {
368 Py_FatalError("PyState_AddModule: Module Definition is NULL");
369 return -1;
370 }
371 index = def->m_base.m_index;
372 if (state->modules_by_index) {
373 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
374 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
375 Py_FatalError("PyState_AddModule: Module already added!");
376 return -1;
377 }
378 }
379 }
380 return _PyState_AddModule(module, def);
381}
382
383int
384PyState_RemoveModule(struct PyModuleDef* def)
385{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000386 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200387 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000388 if (def->m_slots) {
389 PyErr_SetString(PyExc_SystemError,
390 "PyState_RemoveModule called on module with slots");
391 return -1;
392 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100393 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200394 if (index == 0) {
395 Py_FatalError("PyState_RemoveModule: Module index invalid.");
396 return -1;
397 }
398 if (state->modules_by_index == NULL) {
399 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
400 return -1;
401 }
402 if (index > PyList_GET_SIZE(state->modules_by_index)) {
403 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
404 return -1;
405 }
406 return PyList_SetItem(state->modules_by_index, index, Py_None);
407}
408
Antoine Pitrou40322e62013-08-11 00:30:09 +0200409/* used by import.c:PyImport_Cleanup */
410void
411_PyState_ClearModules(void)
412{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100413 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200414 if (state->modules_by_index) {
415 Py_ssize_t i;
416 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
417 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
418 if (PyModule_Check(m)) {
419 /* cleanup the saved copy of module dicts */
420 PyModuleDef *md = PyModule_GetDef(m);
421 if (md)
422 Py_CLEAR(md->m_base.m_copy);
423 }
424 }
425 /* Setting modules_by_index to NULL could be dangerous, so we
426 clear the list instead. */
427 if (PyList_SetSlice(state->modules_by_index,
428 0, PyList_GET_SIZE(state->modules_by_index),
429 NULL))
430 PyErr_WriteUnraisable(state->modules_by_index);
431 }
432}
433
Guido van Rossuma027efa1997-05-05 20:56:21 +0000434void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000435PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 if (Py_VerboseFlag && tstate->frame != NULL)
438 fprintf(stderr,
439 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 Py_CLEAR(tstate->dict);
444 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 Py_CLEAR(tstate->curexc_type);
447 Py_CLEAR(tstate->curexc_value);
448 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000449
Mark Shannonae3087c2017-10-22 22:41:51 +0100450 Py_CLEAR(tstate->exc_state.exc_type);
451 Py_CLEAR(tstate->exc_state.exc_value);
452 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300453
Mark Shannonae3087c2017-10-22 22:41:51 +0100454 /* The stack of exception states should contain just this thread. */
455 assert(tstate->exc_info->previous_item == NULL);
456 if (Py_VerboseFlag && tstate->exc_info != &tstate->exc_state) {
457 fprintf(stderr,
458 "PyThreadState_Clear: warning: thread still has a generator\n");
459 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 tstate->c_profilefunc = NULL;
462 tstate->c_tracefunc = NULL;
463 Py_CLEAR(tstate->c_profileobj);
464 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400465
466 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700467 Py_CLEAR(tstate->async_gen_firstiter);
468 Py_CLEAR(tstate->async_gen_finalizer);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000469}
470
471
Guido van Rossum29757862001-01-23 01:46:06 +0000472/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
473static void
474tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 if (tstate == NULL)
478 Py_FatalError("PyThreadState_Delete: NULL tstate");
479 interp = tstate->interp;
480 if (interp == NULL)
481 Py_FatalError("PyThreadState_Delete: NULL interp");
482 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200483 if (tstate->prev)
484 tstate->prev->next = tstate->next;
485 else
486 interp->tstate_head = tstate->next;
487 if (tstate->next)
488 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200490 if (tstate->on_delete != NULL) {
491 tstate->on_delete(tstate->on_delete_data);
492 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200493 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000494}
495
496
Guido van Rossum29757862001-01-23 01:46:06 +0000497void
498PyThreadState_Delete(PyThreadState *tstate)
499{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100500 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600502 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900503 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600504 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900505 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600506 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200507 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000508}
509
510
Guido van Rossum29757862001-01-23 01:46:06 +0000511void
512PyThreadState_DeleteCurrent()
513{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100514 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 if (tstate == NULL)
516 Py_FatalError(
517 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100518 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600519 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900520 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600521 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900522 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600523 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100524 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000526}
Guido van Rossum29757862001-01-23 01:46:06 +0000527
528
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200529/*
530 * Delete all thread states except the one passed as argument.
531 * Note that, if there is a current thread state, it *must* be the one
532 * passed as argument. Also, this won't touch any other interpreters
533 * than the current one, since we don't know which thread state should
534 * be kept in those other interpreteres.
535 */
536void
537_PyThreadState_DeleteExcept(PyThreadState *tstate)
538{
539 PyInterpreterState *interp = tstate->interp;
540 PyThreadState *p, *next, *garbage;
541 HEAD_LOCK();
542 /* Remove all thread states, except tstate, from the linked list of
543 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200544 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200545 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200546 if (garbage == tstate)
547 garbage = tstate->next;
548 if (tstate->prev)
549 tstate->prev->next = tstate->next;
550 if (tstate->next)
551 tstate->next->prev = tstate->prev;
552 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200553 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200554 HEAD_UNLOCK();
555 /* Clear and deallocate all stale thread states. Even if this
556 executes Python code, we should be safe since it executes
557 in the current thread, not one of the stale threads. */
558 for (p = garbage; p; p = next) {
559 next = p->next;
560 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200561 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200562 }
563}
564
565
Guido van Rossuma027efa1997-05-05 20:56:21 +0000566PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100567_PyThreadState_UncheckedGet(void)
568{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100569 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100570}
571
572
573PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000574PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000575{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100576 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 if (tstate == NULL)
578 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000581}
582
583
584PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000585PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000586{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100587 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000588
Victor Stinnerb02ef712016-01-22 14:09:55 +0100589 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 /* It should not be possible for more than one thread state
591 to be used for a thread. Check this the best we can in debug
592 builds.
593 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200594#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 if (newts) {
596 /* This can be called from PyEval_RestoreThread(). Similar
597 to it, we need to ensure errno doesn't change.
598 */
599 int err = errno;
600 PyThreadState *check = PyGILState_GetThisThreadState();
601 if (check && check->interp == newts->interp && check != newts)
602 Py_FatalError("Invalid thread state for this thread");
603 errno = err;
604 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000605#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000607}
Guido van Rossumede04391998-04-10 20:18:25 +0000608
609/* An extension mechanism to store arbitrary additional per-thread state.
610 PyThreadState_GetDict() returns a dictionary that can be used to hold such
611 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000612 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
613 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000614
615PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000616PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +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 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 if (tstate->dict == NULL) {
623 PyObject *d;
624 tstate->dict = d = PyDict_New();
625 if (d == NULL)
626 PyErr_Clear();
627 }
628 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000629}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000630
631
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000632/* Asynchronously raise an exception in a thread.
633 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000634 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000635 to call this, or use ctypes. Must be called with the GIL held.
636 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
637 match any known thread id). Can be called with exc=NULL to clear an
638 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000639
640int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200641PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
642{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100643 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 /* Although the GIL is held, a few C API functions can be called
647 * without the GIL held, and in particular some that create and
648 * destroy thread and interpreter states. Those can mutate the
649 * list of thread states we're traversing, so to prevent that we lock
650 * head_mutex for the duration.
651 */
652 HEAD_LOCK();
653 for (p = interp->tstate_head; p != NULL; p = p->next) {
654 if (p->thread_id == id) {
655 /* Tricky: we need to decref the current value
656 * (if any) in p->async_exc, but that can in turn
657 * allow arbitrary Python code to run, including
658 * perhaps calls to this function. To prevent
659 * deadlock, we need to release head_mutex before
660 * the decref.
661 */
662 PyObject *old_exc = p->async_exc;
663 Py_XINCREF(exc);
664 p->async_exc = exc;
665 HEAD_UNLOCK();
666 Py_XDECREF(old_exc);
667 _PyEval_SignalAsyncExc();
668 return 1;
669 }
670 }
671 HEAD_UNLOCK();
672 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000673}
674
675
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000676/* Routines for advanced debuggers, requested by David Beazley.
677 Don't use unless you know what you are doing! */
678
679PyInterpreterState *
680PyInterpreterState_Head(void)
681{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600682 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000683}
684
685PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700686PyInterpreterState_Main(void)
687{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600688 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700689}
690
691PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000692PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000694}
695
696PyThreadState *
697PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000699}
700
701PyThreadState *
702PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000704}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000705
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000706/* The implementation of sys._current_frames(). This is intended to be
707 called with the GIL held, as it will be when called via
708 sys._current_frames(). It's possible it would work fine even without
709 the GIL held, but haven't thought enough about that.
710*/
711PyObject *
712_PyThread_CurrentFrames(void)
713{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyObject *result;
715 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 result = PyDict_New();
718 if (result == NULL)
719 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 /* for i in all interpreters:
722 * for t in all of i's thread states:
723 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200724 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 * need to grab head_mutex for the duration.
726 */
727 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600728 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 PyThreadState *t;
730 for (t = i->tstate_head; t != NULL; t = t->next) {
731 PyObject *id;
732 int stat;
733 struct _frame *frame = t->frame;
734 if (frame == NULL)
735 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200736 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 if (id == NULL)
738 goto Fail;
739 stat = PyDict_SetItem(result, id, (PyObject *)frame);
740 Py_DECREF(id);
741 if (stat < 0)
742 goto Fail;
743 }
744 }
745 HEAD_UNLOCK();
746 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000747
748 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 HEAD_UNLOCK();
750 Py_DECREF(result);
751 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000752}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000753
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000754/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000755
756/* Keep this as a static, as it is not reliable! It can only
757 ever be compared to the state for the *current* thread.
758 * If not equal, then it doesn't matter that the actual
759 value may change immediately after comparison, as it can't
760 possibly change to the current thread's state.
761 * If equal, then the current thread holds the lock, so the value can't
762 change until we yield the lock.
763*/
764static int
765PyThreadState_IsCurrent(PyThreadState *tstate)
766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 /* Must be the tstate for this thread */
768 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100769 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000770}
771
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000772/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000773 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000774*/
Tim Peters19717fa2004-10-09 17:38:29 +0000775void
776_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900779 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
780 Py_FatalError("Could not allocate TSS entry");
781 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600782 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900783 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000787}
788
Victor Stinner861d9ab2016-03-16 22:45:24 +0100789PyInterpreterState *
790_PyGILState_GetInterpreterStateUnsafe(void)
791{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600792 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100793}
794
Tim Peters19717fa2004-10-09 17:38:29 +0000795void
796_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000797{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900798 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600799 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000800}
801
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900802/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200803 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900804 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200805 */
806void
807_PyGILState_Reinit(void)
808{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600809 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
810 if (_PyRuntime.interpreters.mutex == NULL)
811 Py_FatalError("Can't initialize threads for interpreter");
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200812 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900813 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
814 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
815 Py_FatalError("Could not allocate TSS entry");
816 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200817
Charles-François Natalia233df82011-11-22 19:49:51 +0100818 /* If the thread had an associated auto thread state, reassociate it with
819 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900820 if (tstate &&
821 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
822 {
823 Py_FatalError("Couldn't create autoTSSkey mapping");
824 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200825}
826
Michael W. Hudson188d4362005-06-20 16:52:57 +0000827/* When a thread state is created for a thread by some mechanism other than
828 PyGILState_Ensure, it's important that the GILState machinery knows about
829 it so it doesn't try to create another thread state for the thread (this is
830 a better fix for SF bug #1010677 than the first one attempted).
831*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000832static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000833_PyGILState_NoteThreadState(PyThreadState* tstate)
834{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900835 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +0000836 threadstate created in Py_Initialize(). Don't do anything for now
837 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600838 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000840
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900841 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 The only situation where you can legitimately have more than one
844 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100845 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000846
Victor Stinner590cebe2013-12-13 11:08:56 +0100847 You shouldn't really be using the PyGILState_ APIs anyway (see issues
848 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000849
Victor Stinner590cebe2013-12-13 11:08:56 +0100850 The first thread state created for that given OS level thread will
851 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900853 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
854 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
855 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600856 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900857 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600858 }
Victor Stinner590cebe2013-12-13 11:08:56 +0100859 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 /* PyGILState_Release must not try to delete this thread state. */
862 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000863}
864
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000865/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000866PyThreadState *
867PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000868{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600869 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900871 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000872}
873
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700874int
875PyGILState_Check(void)
876{
Victor Stinner8a1be612016-03-14 22:07:55 +0100877 PyThreadState *tstate;
878
879 if (!_PyGILState_check_enabled)
880 return 1;
881
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900882 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +0100883 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900884 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100885
886 tstate = GET_TSTATE();
887 if (tstate == NULL)
888 return 0;
889
890 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700891}
892
Tim Peters19717fa2004-10-09 17:38:29 +0000893PyGILState_STATE
894PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 int current;
897 PyThreadState *tcur;
898 /* Note that we do not auto-init Python here - apart from
899 potential races with 2 threads auto-initializing, pep-311
900 spells out other issues. Embedders are expected to have
901 called Py_Initialize() and usually PyEval_InitThreads().
902 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600903 /* Py_Initialize() hasn't been called! */
904 assert(_PyRuntime.gilstate.autoInterpreterState);
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900905 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 if (tcur == NULL) {
Victor Stinner62ca1002013-12-13 01:46:43 +0100907 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
908 called from a new thread for the first time, we need the create the
909 GIL. */
910 PyEval_InitThreads();
911
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000912 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600913 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 if (tcur == NULL)
915 Py_FatalError("Couldn't create thread-state for new thread");
916 /* This is our thread state! We'll need to delete it in the
917 matching call to PyGILState_Release(). */
918 tcur->gilstate_counter = 0;
919 current = 0; /* new thread state is never current */
920 }
921 else
922 current = PyThreadState_IsCurrent(tcur);
923 if (current == 0)
924 PyEval_RestoreThread(tcur);
925 /* Update our counter in the thread-state - no need for locks:
926 - tcur will remain valid as we hold the GIL.
927 - the counter is safe as we are the only thread "allowed"
928 to modify this value
929 */
930 ++tcur->gilstate_counter;
931 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000932}
933
Tim Peters19717fa2004-10-09 17:38:29 +0000934void
935PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000936{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900937 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
938 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 if (tcur == NULL)
940 Py_FatalError("auto-releasing thread-state, "
941 "but no thread-state for this thread");
942 /* We must hold the GIL and have our thread state current */
943 /* XXX - remove the check - the assert should be fine,
944 but while this is very new (April 2003), the extra check
945 by release-only users can't hurt.
946 */
947 if (! PyThreadState_IsCurrent(tcur))
948 Py_FatalError("This thread state must be current when releasing");
949 assert(PyThreadState_IsCurrent(tcur));
950 --tcur->gilstate_counter;
951 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 /* If we're going to destroy this thread-state, we must
954 * clear it while the GIL is held, as destructors may run.
955 */
956 if (tcur->gilstate_counter == 0) {
957 /* can't have been locked when we created it */
958 assert(oldstate == PyGILState_UNLOCKED);
959 PyThreadState_Clear(tcur);
960 /* Delete the thread-state. Note this releases the GIL too!
961 * It's vital that the GIL be held here, to avoid shutdown
962 * races; see bugs 225673 and 1061968 (that nasty bug has a
963 * habit of coming back).
964 */
965 PyThreadState_DeleteCurrent();
966 }
967 /* Release the lock if necessary */
968 else if (oldstate == PyGILState_UNLOCKED)
969 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000970}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000971
Benjamin Peterson3bf01752012-04-13 18:06:36 -0400972
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000973#ifdef __cplusplus
974}
975#endif