blob: 2d926372fd60b2ba9116d9488dd68b71abdfce78 [file] [log] [blame]
Guido van Rossuma027efa1997-05-05 20:56:21 +00001
2/* Thread and interpreter state structures and their interfaces */
3
4#include "Python.h"
5
Victor Stinnerb02ef712016-01-22 14:09:55 +01006#define GET_TSTATE() \
7 ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current))
8#define SET_TSTATE(value) \
Benjamin Petersonca470632016-09-06 13:47:26 -07009 _Py_atomic_store_relaxed(&_PyThreadState_Current, (uintptr_t)(value))
Victor Stinnerb02ef712016-01-22 14:09:55 +010010#define GET_INTERP_STATE() \
11 (GET_TSTATE()->interp)
12
Victor Stinnerbfd316e2016-01-20 11:12:38 +010013
Tim Peters84705582004-10-10 02:47:33 +000014/* --------------------------------------------------------------------------
15CAUTION
16
Victor Stinner1a7425f2013-07-07 16:25:15 +020017Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
18number of these functions are advertised as safe to call when the GIL isn't
19held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
20debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
21to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000022-------------------------------------------------------------------------- */
23
Martin v. Löwisf0473d52001-07-18 16:17:16 +000024#ifdef HAVE_DLOPEN
25#ifdef HAVE_DLFCN_H
26#include <dlfcn.h>
27#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030028#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000029#define RTLD_LAZY 1
30#endif
31#endif
32
Benjamin Peterson43162b82012-04-13 11:58:27 -040033#ifdef __cplusplus
34extern "C" {
35#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000036
Eric Snow76d5abc2017-09-05 18:26:16 -070037void
38_PyRuntimeState_Init(_PyRuntimeState *runtime)
39{
Benjamin Petersonb0a9a5a2017-09-05 20:19:12 -070040 memset(runtime, 0, sizeof(*runtime));
Eric Snow76d5abc2017-09-05 18:26:16 -070041
42 _PyObject_Initialize(&runtime->obj);
43 _PyMem_Initialize(&runtime->mem);
44 _PyGC_Initialize(&runtime->gc);
45 _PyEval_Initialize(&runtime->ceval);
46
47 runtime->gilstate.check_enabled = 1;
48 runtime->gilstate.autoTLSkey = -1;
Victor Stinner8a1be612016-03-14 22:07:55 +010049
Guido van Rossum1d5ad901999-06-18 14:22:24 +000050#ifdef WITH_THREAD
Eric Snow76d5abc2017-09-05 18:26:16 -070051 runtime->interpreters.mutex = PyThread_allocate_lock();
52 if (runtime->interpreters.mutex == NULL)
53 Py_FatalError("Can't initialize threads for interpreter");
54#endif
55 runtime->interpreters.next_id = -1;
56}
Michael W. Hudson188d4362005-06-20 16:52:57 +000057
Eric Snow76d5abc2017-09-05 18:26:16 -070058void
59_PyRuntimeState_Fini(_PyRuntimeState *runtime)
60{
61#ifdef WITH_THREAD
62 if (runtime->interpreters.mutex != NULL) {
63 PyThread_free_lock(runtime->interpreters.mutex);
64 runtime->interpreters.mutex = NULL;
65 }
66#endif
67}
68
69#ifdef WITH_THREAD
70#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
71 WAIT_LOCK)
72#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Guido van Rossum1d5ad901999-06-18 14:22:24 +000073#else
Guido van Rossum1d5ad901999-06-18 14:22:24 +000074#define HEAD_LOCK() /* Nothing */
75#define HEAD_UNLOCK() /* Nothing */
76#endif
77
Michael W. Hudsonce7da6c2005-09-30 08:20:24 +000078#ifdef WITH_THREAD
Michael W. Hudson188d4362005-06-20 16:52:57 +000079static void _PyGILState_NoteThreadState(PyThreadState* tstate);
Michael W. Hudsonce7da6c2005-09-30 08:20:24 +000080#endif
Michael W. Hudson188d4362005-06-20 16:52:57 +000081
Eric Snowe3774162017-05-22 19:46:40 -070082void
Eric Snow76d5abc2017-09-05 18:26:16 -070083_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -070084{
Eric Snow76d5abc2017-09-05 18:26:16 -070085 runtime->interpreters.next_id = 0;
86#ifdef WITH_THREAD
87 /* Since we only call _PyRuntimeState_Init() once per process
88 (see _PyRuntime_Initialize()), we make sure the mutex is
89 initialized here. */
90 if (runtime->interpreters.mutex == NULL) {
91 runtime->interpreters.mutex = PyThread_allocate_lock();
92 if (runtime->interpreters.mutex == NULL)
93 Py_FatalError("Can't initialize threads for interpreter");
94 }
95#endif
Eric Snowe3774162017-05-22 19:46:40 -070096}
Guido van Rossuma027efa1997-05-05 20:56:21 +000097
98PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000099PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200102 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 if (interp != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 interp->modules_by_index = NULL;
106 interp->sysdict = NULL;
107 interp->builtins = NULL;
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200108 interp->builtins_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 interp->tstate_head = NULL;
Eric Snow76d5abc2017-09-05 18:26:16 -0700110 interp->check_interval = 100;
111 interp->warnoptions = NULL;
112 interp->xoptions = NULL;
113 interp->num_threads = 0;
114 interp->pythread_stacksize = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 interp->codec_search_path = NULL;
116 interp->codec_search_cache = NULL;
117 interp->codec_error_registry = NULL;
118 interp->codecs_initialized = 0;
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200119 interp->fscodec_initialized = 0;
Brett Cannonfd074152012-04-14 14:10:13 -0400120 interp->importlib = NULL;
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300121 interp->import_func = NULL;
Brett Cannon3cebf932016-09-05 15:33:46 -0700122 interp->eval_frame = _PyEval_EvalFrameDefault;
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700123 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000124#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300125#if HAVE_DECL_RTLD_NOW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000127#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000129#endif
130#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200131#ifdef HAVE_FORK
132 interp->before_forkers = NULL;
133 interp->after_forkers_parent = NULL;
134 interp->after_forkers_child = NULL;
135#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 HEAD_LOCK();
Eric Snow76d5abc2017-09-05 18:26:16 -0700138 interp->next = _PyRuntime.interpreters.head;
139 if (_PyRuntime.interpreters.main == NULL) {
140 _PyRuntime.interpreters.main = interp;
Eric Snow6b4be192017-05-22 21:36:03 -0700141 }
Eric Snow76d5abc2017-09-05 18:26:16 -0700142 _PyRuntime.interpreters.head = interp;
143 if (_PyRuntime.interpreters.next_id < 0) {
Eric Snowe3774162017-05-22 19:46:40 -0700144 /* overflow or Py_Initialize() not called! */
145 PyErr_SetString(PyExc_RuntimeError,
146 "failed to get an interpreter ID");
147 interp = NULL;
148 } else {
Eric Snow76d5abc2017-09-05 18:26:16 -0700149 interp->id = _PyRuntime.interpreters.next_id;
150 _PyRuntime.interpreters.next_id += 1;
Eric Snowe3774162017-05-22 19:46:40 -0700151 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 HEAD_UNLOCK();
153 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000156}
157
158
159void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000160PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 PyThreadState *p;
163 HEAD_LOCK();
164 for (p = interp->tstate_head; p != NULL; p = p->next)
165 PyThreadState_Clear(p);
166 HEAD_UNLOCK();
167 Py_CLEAR(interp->codec_search_path);
168 Py_CLEAR(interp->codec_search_cache);
169 Py_CLEAR(interp->codec_error_registry);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 Py_CLEAR(interp->sysdict);
172 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200173 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400174 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300175 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200176#ifdef HAVE_FORK
177 Py_CLEAR(interp->before_forkers);
178 Py_CLEAR(interp->after_forkers_parent);
179 Py_CLEAR(interp->after_forkers_child);
180#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000181}
182
183
184static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000185zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 PyThreadState *p;
188 /* No need to lock the mutex here because this should only happen
189 when the threads are all really dead (XXX famous last words). */
190 while ((p = interp->tstate_head) != NULL) {
191 PyThreadState_Delete(p);
192 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000193}
194
195
196void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000197PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 PyInterpreterState **p;
200 zapthreads(interp);
201 HEAD_LOCK();
Eric Snow76d5abc2017-09-05 18:26:16 -0700202 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 if (*p == NULL)
204 Py_FatalError(
205 "PyInterpreterState_Delete: invalid interp");
206 if (*p == interp)
207 break;
208 }
209 if (interp->tstate_head != NULL)
210 Py_FatalError("PyInterpreterState_Delete: remaining threads");
211 *p = interp->next;
Eric Snow76d5abc2017-09-05 18:26:16 -0700212 if (_PyRuntime.interpreters.main == interp) {
213 _PyRuntime.interpreters.main = NULL;
214 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700215 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
216 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200218 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000219}
220
221
Eric Snowe3774162017-05-22 19:46:40 -0700222int64_t
223PyInterpreterState_GetID(PyInterpreterState *interp)
224{
225 if (interp == NULL) {
226 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
227 return -1;
228 }
229 return interp->id;
230}
231
232
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000233/* Default implementation for _PyThreadState_GetFrame */
234static struct _frame *
235threadstate_getframe(PyThreadState *self)
236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000238}
239
Victor Stinner45b9be52010-03-03 23:28:07 +0000240static PyThreadState *
241new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000242{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200243 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 if (_PyThreadState_GetFrame == NULL)
246 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 if (tstate != NULL) {
249 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 tstate->frame = NULL;
252 tstate->recursion_depth = 0;
253 tstate->overflowed = 0;
254 tstate->recursion_critical = 0;
255 tstate->tracing = 0;
256 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 tstate->gilstate_counter = 0;
258 tstate->async_exc = NULL;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000259#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 tstate->thread_id = PyThread_get_thread_ident();
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000261#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 tstate->thread_id = 0;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000263#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +0000264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 tstate->curexc_type = NULL;
268 tstate->curexc_value = NULL;
269 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 tstate->exc_type = NULL;
272 tstate->exc_value = NULL;
273 tstate->exc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 tstate->c_profilefunc = NULL;
276 tstate->c_tracefunc = NULL;
277 tstate->c_profileobj = NULL;
278 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000279
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200280 tstate->trash_delete_nesting = 0;
281 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200282 tstate->on_delete = NULL;
283 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200284
Yury Selivanov75445082015-05-11 22:57:16 -0400285 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400286 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400287
Yury Selivanoveb636452016-09-08 22:01:51 -0700288 tstate->async_gen_firstiter = NULL;
289 tstate->async_gen_finalizer = NULL;
290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 if (init)
292 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200295 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200297 if (tstate->next)
298 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 interp->tstate_head = tstate;
300 HEAD_UNLOCK();
301 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000304}
305
Victor Stinner45b9be52010-03-03 23:28:07 +0000306PyThreadState *
307PyThreadState_New(PyInterpreterState *interp)
308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000310}
311
312PyThreadState *
313_PyThreadState_Prealloc(PyInterpreterState *interp)
314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000316}
317
318void
319_PyThreadState_Init(PyThreadState *tstate)
320{
321#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000323#endif
324}
325
Martin v. Löwis1a214512008-06-11 05:26:20 +0000326PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200327PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000328{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200329 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100330 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000332 if (module->m_slots) {
333 return NULL;
334 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 if (index == 0)
336 return NULL;
337 if (state->modules_by_index == NULL)
338 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200339 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 return NULL;
341 res = PyList_GET_ITEM(state->modules_by_index, index);
342 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000343}
344
345int
346_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
347{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000348 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300349 if (!def) {
350 assert(PyErr_Occurred());
351 return -1;
352 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000353 if (def->m_slots) {
354 PyErr_SetString(PyExc_SystemError,
355 "PyState_AddModule called on module with slots");
356 return -1;
357 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100358 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 if (!state->modules_by_index) {
360 state->modules_by_index = PyList_New(0);
361 if (!state->modules_by_index)
362 return -1;
363 }
364 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
365 if (PyList_Append(state->modules_by_index, Py_None) < 0)
366 return -1;
367 Py_INCREF(module);
368 return PyList_SetItem(state->modules_by_index,
369 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000370}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000371
Martin v. Löwis7800f752012-06-22 12:20:55 +0200372int
373PyState_AddModule(PyObject* module, struct PyModuleDef* def)
374{
375 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100376 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200377 if (!def) {
378 Py_FatalError("PyState_AddModule: Module Definition is NULL");
379 return -1;
380 }
381 index = def->m_base.m_index;
382 if (state->modules_by_index) {
383 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
384 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
385 Py_FatalError("PyState_AddModule: Module already added!");
386 return -1;
387 }
388 }
389 }
390 return _PyState_AddModule(module, def);
391}
392
393int
394PyState_RemoveModule(struct PyModuleDef* def)
395{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000396 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200397 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000398 if (def->m_slots) {
399 PyErr_SetString(PyExc_SystemError,
400 "PyState_RemoveModule called on module with slots");
401 return -1;
402 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100403 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200404 if (index == 0) {
405 Py_FatalError("PyState_RemoveModule: Module index invalid.");
406 return -1;
407 }
408 if (state->modules_by_index == NULL) {
409 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
410 return -1;
411 }
412 if (index > PyList_GET_SIZE(state->modules_by_index)) {
413 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
414 return -1;
415 }
416 return PyList_SetItem(state->modules_by_index, index, Py_None);
417}
418
Antoine Pitrou40322e62013-08-11 00:30:09 +0200419/* used by import.c:PyImport_Cleanup */
420void
421_PyState_ClearModules(void)
422{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100423 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200424 if (state->modules_by_index) {
425 Py_ssize_t i;
426 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
427 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
428 if (PyModule_Check(m)) {
429 /* cleanup the saved copy of module dicts */
430 PyModuleDef *md = PyModule_GetDef(m);
431 if (md)
432 Py_CLEAR(md->m_base.m_copy);
433 }
434 }
435 /* Setting modules_by_index to NULL could be dangerous, so we
436 clear the list instead. */
437 if (PyList_SetSlice(state->modules_by_index,
438 0, PyList_GET_SIZE(state->modules_by_index),
439 NULL))
440 PyErr_WriteUnraisable(state->modules_by_index);
441 }
442}
443
Guido van Rossuma027efa1997-05-05 20:56:21 +0000444void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000445PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 if (Py_VerboseFlag && tstate->frame != NULL)
448 fprintf(stderr,
449 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 Py_CLEAR(tstate->dict);
454 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 Py_CLEAR(tstate->curexc_type);
457 Py_CLEAR(tstate->curexc_value);
458 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 Py_CLEAR(tstate->exc_type);
461 Py_CLEAR(tstate->exc_value);
462 Py_CLEAR(tstate->exc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 tstate->c_profilefunc = NULL;
465 tstate->c_tracefunc = NULL;
466 Py_CLEAR(tstate->c_profileobj);
467 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400468
469 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700470 Py_CLEAR(tstate->async_gen_firstiter);
471 Py_CLEAR(tstate->async_gen_finalizer);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000472}
473
474
Guido van Rossum29757862001-01-23 01:46:06 +0000475/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
476static void
477tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 if (tstate == NULL)
481 Py_FatalError("PyThreadState_Delete: NULL tstate");
482 interp = tstate->interp;
483 if (interp == NULL)
484 Py_FatalError("PyThreadState_Delete: NULL interp");
485 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200486 if (tstate->prev)
487 tstate->prev->next = tstate->next;
488 else
489 interp->tstate_head = tstate->next;
490 if (tstate->next)
491 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200493 if (tstate->on_delete != NULL) {
494 tstate->on_delete(tstate->on_delete_data);
495 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200496 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000497}
498
499
Guido van Rossum29757862001-01-23 01:46:06 +0000500void
501PyThreadState_Delete(PyThreadState *tstate)
502{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100503 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 Py_FatalError("PyThreadState_Delete: tstate is still current");
Tim Petersf4e69282006-02-27 17:15:31 +0000505#ifdef WITH_THREAD
Eric Snow76d5abc2017-09-05 18:26:16 -0700506 if (_PyRuntime.gilstate.autoInterpreterState &&
507 PyThread_get_key_value(_PyRuntime.gilstate.autoTLSkey) == tstate)
508 {
509 PyThread_delete_key_value(_PyRuntime.gilstate.autoTLSkey);
510 }
Tim Petersf4e69282006-02-27 17:15:31 +0000511#endif /* WITH_THREAD */
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200512 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000513}
514
515
516#ifdef WITH_THREAD
517void
518PyThreadState_DeleteCurrent()
519{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100520 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (tstate == NULL)
522 Py_FatalError(
523 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100524 tstate_delete_common(tstate);
Eric Snow76d5abc2017-09-05 18:26:16 -0700525 if (_PyRuntime.gilstate.autoInterpreterState &&
526 PyThread_get_key_value(_PyRuntime.gilstate.autoTLSkey) == tstate)
527 {
528 PyThread_delete_key_value(_PyRuntime.gilstate.autoTLSkey);
529 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100530 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000532}
533#endif /* WITH_THREAD */
534
535
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200536/*
537 * Delete all thread states except the one passed as argument.
538 * Note that, if there is a current thread state, it *must* be the one
539 * passed as argument. Also, this won't touch any other interpreters
540 * than the current one, since we don't know which thread state should
541 * be kept in those other interpreteres.
542 */
543void
544_PyThreadState_DeleteExcept(PyThreadState *tstate)
545{
546 PyInterpreterState *interp = tstate->interp;
547 PyThreadState *p, *next, *garbage;
548 HEAD_LOCK();
549 /* Remove all thread states, except tstate, from the linked list of
550 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200551 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200552 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200553 if (garbage == tstate)
554 garbage = tstate->next;
555 if (tstate->prev)
556 tstate->prev->next = tstate->next;
557 if (tstate->next)
558 tstate->next->prev = tstate->prev;
559 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200560 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200561 HEAD_UNLOCK();
562 /* Clear and deallocate all stale thread states. Even if this
563 executes Python code, we should be safe since it executes
564 in the current thread, not one of the stale threads. */
565 for (p = garbage; p; p = next) {
566 next = p->next;
567 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200568 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200569 }
570}
571
572
Guido van Rossuma027efa1997-05-05 20:56:21 +0000573PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100574_PyThreadState_UncheckedGet(void)
575{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100576 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100577}
578
579
580PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000581PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000582{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100583 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 if (tstate == NULL)
585 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000586
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000588}
589
590
591PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000592PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000593{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100594 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000595
Victor Stinnerb02ef712016-01-22 14:09:55 +0100596 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 /* It should not be possible for more than one thread state
598 to be used for a thread. Check this the best we can in debug
599 builds.
600 */
Martin v. Löwis9e296252003-05-01 05:25:29 +0000601#if defined(Py_DEBUG) && defined(WITH_THREAD)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if (newts) {
603 /* This can be called from PyEval_RestoreThread(). Similar
604 to it, we need to ensure errno doesn't change.
605 */
606 int err = errno;
607 PyThreadState *check = PyGILState_GetThisThreadState();
608 if (check && check->interp == newts->interp && check != newts)
609 Py_FatalError("Invalid thread state for this thread");
610 errno = err;
611 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000612#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000614}
Guido van Rossumede04391998-04-10 20:18:25 +0000615
616/* An extension mechanism to store arbitrary additional per-thread state.
617 PyThreadState_GetDict() returns a dictionary that can be used to hold such
618 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000619 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
620 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000621
622PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000623PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000624{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100625 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 if (tstate == NULL)
627 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 if (tstate->dict == NULL) {
630 PyObject *d;
631 tstate->dict = d = PyDict_New();
632 if (d == NULL)
633 PyErr_Clear();
634 }
635 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000636}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000637
638
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000639/* Asynchronously raise an exception in a thread.
640 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000641 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000642 to call this, or use ctypes. Must be called with the GIL held.
643 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
644 match any known thread id). Can be called with exc=NULL to clear an
645 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000646
647int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200648PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
649{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100650 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 /* Although the GIL is held, a few C API functions can be called
654 * without the GIL held, and in particular some that create and
655 * destroy thread and interpreter states. Those can mutate the
656 * list of thread states we're traversing, so to prevent that we lock
657 * head_mutex for the duration.
658 */
659 HEAD_LOCK();
660 for (p = interp->tstate_head; p != NULL; p = p->next) {
661 if (p->thread_id == id) {
662 /* Tricky: we need to decref the current value
663 * (if any) in p->async_exc, but that can in turn
664 * allow arbitrary Python code to run, including
665 * perhaps calls to this function. To prevent
666 * deadlock, we need to release head_mutex before
667 * the decref.
668 */
669 PyObject *old_exc = p->async_exc;
670 Py_XINCREF(exc);
671 p->async_exc = exc;
672 HEAD_UNLOCK();
673 Py_XDECREF(old_exc);
674 _PyEval_SignalAsyncExc();
675 return 1;
676 }
677 }
678 HEAD_UNLOCK();
679 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000680}
681
682
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000683/* Routines for advanced debuggers, requested by David Beazley.
684 Don't use unless you know what you are doing! */
685
686PyInterpreterState *
687PyInterpreterState_Head(void)
688{
Eric Snow76d5abc2017-09-05 18:26:16 -0700689 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000690}
691
692PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700693PyInterpreterState_Main(void)
694{
Eric Snow76d5abc2017-09-05 18:26:16 -0700695 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700696}
697
698PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000699PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000701}
702
703PyThreadState *
704PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000706}
707
708PyThreadState *
709PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000711}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000712
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000713/* The implementation of sys._current_frames(). This is intended to be
714 called with the GIL held, as it will be when called via
715 sys._current_frames(). It's possible it would work fine even without
716 the GIL held, but haven't thought enough about that.
717*/
718PyObject *
719_PyThread_CurrentFrames(void)
720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 PyObject *result;
722 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 result = PyDict_New();
725 if (result == NULL)
726 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 /* for i in all interpreters:
729 * for t in all of i's thread states:
730 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200731 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 * need to grab head_mutex for the duration.
733 */
734 HEAD_LOCK();
Eric Snow76d5abc2017-09-05 18:26:16 -0700735 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 PyThreadState *t;
737 for (t = i->tstate_head; t != NULL; t = t->next) {
738 PyObject *id;
739 int stat;
740 struct _frame *frame = t->frame;
741 if (frame == NULL)
742 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200743 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (id == NULL)
745 goto Fail;
746 stat = PyDict_SetItem(result, id, (PyObject *)frame);
747 Py_DECREF(id);
748 if (stat < 0)
749 goto Fail;
750 }
751 }
752 HEAD_UNLOCK();
753 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000754
755 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 HEAD_UNLOCK();
757 Py_DECREF(result);
758 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000759}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000760
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000761/* Python "auto thread state" API. */
762#ifdef WITH_THREAD
763
764/* Keep this as a static, as it is not reliable! It can only
765 ever be compared to the state for the *current* thread.
766 * If not equal, then it doesn't matter that the actual
767 value may change immediately after comparison, as it can't
768 possibly change to the current thread's state.
769 * If equal, then the current thread holds the lock, so the value can't
770 change until we yield the lock.
771*/
772static int
773PyThreadState_IsCurrent(PyThreadState *tstate)
774{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000775 /* Must be the tstate for this thread */
776 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100777 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000778}
779
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000780/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000781 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000782*/
Tim Peters19717fa2004-10-09 17:38:29 +0000783void
784_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000786 assert(i && t); /* must init with valid states */
Eric Snow76d5abc2017-09-05 18:26:16 -0700787 _PyRuntime.gilstate.autoTLSkey = PyThread_create_key();
788 if (_PyRuntime.gilstate.autoTLSkey == -1)
Kristján Valur Jónsson2fea9b92010-09-20 02:11:49 +0000789 Py_FatalError("Could not allocate TLS entry");
Eric Snow76d5abc2017-09-05 18:26:16 -0700790 _PyRuntime.gilstate.autoInterpreterState = i;
791 assert(PyThread_get_key_value(_PyRuntime.gilstate.autoTLSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000795}
796
Victor Stinner861d9ab2016-03-16 22:45:24 +0100797PyInterpreterState *
798_PyGILState_GetInterpreterStateUnsafe(void)
799{
Eric Snow76d5abc2017-09-05 18:26:16 -0700800 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100801}
802
Tim Peters19717fa2004-10-09 17:38:29 +0000803void
804_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000805{
Eric Snow76d5abc2017-09-05 18:26:16 -0700806 PyThread_delete_key(_PyRuntime.gilstate.autoTLSkey);
807 _PyRuntime.gilstate.autoTLSkey = -1;
808 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000809}
810
Antoine Pitrouf7ecfac2017-05-28 11:35:14 +0200811/* Reset the TLS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200812 * This should not be necessary, but some - buggy - pthread implementations
Charles-François Natalia233df82011-11-22 19:49:51 +0100813 * don't reset TLS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200814 */
815void
816_PyGILState_Reinit(void)
817{
Jason Friedf82c9512017-05-22 16:58:55 -0700818#ifdef WITH_THREAD
Eric Snow76d5abc2017-09-05 18:26:16 -0700819 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
820 if (_PyRuntime.interpreters.mutex == NULL)
821 Py_FatalError("Can't initialize threads for interpreter");
Jason Friedf82c9512017-05-22 16:58:55 -0700822#endif
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200823 PyThreadState *tstate = PyGILState_GetThisThreadState();
Eric Snow76d5abc2017-09-05 18:26:16 -0700824 PyThread_delete_key(_PyRuntime.gilstate.autoTLSkey);
825 if ((_PyRuntime.gilstate.autoTLSkey = PyThread_create_key()) == -1)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200826 Py_FatalError("Could not allocate TLS entry");
827
Charles-François Natalia233df82011-11-22 19:49:51 +0100828 /* If the thread had an associated auto thread state, reassociate it with
829 * the new key. */
Eric Snow76d5abc2017-09-05 18:26:16 -0700830 if (tstate && PyThread_set_key_value(_PyRuntime.gilstate.autoTLSkey,
831 (void *)tstate) < 0)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200832 Py_FatalError("Couldn't create autoTLSkey mapping");
833}
834
Michael W. Hudson188d4362005-06-20 16:52:57 +0000835/* When a thread state is created for a thread by some mechanism other than
836 PyGILState_Ensure, it's important that the GILState machinery knows about
837 it so it doesn't try to create another thread state for the thread (this is
838 a better fix for SF bug #1010677 than the first one attempted).
839*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000840static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000841_PyGILState_NoteThreadState(PyThreadState* tstate)
842{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000843 /* If autoTLSkey isn't initialized, this must be the very first
844 threadstate created in Py_Initialize(). Don't do anything for now
845 (we'll be back here when _PyGILState_Init is called). */
Eric Snow76d5abc2017-09-05 18:26:16 -0700846 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 /* Stick the thread state for this thread in thread local storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 The only situation where you can legitimately have more than one
852 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100853 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000854
Victor Stinner590cebe2013-12-13 11:08:56 +0100855 You shouldn't really be using the PyGILState_ APIs anyway (see issues
856 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000857
Victor Stinner590cebe2013-12-13 11:08:56 +0100858 The first thread state created for that given OS level thread will
859 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 */
Eric Snow76d5abc2017-09-05 18:26:16 -0700861 if (PyThread_get_key_value(_PyRuntime.gilstate.autoTLSkey) == NULL) {
862 if ((PyThread_set_key_value(_PyRuntime.gilstate.autoTLSkey,
863 (void *)tstate)
864 ) < 0)
865 {
Victor Stinner590cebe2013-12-13 11:08:56 +0100866 Py_FatalError("Couldn't create autoTLSkey mapping");
Eric Snow76d5abc2017-09-05 18:26:16 -0700867 }
Victor Stinner590cebe2013-12-13 11:08:56 +0100868 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 /* PyGILState_Release must not try to delete this thread state. */
871 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000872}
873
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000874/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000875PyThreadState *
876PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000877{
Eric Snow76d5abc2017-09-05 18:26:16 -0700878 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 return NULL;
Eric Snow76d5abc2017-09-05 18:26:16 -0700880 return (PyThreadState *)PyThread_get_key_value(
881 _PyRuntime.gilstate.autoTLSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000882}
883
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700884int
885PyGILState_Check(void)
886{
Victor Stinner8a1be612016-03-14 22:07:55 +0100887 PyThreadState *tstate;
888
889 if (!_PyGILState_check_enabled)
890 return 1;
891
Eric Snow76d5abc2017-09-05 18:26:16 -0700892 if (_PyRuntime.gilstate.autoTLSkey == -1)
Victor Stinner8a1be612016-03-14 22:07:55 +0100893 return 1;
894
895 tstate = GET_TSTATE();
896 if (tstate == NULL)
897 return 0;
898
899 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700900}
901
Tim Peters19717fa2004-10-09 17:38:29 +0000902PyGILState_STATE
903PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 int current;
906 PyThreadState *tcur;
907 /* Note that we do not auto-init Python here - apart from
908 potential races with 2 threads auto-initializing, pep-311
909 spells out other issues. Embedders are expected to have
910 called Py_Initialize() and usually PyEval_InitThreads().
911 */
Eric Snow76d5abc2017-09-05 18:26:16 -0700912 /* Py_Initialize() hasn't been called! */
913 assert(_PyRuntime.gilstate.autoInterpreterState);
914 tcur = (PyThreadState *)PyThread_get_key_value(
915 _PyRuntime.gilstate.autoTLSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 if (tcur == NULL) {
Victor Stinner62ca1002013-12-13 01:46:43 +0100917 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
918 called from a new thread for the first time, we need the create the
919 GIL. */
920 PyEval_InitThreads();
921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 /* Create a new thread state for this thread */
Eric Snow76d5abc2017-09-05 18:26:16 -0700923 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 if (tcur == NULL)
925 Py_FatalError("Couldn't create thread-state for new thread");
926 /* This is our thread state! We'll need to delete it in the
927 matching call to PyGILState_Release(). */
928 tcur->gilstate_counter = 0;
929 current = 0; /* new thread state is never current */
930 }
931 else
932 current = PyThreadState_IsCurrent(tcur);
933 if (current == 0)
934 PyEval_RestoreThread(tcur);
935 /* Update our counter in the thread-state - no need for locks:
936 - tcur will remain valid as we hold the GIL.
937 - the counter is safe as we are the only thread "allowed"
938 to modify this value
939 */
940 ++tcur->gilstate_counter;
941 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000942}
943
Tim Peters19717fa2004-10-09 17:38:29 +0000944void
945PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
Eric Snow76d5abc2017-09-05 18:26:16 -0700948 _PyRuntime.gilstate.autoTLSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 if (tcur == NULL)
950 Py_FatalError("auto-releasing thread-state, "
951 "but no thread-state for this thread");
952 /* We must hold the GIL and have our thread state current */
953 /* XXX - remove the check - the assert should be fine,
954 but while this is very new (April 2003), the extra check
955 by release-only users can't hurt.
956 */
957 if (! PyThreadState_IsCurrent(tcur))
958 Py_FatalError("This thread state must be current when releasing");
959 assert(PyThreadState_IsCurrent(tcur));
960 --tcur->gilstate_counter;
961 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 /* If we're going to destroy this thread-state, we must
964 * clear it while the GIL is held, as destructors may run.
965 */
966 if (tcur->gilstate_counter == 0) {
967 /* can't have been locked when we created it */
968 assert(oldstate == PyGILState_UNLOCKED);
969 PyThreadState_Clear(tcur);
970 /* Delete the thread-state. Note this releases the GIL too!
971 * It's vital that the GIL be held here, to avoid shutdown
972 * races; see bugs 225673 and 1061968 (that nasty bug has a
973 * habit of coming back).
974 */
975 PyThreadState_DeleteCurrent();
976 }
977 /* Release the lock if necessary */
978 else if (oldstate == PyGILState_UNLOCKED)
979 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000980}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000981
Benjamin Peterson3bf01752012-04-13 18:06:36 -0400982#endif /* WITH_THREAD */
983
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000984#ifdef __cplusplus
985}
986#endif
987
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000988