blob: 08048428610dfddda046a322f3bbc1eb257a4f73 [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;
49 runtime->gilstate.autoTLSkey = -1;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000050
Eric Snow2ebc5ce2017-09-07 23:51:28 -060051 runtime->interpreters.mutex = PyThread_allocate_lock();
52 if (runtime->interpreters.mutex == NULL)
53 Py_FatalError("Can't initialize threads for interpreter");
54 runtime->interpreters.next_id = -1;
55}
Eric Snow05351c12017-09-05 21:43:08 -070056
Eric Snow2ebc5ce2017-09-07 23:51:28 -060057void
58_PyRuntimeState_Fini(_PyRuntimeState *runtime)
59{
60 if (runtime->interpreters.mutex != NULL) {
61 PyThread_free_lock(runtime->interpreters.mutex);
62 runtime->interpreters.mutex = NULL;
63 }
64}
65
66#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
67 WAIT_LOCK)
68#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -070069
Michael W. Hudson188d4362005-06-20 16:52:57 +000070static void _PyGILState_NoteThreadState(PyThreadState* tstate);
71
Eric Snowe3774162017-05-22 19:46:40 -070072void
Eric Snow2ebc5ce2017-09-07 23:51:28 -060073_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -070074{
Eric Snow2ebc5ce2017-09-07 23:51:28 -060075 runtime->interpreters.next_id = 0;
76 /* Since we only call _PyRuntimeState_Init() once per process
77 (see _PyRuntime_Initialize()), we make sure the mutex is
78 initialized here. */
79 if (runtime->interpreters.mutex == NULL) {
80 runtime->interpreters.mutex = PyThread_allocate_lock();
81 if (runtime->interpreters.mutex == NULL)
82 Py_FatalError("Can't initialize threads for interpreter");
83 }
Eric Snowe3774162017-05-22 19:46:40 -070084}
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) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 interp->modules_by_index = NULL;
94 interp->sysdict = NULL;
95 interp->builtins = NULL;
Serhiy Storchaka87a5c512014-02-10 18:21:34 +020096 interp->builtins_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 interp->tstate_head = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060098 interp->check_interval = 100;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060099 interp->num_threads = 0;
100 interp->pythread_stacksize = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 interp->codec_search_path = NULL;
102 interp->codec_search_cache = NULL;
103 interp->codec_error_registry = NULL;
104 interp->codecs_initialized = 0;
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200105 interp->fscodec_initialized = 0;
Brett Cannonfd074152012-04-14 14:10:13 -0400106 interp->importlib = NULL;
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300107 interp->import_func = NULL;
Brett Cannon3cebf932016-09-05 15:33:46 -0700108 interp->eval_frame = _PyEval_EvalFrameDefault;
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700109 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000110#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300111#if HAVE_DECL_RTLD_NOW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000113#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000115#endif
116#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200117#ifdef HAVE_FORK
118 interp->before_forkers = NULL;
119 interp->after_forkers_parent = NULL;
120 interp->after_forkers_child = NULL;
121#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000123 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600124 interp->next = _PyRuntime.interpreters.head;
125 if (_PyRuntime.interpreters.main == NULL) {
126 _PyRuntime.interpreters.main = interp;
Eric Snow6b4be192017-05-22 21:36:03 -0700127 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600128 _PyRuntime.interpreters.head = interp;
129 if (_PyRuntime.interpreters.next_id < 0) {
Eric Snowe3774162017-05-22 19:46:40 -0700130 /* overflow or Py_Initialize() not called! */
131 PyErr_SetString(PyExc_RuntimeError,
132 "failed to get an interpreter ID");
133 interp = NULL;
134 } else {
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600135 interp->id = _PyRuntime.interpreters.next_id;
136 _PyRuntime.interpreters.next_id += 1;
Eric Snowe3774162017-05-22 19:46:40 -0700137 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 HEAD_UNLOCK();
139 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000142}
143
144
145void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000146PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 PyThreadState *p;
149 HEAD_LOCK();
150 for (p = interp->tstate_head; p != NULL; p = p->next)
151 PyThreadState_Clear(p);
152 HEAD_UNLOCK();
153 Py_CLEAR(interp->codec_search_path);
154 Py_CLEAR(interp->codec_search_cache);
155 Py_CLEAR(interp->codec_error_registry);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 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);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200162#ifdef HAVE_FORK
163 Py_CLEAR(interp->before_forkers);
164 Py_CLEAR(interp->after_forkers_parent);
165 Py_CLEAR(interp->after_forkers_child);
166#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000167}
168
169
170static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000171zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000172{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 PyThreadState *p;
174 /* No need to lock the mutex here because this should only happen
175 when the threads are all really dead (XXX famous last words). */
176 while ((p = interp->tstate_head) != NULL) {
177 PyThreadState_Delete(p);
178 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000179}
180
181
182void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000183PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 PyInterpreterState **p;
186 zapthreads(interp);
187 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600188 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 if (*p == NULL)
190 Py_FatalError(
191 "PyInterpreterState_Delete: invalid interp");
192 if (*p == interp)
193 break;
194 }
195 if (interp->tstate_head != NULL)
196 Py_FatalError("PyInterpreterState_Delete: remaining threads");
197 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600198 if (_PyRuntime.interpreters.main == interp) {
199 _PyRuntime.interpreters.main = NULL;
200 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700201 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
202 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200204 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000205}
206
207
Eric Snowe3774162017-05-22 19:46:40 -0700208int64_t
209PyInterpreterState_GetID(PyInterpreterState *interp)
210{
211 if (interp == NULL) {
212 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
213 return -1;
214 }
215 return interp->id;
216}
217
218
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000219/* Default implementation for _PyThreadState_GetFrame */
220static struct _frame *
221threadstate_getframe(PyThreadState *self)
222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000224}
225
Victor Stinner45b9be52010-03-03 23:28:07 +0000226static PyThreadState *
227new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000228{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200229 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 if (_PyThreadState_GetFrame == NULL)
232 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (tstate != NULL) {
235 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 tstate->frame = NULL;
238 tstate->recursion_depth = 0;
239 tstate->overflowed = 0;
240 tstate->recursion_critical = 0;
241 tstate->tracing = 0;
242 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 tstate->gilstate_counter = 0;
244 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 tstate->curexc_type = NULL;
250 tstate->curexc_value = NULL;
251 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 tstate->exc_type = NULL;
254 tstate->exc_value = NULL;
255 tstate->exc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 tstate->c_profilefunc = NULL;
258 tstate->c_tracefunc = NULL;
259 tstate->c_profileobj = NULL;
260 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000261
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200262 tstate->trash_delete_nesting = 0;
263 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200264 tstate->on_delete = NULL;
265 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200266
Yury Selivanov75445082015-05-11 22:57:16 -0400267 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400268 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400269
Yury Selivanoveb636452016-09-08 22:01:51 -0700270 tstate->async_gen_firstiter = NULL;
271 tstate->async_gen_finalizer = NULL;
272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 if (init)
274 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200277 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200279 if (tstate->next)
280 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 interp->tstate_head = tstate;
282 HEAD_UNLOCK();
283 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000286}
287
Victor Stinner45b9be52010-03-03 23:28:07 +0000288PyThreadState *
289PyThreadState_New(PyInterpreterState *interp)
290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000292}
293
294PyThreadState *
295_PyThreadState_Prealloc(PyInterpreterState *interp)
296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000298}
299
300void
301_PyThreadState_Init(PyThreadState *tstate)
302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000304}
305
Martin v. Löwis1a214512008-06-11 05:26:20 +0000306PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200307PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000308{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200309 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100310 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000312 if (module->m_slots) {
313 return NULL;
314 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 if (index == 0)
316 return NULL;
317 if (state->modules_by_index == NULL)
318 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200319 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 return NULL;
321 res = PyList_GET_ITEM(state->modules_by_index, index);
322 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000323}
324
325int
326_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
327{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000328 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300329 if (!def) {
330 assert(PyErr_Occurred());
331 return -1;
332 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000333 if (def->m_slots) {
334 PyErr_SetString(PyExc_SystemError,
335 "PyState_AddModule called on module with slots");
336 return -1;
337 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100338 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 if (!state->modules_by_index) {
340 state->modules_by_index = PyList_New(0);
341 if (!state->modules_by_index)
342 return -1;
343 }
344 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
345 if (PyList_Append(state->modules_by_index, Py_None) < 0)
346 return -1;
347 Py_INCREF(module);
348 return PyList_SetItem(state->modules_by_index,
349 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000350}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000351
Martin v. Löwis7800f752012-06-22 12:20:55 +0200352int
353PyState_AddModule(PyObject* module, struct PyModuleDef* def)
354{
355 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100356 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200357 if (!def) {
358 Py_FatalError("PyState_AddModule: Module Definition is NULL");
359 return -1;
360 }
361 index = def->m_base.m_index;
362 if (state->modules_by_index) {
363 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
364 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
365 Py_FatalError("PyState_AddModule: Module already added!");
366 return -1;
367 }
368 }
369 }
370 return _PyState_AddModule(module, def);
371}
372
373int
374PyState_RemoveModule(struct PyModuleDef* def)
375{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000376 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200377 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000378 if (def->m_slots) {
379 PyErr_SetString(PyExc_SystemError,
380 "PyState_RemoveModule called on module with slots");
381 return -1;
382 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100383 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200384 if (index == 0) {
385 Py_FatalError("PyState_RemoveModule: Module index invalid.");
386 return -1;
387 }
388 if (state->modules_by_index == NULL) {
389 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
390 return -1;
391 }
392 if (index > PyList_GET_SIZE(state->modules_by_index)) {
393 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
394 return -1;
395 }
396 return PyList_SetItem(state->modules_by_index, index, Py_None);
397}
398
Antoine Pitrou40322e62013-08-11 00:30:09 +0200399/* used by import.c:PyImport_Cleanup */
400void
401_PyState_ClearModules(void)
402{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100403 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200404 if (state->modules_by_index) {
405 Py_ssize_t i;
406 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
407 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
408 if (PyModule_Check(m)) {
409 /* cleanup the saved copy of module dicts */
410 PyModuleDef *md = PyModule_GetDef(m);
411 if (md)
412 Py_CLEAR(md->m_base.m_copy);
413 }
414 }
415 /* Setting modules_by_index to NULL could be dangerous, so we
416 clear the list instead. */
417 if (PyList_SetSlice(state->modules_by_index,
418 0, PyList_GET_SIZE(state->modules_by_index),
419 NULL))
420 PyErr_WriteUnraisable(state->modules_by_index);
421 }
422}
423
Guido van Rossuma027efa1997-05-05 20:56:21 +0000424void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000425PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 if (Py_VerboseFlag && tstate->frame != NULL)
428 fprintf(stderr,
429 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 Py_CLEAR(tstate->dict);
434 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 Py_CLEAR(tstate->curexc_type);
437 Py_CLEAR(tstate->curexc_value);
438 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 Py_CLEAR(tstate->exc_type);
441 Py_CLEAR(tstate->exc_value);
442 Py_CLEAR(tstate->exc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 tstate->c_profilefunc = NULL;
445 tstate->c_tracefunc = NULL;
446 Py_CLEAR(tstate->c_profileobj);
447 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400448
449 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700450 Py_CLEAR(tstate->async_gen_firstiter);
451 Py_CLEAR(tstate->async_gen_finalizer);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000452}
453
454
Guido van Rossum29757862001-01-23 01:46:06 +0000455/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
456static void
457tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 if (tstate == NULL)
461 Py_FatalError("PyThreadState_Delete: NULL tstate");
462 interp = tstate->interp;
463 if (interp == NULL)
464 Py_FatalError("PyThreadState_Delete: NULL interp");
465 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200466 if (tstate->prev)
467 tstate->prev->next = tstate->next;
468 else
469 interp->tstate_head = tstate->next;
470 if (tstate->next)
471 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200473 if (tstate->on_delete != NULL) {
474 tstate->on_delete(tstate->on_delete_data);
475 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200476 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000477}
478
479
Guido van Rossum29757862001-01-23 01:46:06 +0000480void
481PyThreadState_Delete(PyThreadState *tstate)
482{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100483 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600485 if (_PyRuntime.gilstate.autoInterpreterState &&
486 PyThread_get_key_value(_PyRuntime.gilstate.autoTLSkey) == tstate)
487 {
488 PyThread_delete_key_value(_PyRuntime.gilstate.autoTLSkey);
489 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200490 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000491}
492
493
Guido van Rossum29757862001-01-23 01:46:06 +0000494void
495PyThreadState_DeleteCurrent()
496{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100497 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 if (tstate == NULL)
499 Py_FatalError(
500 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100501 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600502 if (_PyRuntime.gilstate.autoInterpreterState &&
503 PyThread_get_key_value(_PyRuntime.gilstate.autoTLSkey) == tstate)
504 {
505 PyThread_delete_key_value(_PyRuntime.gilstate.autoTLSkey);
506 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100507 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000509}
Guido van Rossum29757862001-01-23 01:46:06 +0000510
511
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200512/*
513 * Delete all thread states except the one passed as argument.
514 * Note that, if there is a current thread state, it *must* be the one
515 * passed as argument. Also, this won't touch any other interpreters
516 * than the current one, since we don't know which thread state should
517 * be kept in those other interpreteres.
518 */
519void
520_PyThreadState_DeleteExcept(PyThreadState *tstate)
521{
522 PyInterpreterState *interp = tstate->interp;
523 PyThreadState *p, *next, *garbage;
524 HEAD_LOCK();
525 /* Remove all thread states, except tstate, from the linked list of
526 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200527 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200528 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200529 if (garbage == tstate)
530 garbage = tstate->next;
531 if (tstate->prev)
532 tstate->prev->next = tstate->next;
533 if (tstate->next)
534 tstate->next->prev = tstate->prev;
535 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200536 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200537 HEAD_UNLOCK();
538 /* Clear and deallocate all stale thread states. Even if this
539 executes Python code, we should be safe since it executes
540 in the current thread, not one of the stale threads. */
541 for (p = garbage; p; p = next) {
542 next = p->next;
543 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200544 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200545 }
546}
547
548
Guido van Rossuma027efa1997-05-05 20:56:21 +0000549PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100550_PyThreadState_UncheckedGet(void)
551{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100552 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100553}
554
555
556PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000557PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000558{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100559 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 if (tstate == NULL)
561 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000564}
565
566
567PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000568PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000569{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100570 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000571
Victor Stinnerb02ef712016-01-22 14:09:55 +0100572 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 /* It should not be possible for more than one thread state
574 to be used for a thread. Check this the best we can in debug
575 builds.
576 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200577#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 if (newts) {
579 /* This can be called from PyEval_RestoreThread(). Similar
580 to it, we need to ensure errno doesn't change.
581 */
582 int err = errno;
583 PyThreadState *check = PyGILState_GetThisThreadState();
584 if (check && check->interp == newts->interp && check != newts)
585 Py_FatalError("Invalid thread state for this thread");
586 errno = err;
587 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000588#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000590}
Guido van Rossumede04391998-04-10 20:18:25 +0000591
592/* An extension mechanism to store arbitrary additional per-thread state.
593 PyThreadState_GetDict() returns a dictionary that can be used to hold such
594 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000595 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
596 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000597
598PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000599PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000600{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100601 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if (tstate == NULL)
603 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (tstate->dict == NULL) {
606 PyObject *d;
607 tstate->dict = d = PyDict_New();
608 if (d == NULL)
609 PyErr_Clear();
610 }
611 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000612}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000613
614
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000615/* Asynchronously raise an exception in a thread.
616 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000617 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000618 to call this, or use ctypes. Must be called with the GIL held.
619 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
620 match any known thread id). Can be called with exc=NULL to clear an
621 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000622
623int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200624PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
625{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100626 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 /* Although the GIL is held, a few C API functions can be called
630 * without the GIL held, and in particular some that create and
631 * destroy thread and interpreter states. Those can mutate the
632 * list of thread states we're traversing, so to prevent that we lock
633 * head_mutex for the duration.
634 */
635 HEAD_LOCK();
636 for (p = interp->tstate_head; p != NULL; p = p->next) {
637 if (p->thread_id == id) {
638 /* Tricky: we need to decref the current value
639 * (if any) in p->async_exc, but that can in turn
640 * allow arbitrary Python code to run, including
641 * perhaps calls to this function. To prevent
642 * deadlock, we need to release head_mutex before
643 * the decref.
644 */
645 PyObject *old_exc = p->async_exc;
646 Py_XINCREF(exc);
647 p->async_exc = exc;
648 HEAD_UNLOCK();
649 Py_XDECREF(old_exc);
650 _PyEval_SignalAsyncExc();
651 return 1;
652 }
653 }
654 HEAD_UNLOCK();
655 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000656}
657
658
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000659/* Routines for advanced debuggers, requested by David Beazley.
660 Don't use unless you know what you are doing! */
661
662PyInterpreterState *
663PyInterpreterState_Head(void)
664{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600665 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000666}
667
668PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700669PyInterpreterState_Main(void)
670{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600671 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700672}
673
674PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000675PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000677}
678
679PyThreadState *
680PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000682}
683
684PyThreadState *
685PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000687}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000688
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000689/* The implementation of sys._current_frames(). This is intended to be
690 called with the GIL held, as it will be when called via
691 sys._current_frames(). It's possible it would work fine even without
692 the GIL held, but haven't thought enough about that.
693*/
694PyObject *
695_PyThread_CurrentFrames(void)
696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 PyObject *result;
698 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 result = PyDict_New();
701 if (result == NULL)
702 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 /* for i in all interpreters:
705 * for t in all of i's thread states:
706 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200707 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 * need to grab head_mutex for the duration.
709 */
710 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600711 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 PyThreadState *t;
713 for (t = i->tstate_head; t != NULL; t = t->next) {
714 PyObject *id;
715 int stat;
716 struct _frame *frame = t->frame;
717 if (frame == NULL)
718 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200719 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 if (id == NULL)
721 goto Fail;
722 stat = PyDict_SetItem(result, id, (PyObject *)frame);
723 Py_DECREF(id);
724 if (stat < 0)
725 goto Fail;
726 }
727 }
728 HEAD_UNLOCK();
729 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000730
731 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 HEAD_UNLOCK();
733 Py_DECREF(result);
734 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000735}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000736
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000737/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000738
739/* Keep this as a static, as it is not reliable! It can only
740 ever be compared to the state for the *current* thread.
741 * If not equal, then it doesn't matter that the actual
742 value may change immediately after comparison, as it can't
743 possibly change to the current thread's state.
744 * If equal, then the current thread holds the lock, so the value can't
745 change until we yield the lock.
746*/
747static int
748PyThreadState_IsCurrent(PyThreadState *tstate)
749{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 /* Must be the tstate for this thread */
751 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100752 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000753}
754
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000755/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000756 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000757*/
Tim Peters19717fa2004-10-09 17:38:29 +0000758void
759_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 assert(i && t); /* must init with valid states */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600762 _PyRuntime.gilstate.autoTLSkey = PyThread_create_key();
763 if (_PyRuntime.gilstate.autoTLSkey == -1)
Kristján Valur Jónsson2fea9b92010-09-20 02:11:49 +0000764 Py_FatalError("Could not allocate TLS entry");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600765 _PyRuntime.gilstate.autoInterpreterState = i;
766 assert(PyThread_get_key_value(_PyRuntime.gilstate.autoTLSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000770}
771
Victor Stinner861d9ab2016-03-16 22:45:24 +0100772PyInterpreterState *
773_PyGILState_GetInterpreterStateUnsafe(void)
774{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600775 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100776}
777
Tim Peters19717fa2004-10-09 17:38:29 +0000778void
779_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000780{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600781 PyThread_delete_key(_PyRuntime.gilstate.autoTLSkey);
782 _PyRuntime.gilstate.autoTLSkey = -1;
783 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000784}
785
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200786/* Reset the TLS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200787 * This should not be necessary, but some - buggy - pthread implementations
Charles-François Natalia233df82011-11-22 19:49:51 +0100788 * don't reset TLS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200789 */
790void
791_PyGILState_Reinit(void)
792{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600793 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
794 if (_PyRuntime.interpreters.mutex == NULL)
795 Py_FatalError("Can't initialize threads for interpreter");
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200796 PyThreadState *tstate = PyGILState_GetThisThreadState();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600797 PyThread_delete_key(_PyRuntime.gilstate.autoTLSkey);
798 if ((_PyRuntime.gilstate.autoTLSkey = PyThread_create_key()) == -1)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200799 Py_FatalError("Could not allocate TLS entry");
800
Charles-François Natalia233df82011-11-22 19:49:51 +0100801 /* If the thread had an associated auto thread state, reassociate it with
802 * the new key. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600803 if (tstate && PyThread_set_key_value(_PyRuntime.gilstate.autoTLSkey,
804 (void *)tstate) < 0)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200805 Py_FatalError("Couldn't create autoTLSkey mapping");
806}
807
Michael W. Hudson188d4362005-06-20 16:52:57 +0000808/* When a thread state is created for a thread by some mechanism other than
809 PyGILState_Ensure, it's important that the GILState machinery knows about
810 it so it doesn't try to create another thread state for the thread (this is
811 a better fix for SF bug #1010677 than the first one attempted).
812*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000813static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000814_PyGILState_NoteThreadState(PyThreadState* tstate)
815{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000816 /* If autoTLSkey isn't initialized, this must be the very first
817 threadstate created in Py_Initialize(). Don't do anything for now
818 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600819 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 /* Stick the thread state for this thread in thread local storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 The only situation where you can legitimately have more than one
825 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100826 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000827
Victor Stinner590cebe2013-12-13 11:08:56 +0100828 You shouldn't really be using the PyGILState_ APIs anyway (see issues
829 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000830
Victor Stinner590cebe2013-12-13 11:08:56 +0100831 The first thread state created for that given OS level thread will
832 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600834 if (PyThread_get_key_value(_PyRuntime.gilstate.autoTLSkey) == NULL) {
835 if ((PyThread_set_key_value(_PyRuntime.gilstate.autoTLSkey,
836 (void *)tstate)
837 ) < 0)
838 {
Victor Stinner590cebe2013-12-13 11:08:56 +0100839 Py_FatalError("Couldn't create autoTLSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600840 }
Victor Stinner590cebe2013-12-13 11:08:56 +0100841 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000842
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 /* PyGILState_Release must not try to delete this thread state. */
844 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000845}
846
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000847/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000848PyThreadState *
849PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000850{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600851 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600853 return (PyThreadState *)PyThread_get_key_value(
854 _PyRuntime.gilstate.autoTLSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000855}
856
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700857int
858PyGILState_Check(void)
859{
Victor Stinner8a1be612016-03-14 22:07:55 +0100860 PyThreadState *tstate;
861
862 if (!_PyGILState_check_enabled)
863 return 1;
864
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600865 if (_PyRuntime.gilstate.autoTLSkey == -1)
Victor Stinner8a1be612016-03-14 22:07:55 +0100866 return 1;
867
868 tstate = GET_TSTATE();
869 if (tstate == NULL)
870 return 0;
871
872 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700873}
874
Tim Peters19717fa2004-10-09 17:38:29 +0000875PyGILState_STATE
876PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 int current;
879 PyThreadState *tcur;
880 /* Note that we do not auto-init Python here - apart from
881 potential races with 2 threads auto-initializing, pep-311
882 spells out other issues. Embedders are expected to have
883 called Py_Initialize() and usually PyEval_InitThreads().
884 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600885 /* Py_Initialize() hasn't been called! */
886 assert(_PyRuntime.gilstate.autoInterpreterState);
887 tcur = (PyThreadState *)PyThread_get_key_value(
888 _PyRuntime.gilstate.autoTLSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 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 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600896 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 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(
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600921 _PyRuntime.gilstate.autoTLSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 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
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000956#ifdef __cplusplus
957}
958#endif