blob: 3feae346d44cac9e90c4b5eb927c83066bf3354b [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;
248 tstate->tracing = 0;
249 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 tstate->gilstate_counter = 0;
251 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 tstate->curexc_type = NULL;
257 tstate->curexc_value = NULL;
258 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 tstate->exc_type = NULL;
261 tstate->exc_value = NULL;
262 tstate->exc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 tstate->c_profilefunc = NULL;
265 tstate->c_tracefunc = NULL;
266 tstate->c_profileobj = NULL;
267 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000268
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200269 tstate->trash_delete_nesting = 0;
270 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200271 tstate->on_delete = NULL;
272 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200273
Yury Selivanov75445082015-05-11 22:57:16 -0400274 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400275 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400276
Yury Selivanoveb636452016-09-08 22:01:51 -0700277 tstate->async_gen_firstiter = NULL;
278 tstate->async_gen_finalizer = NULL;
279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 if (init)
281 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200284 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200286 if (tstate->next)
287 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 interp->tstate_head = tstate;
289 HEAD_UNLOCK();
290 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000293}
294
Victor Stinner45b9be52010-03-03 23:28:07 +0000295PyThreadState *
296PyThreadState_New(PyInterpreterState *interp)
297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000299}
300
301PyThreadState *
302_PyThreadState_Prealloc(PyInterpreterState *interp)
303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000305}
306
307void
308_PyThreadState_Init(PyThreadState *tstate)
309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000311}
312
Martin v. Löwis1a214512008-06-11 05:26:20 +0000313PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200314PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000315{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200316 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100317 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000319 if (module->m_slots) {
320 return NULL;
321 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 if (index == 0)
323 return NULL;
324 if (state->modules_by_index == NULL)
325 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200326 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 return NULL;
328 res = PyList_GET_ITEM(state->modules_by_index, index);
329 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000330}
331
332int
333_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
334{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000335 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300336 if (!def) {
337 assert(PyErr_Occurred());
338 return -1;
339 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000340 if (def->m_slots) {
341 PyErr_SetString(PyExc_SystemError,
342 "PyState_AddModule called on module with slots");
343 return -1;
344 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100345 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 if (!state->modules_by_index) {
347 state->modules_by_index = PyList_New(0);
348 if (!state->modules_by_index)
349 return -1;
350 }
351 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
352 if (PyList_Append(state->modules_by_index, Py_None) < 0)
353 return -1;
354 Py_INCREF(module);
355 return PyList_SetItem(state->modules_by_index,
356 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000357}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000358
Martin v. Löwis7800f752012-06-22 12:20:55 +0200359int
360PyState_AddModule(PyObject* module, struct PyModuleDef* def)
361{
362 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100363 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200364 if (!def) {
365 Py_FatalError("PyState_AddModule: Module Definition is NULL");
366 return -1;
367 }
368 index = def->m_base.m_index;
369 if (state->modules_by_index) {
370 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
371 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
372 Py_FatalError("PyState_AddModule: Module already added!");
373 return -1;
374 }
375 }
376 }
377 return _PyState_AddModule(module, def);
378}
379
380int
381PyState_RemoveModule(struct PyModuleDef* def)
382{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000383 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200384 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000385 if (def->m_slots) {
386 PyErr_SetString(PyExc_SystemError,
387 "PyState_RemoveModule called on module with slots");
388 return -1;
389 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100390 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200391 if (index == 0) {
392 Py_FatalError("PyState_RemoveModule: Module index invalid.");
393 return -1;
394 }
395 if (state->modules_by_index == NULL) {
396 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
397 return -1;
398 }
399 if (index > PyList_GET_SIZE(state->modules_by_index)) {
400 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
401 return -1;
402 }
403 return PyList_SetItem(state->modules_by_index, index, Py_None);
404}
405
Antoine Pitrou40322e62013-08-11 00:30:09 +0200406/* used by import.c:PyImport_Cleanup */
407void
408_PyState_ClearModules(void)
409{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100410 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200411 if (state->modules_by_index) {
412 Py_ssize_t i;
413 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
414 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
415 if (PyModule_Check(m)) {
416 /* cleanup the saved copy of module dicts */
417 PyModuleDef *md = PyModule_GetDef(m);
418 if (md)
419 Py_CLEAR(md->m_base.m_copy);
420 }
421 }
422 /* Setting modules_by_index to NULL could be dangerous, so we
423 clear the list instead. */
424 if (PyList_SetSlice(state->modules_by_index,
425 0, PyList_GET_SIZE(state->modules_by_index),
426 NULL))
427 PyErr_WriteUnraisable(state->modules_by_index);
428 }
429}
430
Guido van Rossuma027efa1997-05-05 20:56:21 +0000431void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000432PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000433{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 if (Py_VerboseFlag && tstate->frame != NULL)
435 fprintf(stderr,
436 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 Py_CLEAR(tstate->dict);
441 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 Py_CLEAR(tstate->curexc_type);
444 Py_CLEAR(tstate->curexc_value);
445 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 Py_CLEAR(tstate->exc_type);
448 Py_CLEAR(tstate->exc_value);
449 Py_CLEAR(tstate->exc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 tstate->c_profilefunc = NULL;
452 tstate->c_tracefunc = NULL;
453 Py_CLEAR(tstate->c_profileobj);
454 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400455
456 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700457 Py_CLEAR(tstate->async_gen_firstiter);
458 Py_CLEAR(tstate->async_gen_finalizer);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000459}
460
461
Guido van Rossum29757862001-01-23 01:46:06 +0000462/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
463static void
464tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 if (tstate == NULL)
468 Py_FatalError("PyThreadState_Delete: NULL tstate");
469 interp = tstate->interp;
470 if (interp == NULL)
471 Py_FatalError("PyThreadState_Delete: NULL interp");
472 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200473 if (tstate->prev)
474 tstate->prev->next = tstate->next;
475 else
476 interp->tstate_head = tstate->next;
477 if (tstate->next)
478 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200480 if (tstate->on_delete != NULL) {
481 tstate->on_delete(tstate->on_delete_data);
482 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200483 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000484}
485
486
Guido van Rossum29757862001-01-23 01:46:06 +0000487void
488PyThreadState_Delete(PyThreadState *tstate)
489{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100490 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600492 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900493 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600494 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900495 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600496 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200497 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000498}
499
500
Guido van Rossum29757862001-01-23 01:46:06 +0000501void
502PyThreadState_DeleteCurrent()
503{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100504 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 if (tstate == NULL)
506 Py_FatalError(
507 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100508 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600509 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900510 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600511 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900512 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600513 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100514 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000516}
Guido van Rossum29757862001-01-23 01:46:06 +0000517
518
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200519/*
520 * Delete all thread states except the one passed as argument.
521 * Note that, if there is a current thread state, it *must* be the one
522 * passed as argument. Also, this won't touch any other interpreters
523 * than the current one, since we don't know which thread state should
524 * be kept in those other interpreteres.
525 */
526void
527_PyThreadState_DeleteExcept(PyThreadState *tstate)
528{
529 PyInterpreterState *interp = tstate->interp;
530 PyThreadState *p, *next, *garbage;
531 HEAD_LOCK();
532 /* Remove all thread states, except tstate, from the linked list of
533 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200534 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200535 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200536 if (garbage == tstate)
537 garbage = tstate->next;
538 if (tstate->prev)
539 tstate->prev->next = tstate->next;
540 if (tstate->next)
541 tstate->next->prev = tstate->prev;
542 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200543 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200544 HEAD_UNLOCK();
545 /* Clear and deallocate all stale thread states. Even if this
546 executes Python code, we should be safe since it executes
547 in the current thread, not one of the stale threads. */
548 for (p = garbage; p; p = next) {
549 next = p->next;
550 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200551 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200552 }
553}
554
555
Guido van Rossuma027efa1997-05-05 20:56:21 +0000556PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100557_PyThreadState_UncheckedGet(void)
558{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100559 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100560}
561
562
563PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000564PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000565{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100566 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 if (tstate == NULL)
568 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000571}
572
573
574PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000575PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000576{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100577 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000578
Victor Stinnerb02ef712016-01-22 14:09:55 +0100579 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 /* It should not be possible for more than one thread state
581 to be used for a thread. Check this the best we can in debug
582 builds.
583 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200584#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 if (newts) {
586 /* This can be called from PyEval_RestoreThread(). Similar
587 to it, we need to ensure errno doesn't change.
588 */
589 int err = errno;
590 PyThreadState *check = PyGILState_GetThisThreadState();
591 if (check && check->interp == newts->interp && check != newts)
592 Py_FatalError("Invalid thread state for this thread");
593 errno = err;
594 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000595#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000597}
Guido van Rossumede04391998-04-10 20:18:25 +0000598
599/* An extension mechanism to store arbitrary additional per-thread state.
600 PyThreadState_GetDict() returns a dictionary that can be used to hold such
601 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000602 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
603 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000604
605PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000606PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000607{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100608 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (tstate == NULL)
610 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (tstate->dict == NULL) {
613 PyObject *d;
614 tstate->dict = d = PyDict_New();
615 if (d == NULL)
616 PyErr_Clear();
617 }
618 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000619}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000620
621
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000622/* Asynchronously raise an exception in a thread.
623 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000624 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000625 to call this, or use ctypes. Must be called with the GIL held.
626 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
627 match any known thread id). Can be called with exc=NULL to clear an
628 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000629
630int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200631PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
632{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100633 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 /* Although the GIL is held, a few C API functions can be called
637 * without the GIL held, and in particular some that create and
638 * destroy thread and interpreter states. Those can mutate the
639 * list of thread states we're traversing, so to prevent that we lock
640 * head_mutex for the duration.
641 */
642 HEAD_LOCK();
643 for (p = interp->tstate_head; p != NULL; p = p->next) {
644 if (p->thread_id == id) {
645 /* Tricky: we need to decref the current value
646 * (if any) in p->async_exc, but that can in turn
647 * allow arbitrary Python code to run, including
648 * perhaps calls to this function. To prevent
649 * deadlock, we need to release head_mutex before
650 * the decref.
651 */
652 PyObject *old_exc = p->async_exc;
653 Py_XINCREF(exc);
654 p->async_exc = exc;
655 HEAD_UNLOCK();
656 Py_XDECREF(old_exc);
657 _PyEval_SignalAsyncExc();
658 return 1;
659 }
660 }
661 HEAD_UNLOCK();
662 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000663}
664
665
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000666/* Routines for advanced debuggers, requested by David Beazley.
667 Don't use unless you know what you are doing! */
668
669PyInterpreterState *
670PyInterpreterState_Head(void)
671{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600672 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000673}
674
675PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700676PyInterpreterState_Main(void)
677{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600678 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700679}
680
681PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000682PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000684}
685
686PyThreadState *
687PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000689}
690
691PyThreadState *
692PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000694}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000695
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000696/* The implementation of sys._current_frames(). This is intended to be
697 called with the GIL held, as it will be when called via
698 sys._current_frames(). It's possible it would work fine even without
699 the GIL held, but haven't thought enough about that.
700*/
701PyObject *
702_PyThread_CurrentFrames(void)
703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 PyObject *result;
705 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 result = PyDict_New();
708 if (result == NULL)
709 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 /* for i in all interpreters:
712 * for t in all of i's thread states:
713 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200714 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 * need to grab head_mutex for the duration.
716 */
717 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600718 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 PyThreadState *t;
720 for (t = i->tstate_head; t != NULL; t = t->next) {
721 PyObject *id;
722 int stat;
723 struct _frame *frame = t->frame;
724 if (frame == NULL)
725 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200726 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 if (id == NULL)
728 goto Fail;
729 stat = PyDict_SetItem(result, id, (PyObject *)frame);
730 Py_DECREF(id);
731 if (stat < 0)
732 goto Fail;
733 }
734 }
735 HEAD_UNLOCK();
736 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000737
738 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 HEAD_UNLOCK();
740 Py_DECREF(result);
741 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000742}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000743
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000744/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000745
746/* Keep this as a static, as it is not reliable! It can only
747 ever be compared to the state for the *current* thread.
748 * If not equal, then it doesn't matter that the actual
749 value may change immediately after comparison, as it can't
750 possibly change to the current thread's state.
751 * If equal, then the current thread holds the lock, so the value can't
752 change until we yield the lock.
753*/
754static int
755PyThreadState_IsCurrent(PyThreadState *tstate)
756{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 /* Must be the tstate for this thread */
758 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100759 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000760}
761
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000762/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000763 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000764*/
Tim Peters19717fa2004-10-09 17:38:29 +0000765void
766_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900769 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
770 Py_FatalError("Could not allocate TSS entry");
771 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600772 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900773 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000777}
778
Victor Stinner861d9ab2016-03-16 22:45:24 +0100779PyInterpreterState *
780_PyGILState_GetInterpreterStateUnsafe(void)
781{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600782 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100783}
784
Tim Peters19717fa2004-10-09 17:38:29 +0000785void
786_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000787{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900788 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600789 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000790}
791
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900792/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200793 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900794 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200795 */
796void
797_PyGILState_Reinit(void)
798{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600799 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
800 if (_PyRuntime.interpreters.mutex == NULL)
801 Py_FatalError("Can't initialize threads for interpreter");
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200802 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900803 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
804 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
805 Py_FatalError("Could not allocate TSS entry");
806 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200807
Charles-François Natalia233df82011-11-22 19:49:51 +0100808 /* If the thread had an associated auto thread state, reassociate it with
809 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900810 if (tstate &&
811 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
812 {
813 Py_FatalError("Couldn't create autoTSSkey mapping");
814 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200815}
816
Michael W. Hudson188d4362005-06-20 16:52:57 +0000817/* When a thread state is created for a thread by some mechanism other than
818 PyGILState_Ensure, it's important that the GILState machinery knows about
819 it so it doesn't try to create another thread state for the thread (this is
820 a better fix for SF bug #1010677 than the first one attempted).
821*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000822static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000823_PyGILState_NoteThreadState(PyThreadState* tstate)
824{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900825 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +0000826 threadstate created in Py_Initialize(). Don't do anything for now
827 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600828 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000830
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900831 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 The only situation where you can legitimately have more than one
834 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100835 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000836
Victor Stinner590cebe2013-12-13 11:08:56 +0100837 You shouldn't really be using the PyGILState_ APIs anyway (see issues
838 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000839
Victor Stinner590cebe2013-12-13 11:08:56 +0100840 The first thread state created for that given OS level thread will
841 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900843 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
844 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
845 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600846 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900847 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600848 }
Victor Stinner590cebe2013-12-13 11:08:56 +0100849 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 /* PyGILState_Release must not try to delete this thread state. */
852 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000853}
854
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000855/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000856PyThreadState *
857PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000858{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600859 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900861 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000862}
863
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700864int
865PyGILState_Check(void)
866{
Victor Stinner8a1be612016-03-14 22:07:55 +0100867 PyThreadState *tstate;
868
869 if (!_PyGILState_check_enabled)
870 return 1;
871
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900872 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +0100873 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900874 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100875
876 tstate = GET_TSTATE();
877 if (tstate == NULL)
878 return 0;
879
880 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700881}
882
Tim Peters19717fa2004-10-09 17:38:29 +0000883PyGILState_STATE
884PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 int current;
887 PyThreadState *tcur;
888 /* Note that we do not auto-init Python here - apart from
889 potential races with 2 threads auto-initializing, pep-311
890 spells out other issues. Embedders are expected to have
891 called Py_Initialize() and usually PyEval_InitThreads().
892 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600893 /* Py_Initialize() hasn't been called! */
894 assert(_PyRuntime.gilstate.autoInterpreterState);
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900895 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 if (tcur == NULL) {
Victor Stinner62ca1002013-12-13 01:46:43 +0100897 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
898 called from a new thread for the first time, we need the create the
899 GIL. */
900 PyEval_InitThreads();
901
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600903 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 if (tcur == NULL)
905 Py_FatalError("Couldn't create thread-state for new thread");
906 /* This is our thread state! We'll need to delete it in the
907 matching call to PyGILState_Release(). */
908 tcur->gilstate_counter = 0;
909 current = 0; /* new thread state is never current */
910 }
911 else
912 current = PyThreadState_IsCurrent(tcur);
913 if (current == 0)
914 PyEval_RestoreThread(tcur);
915 /* Update our counter in the thread-state - no need for locks:
916 - tcur will remain valid as we hold the GIL.
917 - the counter is safe as we are the only thread "allowed"
918 to modify this value
919 */
920 ++tcur->gilstate_counter;
921 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000922}
923
Tim Peters19717fa2004-10-09 17:38:29 +0000924void
925PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000926{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900927 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
928 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 if (tcur == NULL)
930 Py_FatalError("auto-releasing thread-state, "
931 "but no thread-state for this thread");
932 /* We must hold the GIL and have our thread state current */
933 /* XXX - remove the check - the assert should be fine,
934 but while this is very new (April 2003), the extra check
935 by release-only users can't hurt.
936 */
937 if (! PyThreadState_IsCurrent(tcur))
938 Py_FatalError("This thread state must be current when releasing");
939 assert(PyThreadState_IsCurrent(tcur));
940 --tcur->gilstate_counter;
941 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 /* If we're going to destroy this thread-state, we must
944 * clear it while the GIL is held, as destructors may run.
945 */
946 if (tcur->gilstate_counter == 0) {
947 /* can't have been locked when we created it */
948 assert(oldstate == PyGILState_UNLOCKED);
949 PyThreadState_Clear(tcur);
950 /* Delete the thread-state. Note this releases the GIL too!
951 * It's vital that the GIL be held here, to avoid shutdown
952 * races; see bugs 225673 and 1061968 (that nasty bug has a
953 * habit of coming back).
954 */
955 PyThreadState_DeleteCurrent();
956 }
957 /* Release the lock if necessary */
958 else if (oldstate == PyGILState_UNLOCKED)
959 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000960}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000961
Benjamin Peterson3bf01752012-04-13 18:06:36 -0400962
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000963#ifdef __cplusplus
964}
965#endif