blob: 0a4e63b29de9faa30db837237cdb56690512126d [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*/
Eric Snow6b4be192017-05-22 21:36:03 -070049/* TODO: Given interp_main, it may be possible to kill this ref */
Michael W. Hudson188d4362005-06-20 16:52:57 +000050static PyInterpreterState *autoInterpreterState = NULL;
Victor Stinner8a1be612016-03-14 22:07:55 +010051static int autoTLSkey = -1;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000052#else
53#define HEAD_INIT() /* Nothing */
54#define HEAD_LOCK() /* Nothing */
55#define HEAD_UNLOCK() /* Nothing */
56#endif
57
Guido van Rossum25ce5661997-08-02 03:10:38 +000058static PyInterpreterState *interp_head = NULL;
Eric Snow6b4be192017-05-22 21:36:03 -070059static PyInterpreterState *interp_main = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +000060
Jeffrey Yasskin39370832010-05-03 19:29:34 +000061/* Assuming the current thread holds the GIL, this is the
62 PyThreadState for the current thread. */
Victor Stinnerb02ef712016-01-22 14:09:55 +010063_Py_atomic_address _PyThreadState_Current = {0};
Guido van Rossum6297a7a2003-02-19 15:53:17 +000064PyThreadFrameGetter _PyThreadState_GetFrame = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +000065
Michael W. Hudsonce7da6c2005-09-30 08:20:24 +000066#ifdef WITH_THREAD
Michael W. Hudson188d4362005-06-20 16:52:57 +000067static void _PyGILState_NoteThreadState(PyThreadState* tstate);
Michael W. Hudsonce7da6c2005-09-30 08:20:24 +000068#endif
Michael W. Hudson188d4362005-06-20 16:52:57 +000069
Eric Snowe3774162017-05-22 19:46:40 -070070/* _next_interp_id is an auto-numbered sequence of small integers.
71 It gets initialized in _PyInterpreterState_Init(), which is called
72 in Py_Initialize(), and used in PyInterpreterState_New(). A negative
73 interpreter ID indicates an error occurred. The main interpreter
74 will always have an ID of 0. Overflow results in a RuntimeError.
75 If that becomes a problem later then we can adjust, e.g. by using
76 a Python int.
77
78 We initialize this to -1 so that the pre-Py_Initialize() value
79 results in an error. */
80static int64_t _next_interp_id = -1;
81
82void
83_PyInterpreterState_Init(void)
84{
85 _next_interp_id = 0;
86}
Guido van Rossuma027efa1997-05-05 20:56:21 +000087
88PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000089PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +000090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +020092 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +000093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 if (interp != NULL) {
95 HEAD_INIT();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000096#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 if (head_mutex == NULL)
98 Py_FatalError("Can't initialize threads for interpreter");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000099#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 interp->modules_by_index = NULL;
102 interp->sysdict = NULL;
103 interp->builtins = NULL;
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200104 interp->builtins_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 interp->tstate_head = NULL;
106 interp->codec_search_path = NULL;
107 interp->codec_search_cache = NULL;
108 interp->codec_error_registry = NULL;
109 interp->codecs_initialized = 0;
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200110 interp->fscodec_initialized = 0;
Brett Cannonfd074152012-04-14 14:10:13 -0400111 interp->importlib = NULL;
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300112 interp->import_func = NULL;
Brett Cannon3cebf932016-09-05 15:33:46 -0700113 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000114#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300115#if HAVE_DECL_RTLD_NOW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000117#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000119#endif
120#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000122 HEAD_LOCK();
123 interp->next = interp_head;
Eric Snow6b4be192017-05-22 21:36:03 -0700124 if (interp_main == NULL) {
125 interp_main = interp;
126 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000127 interp_head = interp;
Eric Snowe3774162017-05-22 19:46:40 -0700128 if (_next_interp_id < 0) {
129 /* overflow or Py_Initialize() not called! */
130 PyErr_SetString(PyExc_RuntimeError,
131 "failed to get an interpreter ID");
132 interp = NULL;
133 } else {
134 interp->id = _next_interp_id;
135 _next_interp_id += 1;
136 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 HEAD_UNLOCK();
138 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000141}
142
143
144void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000145PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000147 PyThreadState *p;
148 HEAD_LOCK();
149 for (p = interp->tstate_head; p != NULL; p = p->next)
150 PyThreadState_Clear(p);
151 HEAD_UNLOCK();
152 Py_CLEAR(interp->codec_search_path);
153 Py_CLEAR(interp->codec_search_cache);
154 Py_CLEAR(interp->codec_error_registry);
155 Py_CLEAR(interp->modules);
156 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000157 Py_CLEAR(interp->sysdict);
158 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200159 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400160 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300161 Py_CLEAR(interp->import_func);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000162}
163
164
165static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000166zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000167{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 PyThreadState *p;
169 /* No need to lock the mutex here because this should only happen
170 when the threads are all really dead (XXX famous last words). */
171 while ((p = interp->tstate_head) != NULL) {
172 PyThreadState_Delete(p);
173 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000174}
175
176
177void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000178PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 PyInterpreterState **p;
181 zapthreads(interp);
182 HEAD_LOCK();
183 for (p = &interp_head; ; p = &(*p)->next) {
184 if (*p == NULL)
185 Py_FatalError(
186 "PyInterpreterState_Delete: invalid interp");
187 if (*p == interp)
188 break;
189 }
190 if (interp->tstate_head != NULL)
191 Py_FatalError("PyInterpreterState_Delete: remaining threads");
192 *p = interp->next;
Eric Snow6b4be192017-05-22 21:36:03 -0700193 if (interp_main == interp) {
194 interp_main = NULL;
195 if (interp_head != NULL)
196 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
197 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200199 PyMem_RawFree(interp);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100200#ifdef WITH_THREAD
201 if (interp_head == NULL && head_mutex != NULL) {
202 PyThread_free_lock(head_mutex);
203 head_mutex = NULL;
204 }
205#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +0000206}
207
208
Eric Snowe3774162017-05-22 19:46:40 -0700209int64_t
210PyInterpreterState_GetID(PyInterpreterState *interp)
211{
212 if (interp == NULL) {
213 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
214 return -1;
215 }
216 return interp->id;
217}
218
219
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000220/* Default implementation for _PyThreadState_GetFrame */
221static struct _frame *
222threadstate_getframe(PyThreadState *self)
223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000225}
226
Victor Stinner45b9be52010-03-03 23:28:07 +0000227static PyThreadState *
228new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000229{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200230 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000232 if (_PyThreadState_GetFrame == NULL)
233 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (tstate != NULL) {
236 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 tstate->frame = NULL;
239 tstate->recursion_depth = 0;
240 tstate->overflowed = 0;
241 tstate->recursion_critical = 0;
242 tstate->tracing = 0;
243 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 tstate->gilstate_counter = 0;
245 tstate->async_exc = NULL;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000246#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 tstate->thread_id = PyThread_get_thread_ident();
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000248#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 tstate->thread_id = 0;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000250#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 tstate->curexc_type = NULL;
255 tstate->curexc_value = NULL;
256 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 tstate->exc_type = NULL;
259 tstate->exc_value = NULL;
260 tstate->exc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 tstate->c_profilefunc = NULL;
263 tstate->c_tracefunc = NULL;
264 tstate->c_profileobj = NULL;
265 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000266
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200267 tstate->trash_delete_nesting = 0;
268 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200269 tstate->on_delete = NULL;
270 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200271
Yury Selivanov75445082015-05-11 22:57:16 -0400272 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400273 tstate->in_coroutine_wrapper = 0;
Brett Cannon5c4de282016-09-07 11:16:41 -0700274 tstate->co_extra_user_count = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400275
Yury Selivanoveb636452016-09-08 22:01:51 -0700276 tstate->async_gen_firstiter = NULL;
277 tstate->async_gen_finalizer = NULL;
278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 if (init)
280 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200283 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200285 if (tstate->next)
286 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 interp->tstate_head = tstate;
288 HEAD_UNLOCK();
289 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000292}
293
Victor Stinner45b9be52010-03-03 23:28:07 +0000294PyThreadState *
295PyThreadState_New(PyInterpreterState *interp)
296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000298}
299
300PyThreadState *
301_PyThreadState_Prealloc(PyInterpreterState *interp)
302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000304}
305
306void
307_PyThreadState_Init(PyThreadState *tstate)
308{
309#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000311#endif
312}
313
Martin v. Löwis1a214512008-06-11 05:26:20 +0000314PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200315PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000316{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200317 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100318 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000320 if (module->m_slots) {
321 return NULL;
322 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 if (index == 0)
324 return NULL;
325 if (state->modules_by_index == NULL)
326 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200327 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 return NULL;
329 res = PyList_GET_ITEM(state->modules_by_index, index);
330 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000331}
332
333int
334_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
335{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000336 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300337 if (!def) {
338 assert(PyErr_Occurred());
339 return -1;
340 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000341 if (def->m_slots) {
342 PyErr_SetString(PyExc_SystemError,
343 "PyState_AddModule called on module with slots");
344 return -1;
345 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100346 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 if (!state->modules_by_index) {
348 state->modules_by_index = PyList_New(0);
349 if (!state->modules_by_index)
350 return -1;
351 }
352 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
353 if (PyList_Append(state->modules_by_index, Py_None) < 0)
354 return -1;
355 Py_INCREF(module);
356 return PyList_SetItem(state->modules_by_index,
357 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000358}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000359
Martin v. Löwis7800f752012-06-22 12:20:55 +0200360int
361PyState_AddModule(PyObject* module, struct PyModuleDef* def)
362{
363 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100364 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200365 if (!def) {
366 Py_FatalError("PyState_AddModule: Module Definition is NULL");
367 return -1;
368 }
369 index = def->m_base.m_index;
370 if (state->modules_by_index) {
371 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
372 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
373 Py_FatalError("PyState_AddModule: Module already added!");
374 return -1;
375 }
376 }
377 }
378 return _PyState_AddModule(module, def);
379}
380
381int
382PyState_RemoveModule(struct PyModuleDef* def)
383{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000384 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200385 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000386 if (def->m_slots) {
387 PyErr_SetString(PyExc_SystemError,
388 "PyState_RemoveModule called on module with slots");
389 return -1;
390 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100391 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200392 if (index == 0) {
393 Py_FatalError("PyState_RemoveModule: Module index invalid.");
394 return -1;
395 }
396 if (state->modules_by_index == NULL) {
397 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
398 return -1;
399 }
400 if (index > PyList_GET_SIZE(state->modules_by_index)) {
401 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
402 return -1;
403 }
404 return PyList_SetItem(state->modules_by_index, index, Py_None);
405}
406
Antoine Pitrou40322e62013-08-11 00:30:09 +0200407/* used by import.c:PyImport_Cleanup */
408void
409_PyState_ClearModules(void)
410{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100411 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200412 if (state->modules_by_index) {
413 Py_ssize_t i;
414 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
415 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
416 if (PyModule_Check(m)) {
417 /* cleanup the saved copy of module dicts */
418 PyModuleDef *md = PyModule_GetDef(m);
419 if (md)
420 Py_CLEAR(md->m_base.m_copy);
421 }
422 }
423 /* Setting modules_by_index to NULL could be dangerous, so we
424 clear the list instead. */
425 if (PyList_SetSlice(state->modules_by_index,
426 0, PyList_GET_SIZE(state->modules_by_index),
427 NULL))
428 PyErr_WriteUnraisable(state->modules_by_index);
429 }
430}
431
Guido van Rossuma027efa1997-05-05 20:56:21 +0000432void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000433PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 if (Py_VerboseFlag && tstate->frame != NULL)
436 fprintf(stderr,
437 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 Py_CLEAR(tstate->dict);
442 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 Py_CLEAR(tstate->curexc_type);
445 Py_CLEAR(tstate->curexc_value);
446 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 Py_CLEAR(tstate->exc_type);
449 Py_CLEAR(tstate->exc_value);
450 Py_CLEAR(tstate->exc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 tstate->c_profilefunc = NULL;
453 tstate->c_tracefunc = NULL;
454 Py_CLEAR(tstate->c_profileobj);
455 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400456
457 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700458 Py_CLEAR(tstate->async_gen_firstiter);
459 Py_CLEAR(tstate->async_gen_finalizer);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000460}
461
462
Guido van Rossum29757862001-01-23 01:46:06 +0000463/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
464static void
465tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000466{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 if (tstate == NULL)
469 Py_FatalError("PyThreadState_Delete: NULL tstate");
470 interp = tstate->interp;
471 if (interp == NULL)
472 Py_FatalError("PyThreadState_Delete: NULL interp");
473 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200474 if (tstate->prev)
475 tstate->prev->next = tstate->next;
476 else
477 interp->tstate_head = tstate->next;
478 if (tstate->next)
479 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200481 if (tstate->on_delete != NULL) {
482 tstate->on_delete(tstate->on_delete_data);
483 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200484 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000485}
486
487
Guido van Rossum29757862001-01-23 01:46:06 +0000488void
489PyThreadState_Delete(PyThreadState *tstate)
490{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100491 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 Py_FatalError("PyThreadState_Delete: tstate is still current");
Tim Petersf4e69282006-02-27 17:15:31 +0000493#ifdef WITH_THREAD
Antoine Pitrou079ce542010-09-08 12:37:10 +0000494 if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 PyThread_delete_key_value(autoTLSkey);
Tim Petersf4e69282006-02-27 17:15:31 +0000496#endif /* WITH_THREAD */
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200497 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000498}
499
500
501#ifdef WITH_THREAD
502void
503PyThreadState_DeleteCurrent()
504{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100505 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 if (tstate == NULL)
507 Py_FatalError(
508 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100509 tstate_delete_common(tstate);
Antoine Pitrou079ce542010-09-08 12:37:10 +0000510 if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 PyThread_delete_key_value(autoTLSkey);
Victor Stinner8a1be612016-03-14 22:07:55 +0100512 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000514}
515#endif /* WITH_THREAD */
516
517
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200518/*
519 * Delete all thread states except the one passed as argument.
520 * Note that, if there is a current thread state, it *must* be the one
521 * passed as argument. Also, this won't touch any other interpreters
522 * than the current one, since we don't know which thread state should
523 * be kept in those other interpreteres.
524 */
525void
526_PyThreadState_DeleteExcept(PyThreadState *tstate)
527{
528 PyInterpreterState *interp = tstate->interp;
529 PyThreadState *p, *next, *garbage;
530 HEAD_LOCK();
531 /* Remove all thread states, except tstate, from the linked list of
532 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200533 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200534 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200535 if (garbage == tstate)
536 garbage = tstate->next;
537 if (tstate->prev)
538 tstate->prev->next = tstate->next;
539 if (tstate->next)
540 tstate->next->prev = tstate->prev;
541 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200542 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200543 HEAD_UNLOCK();
544 /* Clear and deallocate all stale thread states. Even if this
545 executes Python code, we should be safe since it executes
546 in the current thread, not one of the stale threads. */
547 for (p = garbage; p; p = next) {
548 next = p->next;
549 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200550 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200551 }
552}
553
554
Guido van Rossuma027efa1997-05-05 20:56:21 +0000555PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100556_PyThreadState_UncheckedGet(void)
557{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100558 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100559}
560
561
562PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000563PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000564{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100565 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 if (tstate == NULL)
567 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000570}
571
572
573PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000574PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000575{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100576 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000577
Victor Stinnerb02ef712016-01-22 14:09:55 +0100578 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 /* It should not be possible for more than one thread state
580 to be used for a thread. Check this the best we can in debug
581 builds.
582 */
Martin v. Löwis9e296252003-05-01 05:25:29 +0000583#if defined(Py_DEBUG) && defined(WITH_THREAD)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 if (newts) {
585 /* This can be called from PyEval_RestoreThread(). Similar
586 to it, we need to ensure errno doesn't change.
587 */
588 int err = errno;
589 PyThreadState *check = PyGILState_GetThisThreadState();
590 if (check && check->interp == newts->interp && check != newts)
591 Py_FatalError("Invalid thread state for this thread");
592 errno = err;
593 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000594#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000596}
Guido van Rossumede04391998-04-10 20:18:25 +0000597
598/* An extension mechanism to store arbitrary additional per-thread state.
599 PyThreadState_GetDict() returns a dictionary that can be used to hold such
600 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000601 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
602 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000603
604PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000605PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000606{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100607 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 if (tstate == NULL)
609 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (tstate->dict == NULL) {
612 PyObject *d;
613 tstate->dict = d = PyDict_New();
614 if (d == NULL)
615 PyErr_Clear();
616 }
617 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000618}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000619
620
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000621/* Asynchronously raise an exception in a thread.
622 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000623 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000624 to call this, or use ctypes. Must be called with the GIL held.
625 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
626 match any known thread id). Can be called with exc=NULL to clear an
627 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000628
629int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200630PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
631{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100632 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 /* Although the GIL is held, a few C API functions can be called
636 * without the GIL held, and in particular some that create and
637 * destroy thread and interpreter states. Those can mutate the
638 * list of thread states we're traversing, so to prevent that we lock
639 * head_mutex for the duration.
640 */
641 HEAD_LOCK();
642 for (p = interp->tstate_head; p != NULL; p = p->next) {
643 if (p->thread_id == id) {
644 /* Tricky: we need to decref the current value
645 * (if any) in p->async_exc, but that can in turn
646 * allow arbitrary Python code to run, including
647 * perhaps calls to this function. To prevent
648 * deadlock, we need to release head_mutex before
649 * the decref.
650 */
651 PyObject *old_exc = p->async_exc;
652 Py_XINCREF(exc);
653 p->async_exc = exc;
654 HEAD_UNLOCK();
655 Py_XDECREF(old_exc);
656 _PyEval_SignalAsyncExc();
657 return 1;
658 }
659 }
660 HEAD_UNLOCK();
661 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000662}
663
664
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000665/* Routines for advanced debuggers, requested by David Beazley.
666 Don't use unless you know what you are doing! */
667
668PyInterpreterState *
669PyInterpreterState_Head(void)
670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 return interp_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000672}
673
674PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700675PyInterpreterState_Main(void)
676{
677 return interp_main;
678}
679
680PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000681PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000683}
684
685PyThreadState *
686PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000688}
689
690PyThreadState *
691PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000693}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000694
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000695/* The implementation of sys._current_frames(). This is intended to be
696 called with the GIL held, as it will be when called via
697 sys._current_frames(). It's possible it would work fine even without
698 the GIL held, but haven't thought enough about that.
699*/
700PyObject *
701_PyThread_CurrentFrames(void)
702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 PyObject *result;
704 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 result = PyDict_New();
707 if (result == NULL)
708 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 /* for i in all interpreters:
711 * for t in all of i's thread states:
712 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200713 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 * need to grab head_mutex for the duration.
715 */
716 HEAD_LOCK();
717 for (i = interp_head; i != NULL; i = i->next) {
718 PyThreadState *t;
719 for (t = i->tstate_head; t != NULL; t = t->next) {
720 PyObject *id;
721 int stat;
722 struct _frame *frame = t->frame;
723 if (frame == NULL)
724 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200725 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 if (id == NULL)
727 goto Fail;
728 stat = PyDict_SetItem(result, id, (PyObject *)frame);
729 Py_DECREF(id);
730 if (stat < 0)
731 goto Fail;
732 }
733 }
734 HEAD_UNLOCK();
735 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000736
737 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 HEAD_UNLOCK();
739 Py_DECREF(result);
740 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000741}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000742
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000743/* Python "auto thread state" API. */
744#ifdef WITH_THREAD
745
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 */
769 autoTLSkey = PyThread_create_key();
Kristján Valur Jónsson2fea9b92010-09-20 02:11:49 +0000770 if (autoTLSkey == -1)
771 Py_FatalError("Could not allocate TLS entry");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 autoInterpreterState = i;
773 assert(PyThread_get_key_value(autoTLSkey) == NULL);
774 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{
782 return autoInterpreterState;
783}
784
Tim Peters19717fa2004-10-09 17:38:29 +0000785void
786_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 PyThread_delete_key(autoTLSkey);
Victor Stinner8a1be612016-03-14 22:07:55 +0100789 autoTLSkey = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000791}
792
Charles-François Natalia233df82011-11-22 19:49:51 +0100793/* Reset the TLS key - called by PyOS_AfterFork().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200794 * This should not be necessary, but some - buggy - pthread implementations
Charles-François Natalia233df82011-11-22 19:49:51 +0100795 * don't reset TLS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200796 */
797void
798_PyGILState_Reinit(void)
799{
Jason Friedf82c9512017-05-22 16:58:55 -0700800#ifdef WITH_THREAD
801 head_mutex = NULL;
802 HEAD_INIT();
803#endif
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200804 PyThreadState *tstate = PyGILState_GetThisThreadState();
805 PyThread_delete_key(autoTLSkey);
806 if ((autoTLSkey = PyThread_create_key()) == -1)
807 Py_FatalError("Could not allocate TLS entry");
808
Charles-François Natalia233df82011-11-22 19:49:51 +0100809 /* If the thread had an associated auto thread state, reassociate it with
810 * the new key. */
811 if (tstate && PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200812 Py_FatalError("Couldn't create autoTLSkey mapping");
813}
814
Michael W. Hudson188d4362005-06-20 16:52:57 +0000815/* When a thread state is created for a thread by some mechanism other than
816 PyGILState_Ensure, it's important that the GILState machinery knows about
817 it so it doesn't try to create another thread state for the thread (this is
818 a better fix for SF bug #1010677 than the first one attempted).
819*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000820static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000821_PyGILState_NoteThreadState(PyThreadState* tstate)
822{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000823 /* If autoTLSkey isn't initialized, this must be the very first
824 threadstate created in Py_Initialize(). Don't do anything for now
825 (we'll be back here when _PyGILState_Init is called). */
826 if (!autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 /* Stick the thread state for this thread in thread local storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 The only situation where you can legitimately have more than one
832 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100833 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000834
Victor Stinner590cebe2013-12-13 11:08:56 +0100835 You shouldn't really be using the PyGILState_ APIs anyway (see issues
836 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000837
Victor Stinner590cebe2013-12-13 11:08:56 +0100838 The first thread state created for that given OS level thread will
839 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 */
Victor Stinner590cebe2013-12-13 11:08:56 +0100841 if (PyThread_get_key_value(autoTLSkey) == NULL) {
842 if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
843 Py_FatalError("Couldn't create autoTLSkey mapping");
844 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 /* PyGILState_Release must not try to delete this thread state. */
847 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000848}
849
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000850/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000851PyThreadState *
852PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000853{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000854 if (autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 return NULL;
856 return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000857}
858
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700859int
860PyGILState_Check(void)
861{
Victor Stinner8a1be612016-03-14 22:07:55 +0100862 PyThreadState *tstate;
863
864 if (!_PyGILState_check_enabled)
865 return 1;
866
867 if (autoTLSkey == -1)
868 return 1;
869
870 tstate = GET_TSTATE();
871 if (tstate == NULL)
872 return 0;
873
874 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700875}
876
Tim Peters19717fa2004-10-09 17:38:29 +0000877PyGILState_STATE
878PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 int current;
881 PyThreadState *tcur;
882 /* Note that we do not auto-init Python here - apart from
883 potential races with 2 threads auto-initializing, pep-311
884 spells out other issues. Embedders are expected to have
885 called Py_Initialize() and usually PyEval_InitThreads().
886 */
887 assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */
888 tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey);
889 if (tcur == NULL) {
Victor Stinner62ca1002013-12-13 01:46:43 +0100890 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
891 called from a new thread for the first time, we need the create the
892 GIL. */
893 PyEval_InitThreads();
894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 /* Create a new thread state for this thread */
896 tcur = PyThreadState_New(autoInterpreterState);
897 if (tcur == NULL)
898 Py_FatalError("Couldn't create thread-state for new thread");
899 /* This is our thread state! We'll need to delete it in the
900 matching call to PyGILState_Release(). */
901 tcur->gilstate_counter = 0;
902 current = 0; /* new thread state is never current */
903 }
904 else
905 current = PyThreadState_IsCurrent(tcur);
906 if (current == 0)
907 PyEval_RestoreThread(tcur);
908 /* Update our counter in the thread-state - no need for locks:
909 - tcur will remain valid as we hold the GIL.
910 - the counter is safe as we are the only thread "allowed"
911 to modify this value
912 */
913 ++tcur->gilstate_counter;
914 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000915}
916
Tim Peters19717fa2004-10-09 17:38:29 +0000917void
918PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
921 autoTLSkey);
922 if (tcur == NULL)
923 Py_FatalError("auto-releasing thread-state, "
924 "but no thread-state for this thread");
925 /* We must hold the GIL and have our thread state current */
926 /* XXX - remove the check - the assert should be fine,
927 but while this is very new (April 2003), the extra check
928 by release-only users can't hurt.
929 */
930 if (! PyThreadState_IsCurrent(tcur))
931 Py_FatalError("This thread state must be current when releasing");
932 assert(PyThreadState_IsCurrent(tcur));
933 --tcur->gilstate_counter;
934 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 /* If we're going to destroy this thread-state, we must
937 * clear it while the GIL is held, as destructors may run.
938 */
939 if (tcur->gilstate_counter == 0) {
940 /* can't have been locked when we created it */
941 assert(oldstate == PyGILState_UNLOCKED);
942 PyThreadState_Clear(tcur);
943 /* Delete the thread-state. Note this releases the GIL too!
944 * It's vital that the GIL be held here, to avoid shutdown
945 * races; see bugs 225673 and 1061968 (that nasty bug has a
946 * habit of coming back).
947 */
948 PyThreadState_DeleteCurrent();
949 }
950 /* Release the lock if necessary */
951 else if (oldstate == PyGILState_UNLOCKED)
952 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000953}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000954
Benjamin Peterson3bf01752012-04-13 18:06:36 -0400955#endif /* WITH_THREAD */
956
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000957#ifdef __cplusplus
958}
959#endif
960
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000961