blob: 99a579a069193aff98b65eec39dbbda9c667168f [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"
5
Victor Stinnerb02ef712016-01-22 14:09:55 +01006#define GET_TSTATE() \
7 ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current))
8#define SET_TSTATE(value) \
Benjamin Petersonca470632016-09-06 13:47:26 -07009 _Py_atomic_store_relaxed(&_PyThreadState_Current, (uintptr_t)(value))
Victor Stinnerb02ef712016-01-22 14:09:55 +010010#define GET_INTERP_STATE() \
11 (GET_TSTATE()->interp)
12
Victor Stinnerbfd316e2016-01-20 11:12:38 +010013
Tim Peters84705582004-10-10 02:47:33 +000014/* --------------------------------------------------------------------------
15CAUTION
16
Victor Stinner1a7425f2013-07-07 16:25:15 +020017Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
18number of these functions are advertised as safe to call when the GIL isn't
19held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
20debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
21to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000022-------------------------------------------------------------------------- */
23
Martin v. Löwisf0473d52001-07-18 16:17:16 +000024#ifdef HAVE_DLOPEN
25#ifdef HAVE_DLFCN_H
26#include <dlfcn.h>
27#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030028#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000029#define RTLD_LAZY 1
30#endif
31#endif
32
Benjamin Peterson43162b82012-04-13 11:58:27 -040033#ifdef __cplusplus
34extern "C" {
35#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000036
Victor Stinner8a1be612016-03-14 22:07:55 +010037int _PyGILState_check_enabled = 1;
38
Guido van Rossum1d5ad901999-06-18 14:22:24 +000039#ifdef WITH_THREAD
40#include "pythread.h"
41static PyThread_type_lock head_mutex = NULL; /* Protects interp->tstate_head */
Moshe Zadka9fb6af92000-08-04 21:27:47 +000042#define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock()))
Guido van Rossum1d5ad901999-06-18 14:22:24 +000043#define HEAD_LOCK() PyThread_acquire_lock(head_mutex, WAIT_LOCK)
44#define HEAD_UNLOCK() PyThread_release_lock(head_mutex)
Michael W. Hudson188d4362005-06-20 16:52:57 +000045
46/* The single PyInterpreterState used by this process'
47 GILState implementation
48*/
49static PyInterpreterState *autoInterpreterState = NULL;
Victor Stinner8a1be612016-03-14 22:07:55 +010050static int autoTLSkey = -1;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000051#else
52#define HEAD_INIT() /* Nothing */
53#define HEAD_LOCK() /* Nothing */
54#define HEAD_UNLOCK() /* Nothing */
55#endif
56
Guido van Rossum25ce5661997-08-02 03:10:38 +000057static PyInterpreterState *interp_head = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +000058
Jeffrey Yasskin39370832010-05-03 19:29:34 +000059/* Assuming the current thread holds the GIL, this is the
60 PyThreadState for the current thread. */
Victor Stinnerb02ef712016-01-22 14:09:55 +010061_Py_atomic_address _PyThreadState_Current = {0};
Guido van Rossum6297a7a2003-02-19 15:53:17 +000062PyThreadFrameGetter _PyThreadState_GetFrame = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +000063
Michael W. Hudsonce7da6c2005-09-30 08:20:24 +000064#ifdef WITH_THREAD
Michael W. Hudson188d4362005-06-20 16:52:57 +000065static void _PyGILState_NoteThreadState(PyThreadState* tstate);
Michael W. Hudsonce7da6c2005-09-30 08:20:24 +000066#endif
Michael W. Hudson188d4362005-06-20 16:52:57 +000067
Eric Snowe3774162017-05-22 19:46:40 -070068/* _next_interp_id is an auto-numbered sequence of small integers.
69 It gets initialized in _PyInterpreterState_Init(), which is called
70 in Py_Initialize(), and used in PyInterpreterState_New(). A negative
71 interpreter ID indicates an error occurred. The main interpreter
72 will always have an ID of 0. Overflow results in a RuntimeError.
73 If that becomes a problem later then we can adjust, e.g. by using
74 a Python int.
75
76 We initialize this to -1 so that the pre-Py_Initialize() value
77 results in an error. */
78static int64_t _next_interp_id = -1;
79
80void
81_PyInterpreterState_Init(void)
82{
83 _next_interp_id = 0;
84}
Guido van Rossuma027efa1997-05-05 20:56:21 +000085
86PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000087PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +000088{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000089 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +020090 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +000091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 if (interp != NULL) {
93 HEAD_INIT();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000094#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000095 if (head_mutex == NULL)
96 Py_FatalError("Can't initialize threads for interpreter");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000097#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 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;
104 interp->codec_search_path = NULL;
105 interp->codec_search_cache = NULL;
106 interp->codec_error_registry = NULL;
107 interp->codecs_initialized = 0;
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200108 interp->fscodec_initialized = 0;
Brett Cannonfd074152012-04-14 14:10:13 -0400109 interp->importlib = NULL;
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300110 interp->import_func = NULL;
Brett Cannon3cebf932016-09-05 15:33:46 -0700111 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000112#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300113#if HAVE_DECL_RTLD_NOW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000115#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000117#endif
118#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000119
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000120 HEAD_LOCK();
121 interp->next = interp_head;
122 interp_head = interp;
Eric Snowe3774162017-05-22 19:46:40 -0700123 if (_next_interp_id < 0) {
124 /* overflow or Py_Initialize() not called! */
125 PyErr_SetString(PyExc_RuntimeError,
126 "failed to get an interpreter ID");
127 interp = NULL;
128 } else {
129 interp->id = _next_interp_id;
130 _next_interp_id += 1;
131 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 HEAD_UNLOCK();
133 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000135 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000136}
137
138
139void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000140PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 PyThreadState *p;
143 HEAD_LOCK();
144 for (p = interp->tstate_head; p != NULL; p = p->next)
145 PyThreadState_Clear(p);
146 HEAD_UNLOCK();
147 Py_CLEAR(interp->codec_search_path);
148 Py_CLEAR(interp->codec_search_cache);
149 Py_CLEAR(interp->codec_error_registry);
150 Py_CLEAR(interp->modules);
151 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 Py_CLEAR(interp->sysdict);
153 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200154 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400155 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300156 Py_CLEAR(interp->import_func);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000157}
158
159
160static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000161zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 PyThreadState *p;
164 /* No need to lock the mutex here because this should only happen
165 when the threads are all really dead (XXX famous last words). */
166 while ((p = interp->tstate_head) != NULL) {
167 PyThreadState_Delete(p);
168 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000169}
170
171
172void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000173PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 PyInterpreterState **p;
176 zapthreads(interp);
177 HEAD_LOCK();
178 for (p = &interp_head; ; p = &(*p)->next) {
179 if (*p == NULL)
180 Py_FatalError(
181 "PyInterpreterState_Delete: invalid interp");
182 if (*p == interp)
183 break;
184 }
185 if (interp->tstate_head != NULL)
186 Py_FatalError("PyInterpreterState_Delete: remaining threads");
187 *p = interp->next;
188 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200189 PyMem_RawFree(interp);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100190#ifdef WITH_THREAD
191 if (interp_head == NULL && head_mutex != NULL) {
192 PyThread_free_lock(head_mutex);
193 head_mutex = NULL;
194 }
195#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +0000196}
197
198
Eric Snowe3774162017-05-22 19:46:40 -0700199int64_t
200PyInterpreterState_GetID(PyInterpreterState *interp)
201{
202 if (interp == NULL) {
203 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
204 return -1;
205 }
206 return interp->id;
207}
208
209
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000210/* Default implementation for _PyThreadState_GetFrame */
211static struct _frame *
212threadstate_getframe(PyThreadState *self)
213{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000215}
216
Victor Stinner45b9be52010-03-03 23:28:07 +0000217static PyThreadState *
218new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000219{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200220 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 if (_PyThreadState_GetFrame == NULL)
223 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 if (tstate != NULL) {
226 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 tstate->frame = NULL;
229 tstate->recursion_depth = 0;
230 tstate->overflowed = 0;
231 tstate->recursion_critical = 0;
232 tstate->tracing = 0;
233 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 tstate->gilstate_counter = 0;
235 tstate->async_exc = NULL;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000236#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 tstate->thread_id = PyThread_get_thread_ident();
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000238#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 tstate->thread_id = 0;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000240#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 tstate->curexc_type = NULL;
245 tstate->curexc_value = NULL;
246 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 tstate->exc_type = NULL;
249 tstate->exc_value = NULL;
250 tstate->exc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 tstate->c_profilefunc = NULL;
253 tstate->c_tracefunc = NULL;
254 tstate->c_profileobj = NULL;
255 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000256
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200257 tstate->trash_delete_nesting = 0;
258 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200259 tstate->on_delete = NULL;
260 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200261
Yury Selivanov75445082015-05-11 22:57:16 -0400262 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400263 tstate->in_coroutine_wrapper = 0;
Brett Cannon5c4de282016-09-07 11:16:41 -0700264 tstate->co_extra_user_count = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400265
Yury Selivanoveb636452016-09-08 22:01:51 -0700266 tstate->async_gen_firstiter = NULL;
267 tstate->async_gen_finalizer = NULL;
268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 if (init)
270 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200273 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200275 if (tstate->next)
276 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 interp->tstate_head = tstate;
278 HEAD_UNLOCK();
279 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000280
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000282}
283
Victor Stinner45b9be52010-03-03 23:28:07 +0000284PyThreadState *
285PyThreadState_New(PyInterpreterState *interp)
286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000288}
289
290PyThreadState *
291_PyThreadState_Prealloc(PyInterpreterState *interp)
292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000294}
295
296void
297_PyThreadState_Init(PyThreadState *tstate)
298{
299#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000301#endif
302}
303
Martin v. Löwis1a214512008-06-11 05:26:20 +0000304PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200305PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000306{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200307 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100308 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000310 if (module->m_slots) {
311 return NULL;
312 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 if (index == 0)
314 return NULL;
315 if (state->modules_by_index == NULL)
316 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200317 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 return NULL;
319 res = PyList_GET_ITEM(state->modules_by_index, index);
320 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000321}
322
323int
324_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
325{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000326 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300327 if (!def) {
328 assert(PyErr_Occurred());
329 return -1;
330 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000331 if (def->m_slots) {
332 PyErr_SetString(PyExc_SystemError,
333 "PyState_AddModule called on module with slots");
334 return -1;
335 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100336 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 if (!state->modules_by_index) {
338 state->modules_by_index = PyList_New(0);
339 if (!state->modules_by_index)
340 return -1;
341 }
342 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
343 if (PyList_Append(state->modules_by_index, Py_None) < 0)
344 return -1;
345 Py_INCREF(module);
346 return PyList_SetItem(state->modules_by_index,
347 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000348}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000349
Martin v. Löwis7800f752012-06-22 12:20:55 +0200350int
351PyState_AddModule(PyObject* module, struct PyModuleDef* def)
352{
353 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100354 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200355 if (!def) {
356 Py_FatalError("PyState_AddModule: Module Definition is NULL");
357 return -1;
358 }
359 index = def->m_base.m_index;
360 if (state->modules_by_index) {
361 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
362 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
363 Py_FatalError("PyState_AddModule: Module already added!");
364 return -1;
365 }
366 }
367 }
368 return _PyState_AddModule(module, def);
369}
370
371int
372PyState_RemoveModule(struct PyModuleDef* def)
373{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000374 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200375 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000376 if (def->m_slots) {
377 PyErr_SetString(PyExc_SystemError,
378 "PyState_RemoveModule called on module with slots");
379 return -1;
380 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100381 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200382 if (index == 0) {
383 Py_FatalError("PyState_RemoveModule: Module index invalid.");
384 return -1;
385 }
386 if (state->modules_by_index == NULL) {
387 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
388 return -1;
389 }
390 if (index > PyList_GET_SIZE(state->modules_by_index)) {
391 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
392 return -1;
393 }
394 return PyList_SetItem(state->modules_by_index, index, Py_None);
395}
396
Antoine Pitrou40322e62013-08-11 00:30:09 +0200397/* used by import.c:PyImport_Cleanup */
398void
399_PyState_ClearModules(void)
400{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100401 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200402 if (state->modules_by_index) {
403 Py_ssize_t i;
404 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
405 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
406 if (PyModule_Check(m)) {
407 /* cleanup the saved copy of module dicts */
408 PyModuleDef *md = PyModule_GetDef(m);
409 if (md)
410 Py_CLEAR(md->m_base.m_copy);
411 }
412 }
413 /* Setting modules_by_index to NULL could be dangerous, so we
414 clear the list instead. */
415 if (PyList_SetSlice(state->modules_by_index,
416 0, PyList_GET_SIZE(state->modules_by_index),
417 NULL))
418 PyErr_WriteUnraisable(state->modules_by_index);
419 }
420}
421
Guido van Rossuma027efa1997-05-05 20:56:21 +0000422void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000423PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (Py_VerboseFlag && tstate->frame != NULL)
426 fprintf(stderr,
427 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 Py_CLEAR(tstate->dict);
432 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 Py_CLEAR(tstate->curexc_type);
435 Py_CLEAR(tstate->curexc_value);
436 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 Py_CLEAR(tstate->exc_type);
439 Py_CLEAR(tstate->exc_value);
440 Py_CLEAR(tstate->exc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 tstate->c_profilefunc = NULL;
443 tstate->c_tracefunc = NULL;
444 Py_CLEAR(tstate->c_profileobj);
445 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400446
447 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700448 Py_CLEAR(tstate->async_gen_firstiter);
449 Py_CLEAR(tstate->async_gen_finalizer);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000450}
451
452
Guido van Rossum29757862001-01-23 01:46:06 +0000453/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
454static void
455tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 if (tstate == NULL)
459 Py_FatalError("PyThreadState_Delete: NULL tstate");
460 interp = tstate->interp;
461 if (interp == NULL)
462 Py_FatalError("PyThreadState_Delete: NULL interp");
463 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200464 if (tstate->prev)
465 tstate->prev->next = tstate->next;
466 else
467 interp->tstate_head = tstate->next;
468 if (tstate->next)
469 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200471 if (tstate->on_delete != NULL) {
472 tstate->on_delete(tstate->on_delete_data);
473 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200474 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000475}
476
477
Guido van Rossum29757862001-01-23 01:46:06 +0000478void
479PyThreadState_Delete(PyThreadState *tstate)
480{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100481 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 Py_FatalError("PyThreadState_Delete: tstate is still current");
Tim Petersf4e69282006-02-27 17:15:31 +0000483#ifdef WITH_THREAD
Antoine Pitrou079ce542010-09-08 12:37:10 +0000484 if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 PyThread_delete_key_value(autoTLSkey);
Tim Petersf4e69282006-02-27 17:15:31 +0000486#endif /* WITH_THREAD */
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200487 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000488}
489
490
491#ifdef WITH_THREAD
492void
493PyThreadState_DeleteCurrent()
494{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100495 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 if (tstate == NULL)
497 Py_FatalError(
498 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100499 tstate_delete_common(tstate);
Antoine Pitrou079ce542010-09-08 12:37:10 +0000500 if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 PyThread_delete_key_value(autoTLSkey);
Victor Stinner8a1be612016-03-14 22:07:55 +0100502 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000504}
505#endif /* WITH_THREAD */
506
507
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200508/*
509 * Delete all thread states except the one passed as argument.
510 * Note that, if there is a current thread state, it *must* be the one
511 * passed as argument. Also, this won't touch any other interpreters
512 * than the current one, since we don't know which thread state should
513 * be kept in those other interpreteres.
514 */
515void
516_PyThreadState_DeleteExcept(PyThreadState *tstate)
517{
518 PyInterpreterState *interp = tstate->interp;
519 PyThreadState *p, *next, *garbage;
520 HEAD_LOCK();
521 /* Remove all thread states, except tstate, from the linked list of
522 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200523 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200524 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200525 if (garbage == tstate)
526 garbage = tstate->next;
527 if (tstate->prev)
528 tstate->prev->next = tstate->next;
529 if (tstate->next)
530 tstate->next->prev = tstate->prev;
531 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200532 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200533 HEAD_UNLOCK();
534 /* Clear and deallocate all stale thread states. Even if this
535 executes Python code, we should be safe since it executes
536 in the current thread, not one of the stale threads. */
537 for (p = garbage; p; p = next) {
538 next = p->next;
539 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200540 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200541 }
542}
543
544
Guido van Rossuma027efa1997-05-05 20:56:21 +0000545PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100546_PyThreadState_UncheckedGet(void)
547{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100548 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100549}
550
551
552PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000553PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000554{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100555 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 if (tstate == NULL)
557 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000560}
561
562
563PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000564PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000565{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100566 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000567
Victor Stinnerb02ef712016-01-22 14:09:55 +0100568 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 /* It should not be possible for more than one thread state
570 to be used for a thread. Check this the best we can in debug
571 builds.
572 */
Martin v. Löwis9e296252003-05-01 05:25:29 +0000573#if defined(Py_DEBUG) && defined(WITH_THREAD)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 if (newts) {
575 /* This can be called from PyEval_RestoreThread(). Similar
576 to it, we need to ensure errno doesn't change.
577 */
578 int err = errno;
579 PyThreadState *check = PyGILState_GetThisThreadState();
580 if (check && check->interp == newts->interp && check != newts)
581 Py_FatalError("Invalid thread state for this thread");
582 errno = err;
583 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000584#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000586}
Guido van Rossumede04391998-04-10 20:18:25 +0000587
588/* An extension mechanism to store arbitrary additional per-thread state.
589 PyThreadState_GetDict() returns a dictionary that can be used to hold such
590 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000591 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
592 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000593
594PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000595PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000596{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100597 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 if (tstate == NULL)
599 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 if (tstate->dict == NULL) {
602 PyObject *d;
603 tstate->dict = d = PyDict_New();
604 if (d == NULL)
605 PyErr_Clear();
606 }
607 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000608}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000609
610
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000611/* Asynchronously raise an exception in a thread.
612 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000613 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000614 to call this, or use ctypes. Must be called with the GIL held.
615 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
616 match any known thread id). Can be called with exc=NULL to clear an
617 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000618
619int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200620PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
621{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100622 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 /* Although the GIL is held, a few C API functions can be called
626 * without the GIL held, and in particular some that create and
627 * destroy thread and interpreter states. Those can mutate the
628 * list of thread states we're traversing, so to prevent that we lock
629 * head_mutex for the duration.
630 */
631 HEAD_LOCK();
632 for (p = interp->tstate_head; p != NULL; p = p->next) {
633 if (p->thread_id == id) {
634 /* Tricky: we need to decref the current value
635 * (if any) in p->async_exc, but that can in turn
636 * allow arbitrary Python code to run, including
637 * perhaps calls to this function. To prevent
638 * deadlock, we need to release head_mutex before
639 * the decref.
640 */
641 PyObject *old_exc = p->async_exc;
642 Py_XINCREF(exc);
643 p->async_exc = exc;
644 HEAD_UNLOCK();
645 Py_XDECREF(old_exc);
646 _PyEval_SignalAsyncExc();
647 return 1;
648 }
649 }
650 HEAD_UNLOCK();
651 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000652}
653
654
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000655/* Routines for advanced debuggers, requested by David Beazley.
656 Don't use unless you know what you are doing! */
657
658PyInterpreterState *
659PyInterpreterState_Head(void)
660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 return interp_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000662}
663
664PyInterpreterState *
665PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000667}
668
669PyThreadState *
670PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000672}
673
674PyThreadState *
675PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000677}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000678
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000679/* The implementation of sys._current_frames(). This is intended to be
680 called with the GIL held, as it will be when called via
681 sys._current_frames(). It's possible it would work fine even without
682 the GIL held, but haven't thought enough about that.
683*/
684PyObject *
685_PyThread_CurrentFrames(void)
686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 PyObject *result;
688 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000689
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 result = PyDict_New();
691 if (result == NULL)
692 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 /* for i in all interpreters:
695 * for t in all of i's thread states:
696 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200697 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000698 * need to grab head_mutex for the duration.
699 */
700 HEAD_LOCK();
701 for (i = interp_head; i != NULL; i = i->next) {
702 PyThreadState *t;
703 for (t = i->tstate_head; t != NULL; t = t->next) {
704 PyObject *id;
705 int stat;
706 struct _frame *frame = t->frame;
707 if (frame == NULL)
708 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200709 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 if (id == NULL)
711 goto Fail;
712 stat = PyDict_SetItem(result, id, (PyObject *)frame);
713 Py_DECREF(id);
714 if (stat < 0)
715 goto Fail;
716 }
717 }
718 HEAD_UNLOCK();
719 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000720
721 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 HEAD_UNLOCK();
723 Py_DECREF(result);
724 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000725}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000726
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000727/* Python "auto thread state" API. */
728#ifdef WITH_THREAD
729
730/* Keep this as a static, as it is not reliable! It can only
731 ever be compared to the state for the *current* thread.
732 * If not equal, then it doesn't matter that the actual
733 value may change immediately after comparison, as it can't
734 possibly change to the current thread's state.
735 * If equal, then the current thread holds the lock, so the value can't
736 change until we yield the lock.
737*/
738static int
739PyThreadState_IsCurrent(PyThreadState *tstate)
740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 /* Must be the tstate for this thread */
742 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100743 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000744}
745
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000746/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000747 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000748*/
Tim Peters19717fa2004-10-09 17:38:29 +0000749void
750_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 assert(i && t); /* must init with valid states */
753 autoTLSkey = PyThread_create_key();
Kristján Valur Jónsson2fea9b92010-09-20 02:11:49 +0000754 if (autoTLSkey == -1)
755 Py_FatalError("Could not allocate TLS entry");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 autoInterpreterState = i;
757 assert(PyThread_get_key_value(autoTLSkey) == NULL);
758 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000759
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000761}
762
Victor Stinner861d9ab2016-03-16 22:45:24 +0100763PyInterpreterState *
764_PyGILState_GetInterpreterStateUnsafe(void)
765{
766 return autoInterpreterState;
767}
768
Tim Peters19717fa2004-10-09 17:38:29 +0000769void
770_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 PyThread_delete_key(autoTLSkey);
Victor Stinner8a1be612016-03-14 22:07:55 +0100773 autoTLSkey = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000775}
776
Charles-François Natalia233df82011-11-22 19:49:51 +0100777/* Reset the TLS key - called by PyOS_AfterFork().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200778 * This should not be necessary, but some - buggy - pthread implementations
Charles-François Natalia233df82011-11-22 19:49:51 +0100779 * don't reset TLS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200780 */
781void
782_PyGILState_Reinit(void)
783{
Jason Friedf82c9512017-05-22 16:58:55 -0700784#ifdef WITH_THREAD
785 head_mutex = NULL;
786 HEAD_INIT();
787#endif
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200788 PyThreadState *tstate = PyGILState_GetThisThreadState();
789 PyThread_delete_key(autoTLSkey);
790 if ((autoTLSkey = PyThread_create_key()) == -1)
791 Py_FatalError("Could not allocate TLS entry");
792
Charles-François Natalia233df82011-11-22 19:49:51 +0100793 /* If the thread had an associated auto thread state, reassociate it with
794 * the new key. */
795 if (tstate && PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200796 Py_FatalError("Couldn't create autoTLSkey mapping");
797}
798
Michael W. Hudson188d4362005-06-20 16:52:57 +0000799/* When a thread state is created for a thread by some mechanism other than
800 PyGILState_Ensure, it's important that the GILState machinery knows about
801 it so it doesn't try to create another thread state for the thread (this is
802 a better fix for SF bug #1010677 than the first one attempted).
803*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000804static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000805_PyGILState_NoteThreadState(PyThreadState* tstate)
806{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000807 /* If autoTLSkey isn't initialized, this must be the very first
808 threadstate created in Py_Initialize(). Don't do anything for now
809 (we'll be back here when _PyGILState_Init is called). */
810 if (!autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 /* Stick the thread state for this thread in thread local storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 The only situation where you can legitimately have more than one
816 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100817 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000818
Victor Stinner590cebe2013-12-13 11:08:56 +0100819 You shouldn't really be using the PyGILState_ APIs anyway (see issues
820 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000821
Victor Stinner590cebe2013-12-13 11:08:56 +0100822 The first thread state created for that given OS level thread will
823 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 */
Victor Stinner590cebe2013-12-13 11:08:56 +0100825 if (PyThread_get_key_value(autoTLSkey) == NULL) {
826 if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
827 Py_FatalError("Couldn't create autoTLSkey mapping");
828 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 /* PyGILState_Release must not try to delete this thread state. */
831 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000832}
833
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000834/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000835PyThreadState *
836PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000837{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000838 if (autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 return NULL;
840 return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000841}
842
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700843int
844PyGILState_Check(void)
845{
Victor Stinner8a1be612016-03-14 22:07:55 +0100846 PyThreadState *tstate;
847
848 if (!_PyGILState_check_enabled)
849 return 1;
850
851 if (autoTLSkey == -1)
852 return 1;
853
854 tstate = GET_TSTATE();
855 if (tstate == NULL)
856 return 0;
857
858 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700859}
860
Tim Peters19717fa2004-10-09 17:38:29 +0000861PyGILState_STATE
862PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 int current;
865 PyThreadState *tcur;
866 /* Note that we do not auto-init Python here - apart from
867 potential races with 2 threads auto-initializing, pep-311
868 spells out other issues. Embedders are expected to have
869 called Py_Initialize() and usually PyEval_InitThreads().
870 */
871 assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */
872 tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey);
873 if (tcur == NULL) {
Victor Stinner62ca1002013-12-13 01:46:43 +0100874 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
875 called from a new thread for the first time, we need the create the
876 GIL. */
877 PyEval_InitThreads();
878
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 /* Create a new thread state for this thread */
880 tcur = PyThreadState_New(autoInterpreterState);
881 if (tcur == NULL)
882 Py_FatalError("Couldn't create thread-state for new thread");
883 /* This is our thread state! We'll need to delete it in the
884 matching call to PyGILState_Release(). */
885 tcur->gilstate_counter = 0;
886 current = 0; /* new thread state is never current */
887 }
888 else
889 current = PyThreadState_IsCurrent(tcur);
890 if (current == 0)
891 PyEval_RestoreThread(tcur);
892 /* Update our counter in the thread-state - no need for locks:
893 - tcur will remain valid as we hold the GIL.
894 - the counter is safe as we are the only thread "allowed"
895 to modify this value
896 */
897 ++tcur->gilstate_counter;
898 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000899}
900
Tim Peters19717fa2004-10-09 17:38:29 +0000901void
902PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
905 autoTLSkey);
906 if (tcur == NULL)
907 Py_FatalError("auto-releasing thread-state, "
908 "but no thread-state for this thread");
909 /* We must hold the GIL and have our thread state current */
910 /* XXX - remove the check - the assert should be fine,
911 but while this is very new (April 2003), the extra check
912 by release-only users can't hurt.
913 */
914 if (! PyThreadState_IsCurrent(tcur))
915 Py_FatalError("This thread state must be current when releasing");
916 assert(PyThreadState_IsCurrent(tcur));
917 --tcur->gilstate_counter;
918 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 /* If we're going to destroy this thread-state, we must
921 * clear it while the GIL is held, as destructors may run.
922 */
923 if (tcur->gilstate_counter == 0) {
924 /* can't have been locked when we created it */
925 assert(oldstate == PyGILState_UNLOCKED);
926 PyThreadState_Clear(tcur);
927 /* Delete the thread-state. Note this releases the GIL too!
928 * It's vital that the GIL be held here, to avoid shutdown
929 * races; see bugs 225673 and 1061968 (that nasty bug has a
930 * habit of coming back).
931 */
932 PyThreadState_DeleteCurrent();
933 }
934 /* Release the lock if necessary */
935 else if (oldstate == PyGILState_UNLOCKED)
936 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000937}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000938
Benjamin Peterson3bf01752012-04-13 18:06:36 -0400939#endif /* WITH_THREAD */
940
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000941#ifdef __cplusplus
942}
943#endif
944
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000945