blob: 53c1236145761dac4f573c6e8e2858ce19480ca5 [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) {
Eric Snow93c92f72017-09-13 23:46:04 -070093 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 interp->modules_by_index = NULL;
95 interp->sysdict = NULL;
96 interp->builtins = NULL;
Serhiy Storchaka87a5c512014-02-10 18:21:34 +020097 interp->builtins_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 interp->tstate_head = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060099 interp->check_interval = 100;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600100 interp->num_threads = 0;
101 interp->pythread_stacksize = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 interp->codec_search_path = NULL;
103 interp->codec_search_cache = NULL;
104 interp->codec_error_registry = NULL;
105 interp->codecs_initialized = 0;
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200106 interp->fscodec_initialized = 0;
Brett Cannonfd074152012-04-14 14:10:13 -0400107 interp->importlib = NULL;
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300108 interp->import_func = NULL;
Brett Cannon3cebf932016-09-05 15:33:46 -0700109 interp->eval_frame = _PyEval_EvalFrameDefault;
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700110 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000111#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300112#if HAVE_DECL_RTLD_NOW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000114#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000116#endif
117#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200118#ifdef HAVE_FORK
119 interp->before_forkers = NULL;
120 interp->after_forkers_parent = NULL;
121 interp->after_forkers_child = NULL;
122#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000124 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600125 interp->next = _PyRuntime.interpreters.head;
126 if (_PyRuntime.interpreters.main == NULL) {
127 _PyRuntime.interpreters.main = interp;
Eric Snow6b4be192017-05-22 21:36:03 -0700128 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600129 _PyRuntime.interpreters.head = interp;
130 if (_PyRuntime.interpreters.next_id < 0) {
Eric Snowe3774162017-05-22 19:46:40 -0700131 /* overflow or Py_Initialize() not called! */
132 PyErr_SetString(PyExc_RuntimeError,
133 "failed to get an interpreter ID");
134 interp = NULL;
135 } else {
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600136 interp->id = _PyRuntime.interpreters.next_id;
137 _PyRuntime.interpreters.next_id += 1;
Eric Snowe3774162017-05-22 19:46:40 -0700138 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 HEAD_UNLOCK();
140 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000142 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000143}
144
145
146void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000147PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 PyThreadState *p;
150 HEAD_LOCK();
151 for (p = interp->tstate_head; p != NULL; p = p->next)
152 PyThreadState_Clear(p);
153 HEAD_UNLOCK();
154 Py_CLEAR(interp->codec_search_path);
155 Py_CLEAR(interp->codec_search_cache);
156 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700157 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 Py_CLEAR(interp->sysdict);
160 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200161 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400162 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300163 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200164#ifdef HAVE_FORK
165 Py_CLEAR(interp->before_forkers);
166 Py_CLEAR(interp->after_forkers_parent);
167 Py_CLEAR(interp->after_forkers_child);
168#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000169}
170
171
172static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000173zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 PyThreadState *p;
176 /* No need to lock the mutex here because this should only happen
177 when the threads are all really dead (XXX famous last words). */
178 while ((p = interp->tstate_head) != NULL) {
179 PyThreadState_Delete(p);
180 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000181}
182
183
184void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000185PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 PyInterpreterState **p;
188 zapthreads(interp);
189 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600190 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 if (*p == NULL)
192 Py_FatalError(
193 "PyInterpreterState_Delete: invalid interp");
194 if (*p == interp)
195 break;
196 }
197 if (interp->tstate_head != NULL)
198 Py_FatalError("PyInterpreterState_Delete: remaining threads");
199 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600200 if (_PyRuntime.interpreters.main == interp) {
201 _PyRuntime.interpreters.main = NULL;
202 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700203 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
204 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200206 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000207}
208
209
Eric Snowe3774162017-05-22 19:46:40 -0700210int64_t
211PyInterpreterState_GetID(PyInterpreterState *interp)
212{
213 if (interp == NULL) {
214 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
215 return -1;
216 }
217 return interp->id;
218}
219
220
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000221/* Default implementation for _PyThreadState_GetFrame */
222static struct _frame *
223threadstate_getframe(PyThreadState *self)
224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000226}
227
Victor Stinner45b9be52010-03-03 23:28:07 +0000228static PyThreadState *
229new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000230{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200231 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 if (_PyThreadState_GetFrame == NULL)
234 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 if (tstate != NULL) {
237 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 tstate->frame = NULL;
240 tstate->recursion_depth = 0;
241 tstate->overflowed = 0;
242 tstate->recursion_critical = 0;
243 tstate->tracing = 0;
244 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 tstate->gilstate_counter = 0;
246 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 tstate->curexc_type = NULL;
252 tstate->curexc_value = NULL;
253 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 tstate->exc_type = NULL;
256 tstate->exc_value = NULL;
257 tstate->exc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 tstate->c_profilefunc = NULL;
260 tstate->c_tracefunc = NULL;
261 tstate->c_profileobj = NULL;
262 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000263
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200264 tstate->trash_delete_nesting = 0;
265 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200266 tstate->on_delete = NULL;
267 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200268
Yury Selivanov75445082015-05-11 22:57:16 -0400269 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400270 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400271
Yury Selivanoveb636452016-09-08 22:01:51 -0700272 tstate->async_gen_firstiter = NULL;
273 tstate->async_gen_finalizer = NULL;
274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 if (init)
276 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200279 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200281 if (tstate->next)
282 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 interp->tstate_head = tstate;
284 HEAD_UNLOCK();
285 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000288}
289
Victor Stinner45b9be52010-03-03 23:28:07 +0000290PyThreadState *
291PyThreadState_New(PyInterpreterState *interp)
292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000294}
295
296PyThreadState *
297_PyThreadState_Prealloc(PyInterpreterState *interp)
298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000300}
301
302void
303_PyThreadState_Init(PyThreadState *tstate)
304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000306}
307
Martin v. Löwis1a214512008-06-11 05:26:20 +0000308PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200309PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000310{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200311 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100312 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000314 if (module->m_slots) {
315 return NULL;
316 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 if (index == 0)
318 return NULL;
319 if (state->modules_by_index == NULL)
320 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200321 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 return NULL;
323 res = PyList_GET_ITEM(state->modules_by_index, index);
324 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000325}
326
327int
328_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
329{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000330 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300331 if (!def) {
332 assert(PyErr_Occurred());
333 return -1;
334 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000335 if (def->m_slots) {
336 PyErr_SetString(PyExc_SystemError,
337 "PyState_AddModule called on module with slots");
338 return -1;
339 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100340 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 if (!state->modules_by_index) {
342 state->modules_by_index = PyList_New(0);
343 if (!state->modules_by_index)
344 return -1;
345 }
346 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
347 if (PyList_Append(state->modules_by_index, Py_None) < 0)
348 return -1;
349 Py_INCREF(module);
350 return PyList_SetItem(state->modules_by_index,
351 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000352}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000353
Martin v. Löwis7800f752012-06-22 12:20:55 +0200354int
355PyState_AddModule(PyObject* module, struct PyModuleDef* def)
356{
357 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100358 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200359 if (!def) {
360 Py_FatalError("PyState_AddModule: Module Definition is NULL");
361 return -1;
362 }
363 index = def->m_base.m_index;
364 if (state->modules_by_index) {
365 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
366 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
367 Py_FatalError("PyState_AddModule: Module already added!");
368 return -1;
369 }
370 }
371 }
372 return _PyState_AddModule(module, def);
373}
374
375int
376PyState_RemoveModule(struct PyModuleDef* def)
377{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000378 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200379 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000380 if (def->m_slots) {
381 PyErr_SetString(PyExc_SystemError,
382 "PyState_RemoveModule called on module with slots");
383 return -1;
384 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100385 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200386 if (index == 0) {
387 Py_FatalError("PyState_RemoveModule: Module index invalid.");
388 return -1;
389 }
390 if (state->modules_by_index == NULL) {
391 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
392 return -1;
393 }
394 if (index > PyList_GET_SIZE(state->modules_by_index)) {
395 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
396 return -1;
397 }
398 return PyList_SetItem(state->modules_by_index, index, Py_None);
399}
400
Antoine Pitrou40322e62013-08-11 00:30:09 +0200401/* used by import.c:PyImport_Cleanup */
402void
403_PyState_ClearModules(void)
404{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100405 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200406 if (state->modules_by_index) {
407 Py_ssize_t i;
408 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
409 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
410 if (PyModule_Check(m)) {
411 /* cleanup the saved copy of module dicts */
412 PyModuleDef *md = PyModule_GetDef(m);
413 if (md)
414 Py_CLEAR(md->m_base.m_copy);
415 }
416 }
417 /* Setting modules_by_index to NULL could be dangerous, so we
418 clear the list instead. */
419 if (PyList_SetSlice(state->modules_by_index,
420 0, PyList_GET_SIZE(state->modules_by_index),
421 NULL))
422 PyErr_WriteUnraisable(state->modules_by_index);
423 }
424}
425
Guido van Rossuma027efa1997-05-05 20:56:21 +0000426void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000427PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 if (Py_VerboseFlag && tstate->frame != NULL)
430 fprintf(stderr,
431 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 Py_CLEAR(tstate->dict);
436 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 Py_CLEAR(tstate->curexc_type);
439 Py_CLEAR(tstate->curexc_value);
440 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 Py_CLEAR(tstate->exc_type);
443 Py_CLEAR(tstate->exc_value);
444 Py_CLEAR(tstate->exc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 tstate->c_profilefunc = NULL;
447 tstate->c_tracefunc = NULL;
448 Py_CLEAR(tstate->c_profileobj);
449 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400450
451 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700452 Py_CLEAR(tstate->async_gen_firstiter);
453 Py_CLEAR(tstate->async_gen_finalizer);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000454}
455
456
Guido van Rossum29757862001-01-23 01:46:06 +0000457/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
458static void
459tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 if (tstate == NULL)
463 Py_FatalError("PyThreadState_Delete: NULL tstate");
464 interp = tstate->interp;
465 if (interp == NULL)
466 Py_FatalError("PyThreadState_Delete: NULL interp");
467 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200468 if (tstate->prev)
469 tstate->prev->next = tstate->next;
470 else
471 interp->tstate_head = tstate->next;
472 if (tstate->next)
473 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200475 if (tstate->on_delete != NULL) {
476 tstate->on_delete(tstate->on_delete_data);
477 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200478 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000479}
480
481
Guido van Rossum29757862001-01-23 01:46:06 +0000482void
483PyThreadState_Delete(PyThreadState *tstate)
484{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100485 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600487 if (_PyRuntime.gilstate.autoInterpreterState &&
488 PyThread_get_key_value(_PyRuntime.gilstate.autoTLSkey) == tstate)
489 {
490 PyThread_delete_key_value(_PyRuntime.gilstate.autoTLSkey);
491 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200492 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000493}
494
495
Guido van Rossum29757862001-01-23 01:46:06 +0000496void
497PyThreadState_DeleteCurrent()
498{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100499 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 if (tstate == NULL)
501 Py_FatalError(
502 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100503 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600504 if (_PyRuntime.gilstate.autoInterpreterState &&
505 PyThread_get_key_value(_PyRuntime.gilstate.autoTLSkey) == tstate)
506 {
507 PyThread_delete_key_value(_PyRuntime.gilstate.autoTLSkey);
508 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100509 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000511}
Guido van Rossum29757862001-01-23 01:46:06 +0000512
513
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200514/*
515 * Delete all thread states except the one passed as argument.
516 * Note that, if there is a current thread state, it *must* be the one
517 * passed as argument. Also, this won't touch any other interpreters
518 * than the current one, since we don't know which thread state should
519 * be kept in those other interpreteres.
520 */
521void
522_PyThreadState_DeleteExcept(PyThreadState *tstate)
523{
524 PyInterpreterState *interp = tstate->interp;
525 PyThreadState *p, *next, *garbage;
526 HEAD_LOCK();
527 /* Remove all thread states, except tstate, from the linked list of
528 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200529 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200530 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200531 if (garbage == tstate)
532 garbage = tstate->next;
533 if (tstate->prev)
534 tstate->prev->next = tstate->next;
535 if (tstate->next)
536 tstate->next->prev = tstate->prev;
537 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200538 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200539 HEAD_UNLOCK();
540 /* Clear and deallocate all stale thread states. Even if this
541 executes Python code, we should be safe since it executes
542 in the current thread, not one of the stale threads. */
543 for (p = garbage; p; p = next) {
544 next = p->next;
545 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200546 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200547 }
548}
549
550
Guido van Rossuma027efa1997-05-05 20:56:21 +0000551PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100552_PyThreadState_UncheckedGet(void)
553{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100554 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100555}
556
557
558PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000559PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000560{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100561 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 if (tstate == NULL)
563 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000566}
567
568
569PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000570PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000571{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100572 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573
Victor Stinnerb02ef712016-01-22 14:09:55 +0100574 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 /* It should not be possible for more than one thread state
576 to be used for a thread. Check this the best we can in debug
577 builds.
578 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200579#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (newts) {
581 /* This can be called from PyEval_RestoreThread(). Similar
582 to it, we need to ensure errno doesn't change.
583 */
584 int err = errno;
585 PyThreadState *check = PyGILState_GetThisThreadState();
586 if (check && check->interp == newts->interp && check != newts)
587 Py_FatalError("Invalid thread state for this thread");
588 errno = err;
589 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000590#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000592}
Guido van Rossumede04391998-04-10 20:18:25 +0000593
594/* An extension mechanism to store arbitrary additional per-thread state.
595 PyThreadState_GetDict() returns a dictionary that can be used to hold such
596 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000597 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
598 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000599
600PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000601PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000602{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100603 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 if (tstate == NULL)
605 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 if (tstate->dict == NULL) {
608 PyObject *d;
609 tstate->dict = d = PyDict_New();
610 if (d == NULL)
611 PyErr_Clear();
612 }
613 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000614}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000615
616
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000617/* Asynchronously raise an exception in a thread.
618 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000619 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000620 to call this, or use ctypes. Must be called with the GIL held.
621 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
622 match any known thread id). Can be called with exc=NULL to clear an
623 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000624
625int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200626PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
627{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100628 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 /* Although the GIL is held, a few C API functions can be called
632 * without the GIL held, and in particular some that create and
633 * destroy thread and interpreter states. Those can mutate the
634 * list of thread states we're traversing, so to prevent that we lock
635 * head_mutex for the duration.
636 */
637 HEAD_LOCK();
638 for (p = interp->tstate_head; p != NULL; p = p->next) {
639 if (p->thread_id == id) {
640 /* Tricky: we need to decref the current value
641 * (if any) in p->async_exc, but that can in turn
642 * allow arbitrary Python code to run, including
643 * perhaps calls to this function. To prevent
644 * deadlock, we need to release head_mutex before
645 * the decref.
646 */
647 PyObject *old_exc = p->async_exc;
648 Py_XINCREF(exc);
649 p->async_exc = exc;
650 HEAD_UNLOCK();
651 Py_XDECREF(old_exc);
652 _PyEval_SignalAsyncExc();
653 return 1;
654 }
655 }
656 HEAD_UNLOCK();
657 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000658}
659
660
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000661/* Routines for advanced debuggers, requested by David Beazley.
662 Don't use unless you know what you are doing! */
663
664PyInterpreterState *
665PyInterpreterState_Head(void)
666{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600667 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000668}
669
670PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700671PyInterpreterState_Main(void)
672{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600673 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700674}
675
676PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000677PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000679}
680
681PyThreadState *
682PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000684}
685
686PyThreadState *
687PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000689}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000690
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000691/* The implementation of sys._current_frames(). This is intended to be
692 called with the GIL held, as it will be when called via
693 sys._current_frames(). It's possible it would work fine even without
694 the GIL held, but haven't thought enough about that.
695*/
696PyObject *
697_PyThread_CurrentFrames(void)
698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 PyObject *result;
700 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 result = PyDict_New();
703 if (result == NULL)
704 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 /* for i in all interpreters:
707 * for t in all of i's thread states:
708 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200709 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 * need to grab head_mutex for the duration.
711 */
712 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600713 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyThreadState *t;
715 for (t = i->tstate_head; t != NULL; t = t->next) {
716 PyObject *id;
717 int stat;
718 struct _frame *frame = t->frame;
719 if (frame == NULL)
720 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200721 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 if (id == NULL)
723 goto Fail;
724 stat = PyDict_SetItem(result, id, (PyObject *)frame);
725 Py_DECREF(id);
726 if (stat < 0)
727 goto Fail;
728 }
729 }
730 HEAD_UNLOCK();
731 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000732
733 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 HEAD_UNLOCK();
735 Py_DECREF(result);
736 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000737}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000738
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000739/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000740
741/* Keep this as a static, as it is not reliable! It can only
742 ever be compared to the state for the *current* thread.
743 * If not equal, then it doesn't matter that the actual
744 value may change immediately after comparison, as it can't
745 possibly change to the current thread's state.
746 * If equal, then the current thread holds the lock, so the value can't
747 change until we yield the lock.
748*/
749static int
750PyThreadState_IsCurrent(PyThreadState *tstate)
751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 /* Must be the tstate for this thread */
753 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100754 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000755}
756
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000757/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000758 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000759*/
Tim Peters19717fa2004-10-09 17:38:29 +0000760void
761_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000762{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 assert(i && t); /* must init with valid states */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600764 _PyRuntime.gilstate.autoTLSkey = PyThread_create_key();
765 if (_PyRuntime.gilstate.autoTLSkey == -1)
Kristján Valur Jónsson2fea9b92010-09-20 02:11:49 +0000766 Py_FatalError("Could not allocate TLS entry");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600767 _PyRuntime.gilstate.autoInterpreterState = i;
768 assert(PyThread_get_key_value(_PyRuntime.gilstate.autoTLSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000772}
773
Victor Stinner861d9ab2016-03-16 22:45:24 +0100774PyInterpreterState *
775_PyGILState_GetInterpreterStateUnsafe(void)
776{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600777 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100778}
779
Tim Peters19717fa2004-10-09 17:38:29 +0000780void
781_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000782{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600783 PyThread_delete_key(_PyRuntime.gilstate.autoTLSkey);
784 _PyRuntime.gilstate.autoTLSkey = -1;
785 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000786}
787
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200788/* Reset the TLS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200789 * This should not be necessary, but some - buggy - pthread implementations
Charles-François Natalia233df82011-11-22 19:49:51 +0100790 * don't reset TLS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200791 */
792void
793_PyGILState_Reinit(void)
794{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600795 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
796 if (_PyRuntime.interpreters.mutex == NULL)
797 Py_FatalError("Can't initialize threads for interpreter");
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200798 PyThreadState *tstate = PyGILState_GetThisThreadState();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600799 PyThread_delete_key(_PyRuntime.gilstate.autoTLSkey);
800 if ((_PyRuntime.gilstate.autoTLSkey = PyThread_create_key()) == -1)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200801 Py_FatalError("Could not allocate TLS entry");
802
Charles-François Natalia233df82011-11-22 19:49:51 +0100803 /* If the thread had an associated auto thread state, reassociate it with
804 * the new key. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600805 if (tstate && PyThread_set_key_value(_PyRuntime.gilstate.autoTLSkey,
806 (void *)tstate) < 0)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200807 Py_FatalError("Couldn't create autoTLSkey mapping");
808}
809
Michael W. Hudson188d4362005-06-20 16:52:57 +0000810/* When a thread state is created for a thread by some mechanism other than
811 PyGILState_Ensure, it's important that the GILState machinery knows about
812 it so it doesn't try to create another thread state for the thread (this is
813 a better fix for SF bug #1010677 than the first one attempted).
814*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000815static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000816_PyGILState_NoteThreadState(PyThreadState* tstate)
817{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000818 /* If autoTLSkey isn't initialized, this must be the very first
819 threadstate created in Py_Initialize(). Don't do anything for now
820 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600821 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 /* Stick the thread state for this thread in thread local storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 The only situation where you can legitimately have more than one
827 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100828 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000829
Victor Stinner590cebe2013-12-13 11:08:56 +0100830 You shouldn't really be using the PyGILState_ APIs anyway (see issues
831 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000832
Victor Stinner590cebe2013-12-13 11:08:56 +0100833 The first thread state created for that given OS level thread will
834 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600836 if (PyThread_get_key_value(_PyRuntime.gilstate.autoTLSkey) == NULL) {
837 if ((PyThread_set_key_value(_PyRuntime.gilstate.autoTLSkey,
838 (void *)tstate)
839 ) < 0)
840 {
Victor Stinner590cebe2013-12-13 11:08:56 +0100841 Py_FatalError("Couldn't create autoTLSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600842 }
Victor Stinner590cebe2013-12-13 11:08:56 +0100843 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 /* PyGILState_Release must not try to delete this thread state. */
846 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000847}
848
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000849/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000850PyThreadState *
851PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000852{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600853 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600855 return (PyThreadState *)PyThread_get_key_value(
856 _PyRuntime.gilstate.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
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600867 if (_PyRuntime.gilstate.autoTLSkey == -1)
Victor Stinner8a1be612016-03-14 22:07:55 +0100868 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 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600887 /* Py_Initialize() hasn't been called! */
888 assert(_PyRuntime.gilstate.autoInterpreterState);
889 tcur = (PyThreadState *)PyThread_get_key_value(
890 _PyRuntime.gilstate.autoTLSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 if (tcur == NULL) {
Victor Stinner62ca1002013-12-13 01:46:43 +0100892 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
893 called from a new thread for the first time, we need the create the
894 GIL. */
895 PyEval_InitThreads();
896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600898 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 if (tcur == NULL)
900 Py_FatalError("Couldn't create thread-state for new thread");
901 /* This is our thread state! We'll need to delete it in the
902 matching call to PyGILState_Release(). */
903 tcur->gilstate_counter = 0;
904 current = 0; /* new thread state is never current */
905 }
906 else
907 current = PyThreadState_IsCurrent(tcur);
908 if (current == 0)
909 PyEval_RestoreThread(tcur);
910 /* Update our counter in the thread-state - no need for locks:
911 - tcur will remain valid as we hold the GIL.
912 - the counter is safe as we are the only thread "allowed"
913 to modify this value
914 */
915 ++tcur->gilstate_counter;
916 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000917}
918
Tim Peters19717fa2004-10-09 17:38:29 +0000919void
920PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600923 _PyRuntime.gilstate.autoTLSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (tcur == NULL)
925 Py_FatalError("auto-releasing thread-state, "
926 "but no thread-state for this thread");
927 /* We must hold the GIL and have our thread state current */
928 /* XXX - remove the check - the assert should be fine,
929 but while this is very new (April 2003), the extra check
930 by release-only users can't hurt.
931 */
932 if (! PyThreadState_IsCurrent(tcur))
933 Py_FatalError("This thread state must be current when releasing");
934 assert(PyThreadState_IsCurrent(tcur));
935 --tcur->gilstate_counter;
936 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* If we're going to destroy this thread-state, we must
939 * clear it while the GIL is held, as destructors may run.
940 */
941 if (tcur->gilstate_counter == 0) {
942 /* can't have been locked when we created it */
943 assert(oldstate == PyGILState_UNLOCKED);
944 PyThreadState_Clear(tcur);
945 /* Delete the thread-state. Note this releases the GIL too!
946 * It's vital that the GIL be held here, to avoid shutdown
947 * races; see bugs 225673 and 1061968 (that nasty bug has a
948 * habit of coming back).
949 */
950 PyThreadState_DeleteCurrent();
951 }
952 /* Release the lock if necessary */
953 else if (oldstate == PyGILState_UNLOCKED)
954 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000955}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000956
Benjamin Peterson3bf01752012-04-13 18:06:36 -0400957
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000958#ifdef __cplusplus
959}
960#endif