blob: f6fbb4d041ea4b80b89140a96df92c88f78f1db3 [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
Victor Stinnerf7e5b562017-11-15 15:48:08 -080038_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060039_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;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080049
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090050 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
51 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080052 Py_tss_t initial = Py_tss_NEEDS_INIT;
53 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000054
Eric Snow2ebc5ce2017-09-07 23:51:28 -060055 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080056 if (runtime->interpreters.mutex == NULL) {
57 return _Py_INIT_ERR("Can't initialize threads for interpreter");
58 }
59
Eric Snow2ebc5ce2017-09-07 23:51:28 -060060 runtime->interpreters.next_id = -1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080061 return _Py_INIT_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060062}
Eric Snow05351c12017-09-05 21:43:08 -070063
Eric Snow2ebc5ce2017-09-07 23:51:28 -060064void
65_PyRuntimeState_Fini(_PyRuntimeState *runtime)
66{
Victor Stinnerccb04422017-11-16 03:20:31 -080067 /* Use the same memory allocator than _PyRuntimeState_Init() */
68 PyMemAllocatorEx old_alloc, raw_alloc;
69 PyMem_GetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
70 _PyMem_GetDefaultRawAllocator(&raw_alloc);
71 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &raw_alloc);
72
Eric Snow2ebc5ce2017-09-07 23:51:28 -060073 if (runtime->interpreters.mutex != NULL) {
74 PyThread_free_lock(runtime->interpreters.mutex);
75 runtime->interpreters.mutex = NULL;
76 }
Victor Stinnerccb04422017-11-16 03:20:31 -080077
78 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060079}
80
81#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
82 WAIT_LOCK)
83#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -070084
Michael W. Hudson188d4362005-06-20 16:52:57 +000085static void _PyGILState_NoteThreadState(PyThreadState* tstate);
86
Victor Stinnera7368ac2017-11-15 18:11:45 -080087_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060088_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -070089{
Eric Snow2ebc5ce2017-09-07 23:51:28 -060090 runtime->interpreters.next_id = 0;
91 /* Since we only call _PyRuntimeState_Init() once per process
92 (see _PyRuntime_Initialize()), we make sure the mutex is
93 initialized here. */
94 if (runtime->interpreters.mutex == NULL) {
95 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnera7368ac2017-11-15 18:11:45 -080096 if (runtime->interpreters.mutex == NULL) {
97 return _Py_INIT_ERR("Can't initialize threads for interpreter");
98 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060099 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800100 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700101}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000102
103PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000104PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200107 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000108
Victor Stinnerd4341102017-11-23 00:12:09 +0100109 if (interp == NULL) {
110 return NULL;
111 }
112
113
114 interp->modules = NULL;
115 interp->modules_by_index = NULL;
116 interp->sysdict = NULL;
117 interp->builtins = NULL;
118 interp->builtins_copy = NULL;
119 interp->tstate_head = NULL;
120 interp->check_interval = 100;
121 interp->num_threads = 0;
122 interp->pythread_stacksize = 0;
123 interp->codec_search_path = NULL;
124 interp->codec_search_cache = NULL;
125 interp->codec_error_registry = NULL;
126 interp->codecs_initialized = 0;
127 interp->fscodec_initialized = 0;
128 interp->core_config = _PyCoreConfig_INIT;
129 interp->config = _PyMainInterpreterConfig_INIT;
130 interp->importlib = NULL;
131 interp->import_func = NULL;
132 interp->eval_frame = _PyEval_EvalFrameDefault;
133 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000134#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300135#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100136 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000137#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100138 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000139#endif
140#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200141#ifdef HAVE_FORK
Victor Stinnerd4341102017-11-23 00:12:09 +0100142 interp->before_forkers = NULL;
143 interp->after_forkers_parent = NULL;
144 interp->after_forkers_child = NULL;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200145#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000146
Victor Stinnerd4341102017-11-23 00:12:09 +0100147 HEAD_LOCK();
148 interp->next = _PyRuntime.interpreters.head;
149 if (_PyRuntime.interpreters.main == NULL) {
150 _PyRuntime.interpreters.main = interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 }
Victor Stinnerd4341102017-11-23 00:12:09 +0100152 _PyRuntime.interpreters.head = interp;
153 if (_PyRuntime.interpreters.next_id < 0) {
154 /* overflow or Py_Initialize() not called! */
155 PyErr_SetString(PyExc_RuntimeError,
156 "failed to get an interpreter ID");
157 interp = NULL;
158 } else {
159 interp->id = _PyRuntime.interpreters.next_id;
160 _PyRuntime.interpreters.next_id += 1;
161 }
162 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000165}
166
167
168void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000169PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 PyThreadState *p;
172 HEAD_LOCK();
173 for (p = interp->tstate_head; p != NULL; p = p->next)
174 PyThreadState_Clear(p);
175 HEAD_UNLOCK();
176 Py_CLEAR(interp->codec_search_path);
177 Py_CLEAR(interp->codec_search_cache);
178 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700179 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 Py_CLEAR(interp->sysdict);
182 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200183 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400184 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300185 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200186#ifdef HAVE_FORK
187 Py_CLEAR(interp->before_forkers);
188 Py_CLEAR(interp->after_forkers_parent);
189 Py_CLEAR(interp->after_forkers_child);
190#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000191}
192
193
194static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000195zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 PyThreadState *p;
198 /* No need to lock the mutex here because this should only happen
199 when the threads are all really dead (XXX famous last words). */
200 while ((p = interp->tstate_head) != NULL) {
201 PyThreadState_Delete(p);
202 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000203}
204
205
206void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000207PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 PyInterpreterState **p;
210 zapthreads(interp);
211 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600212 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 if (*p == NULL)
214 Py_FatalError(
215 "PyInterpreterState_Delete: invalid interp");
216 if (*p == interp)
217 break;
218 }
219 if (interp->tstate_head != NULL)
220 Py_FatalError("PyInterpreterState_Delete: remaining threads");
221 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600222 if (_PyRuntime.interpreters.main == interp) {
223 _PyRuntime.interpreters.main = NULL;
224 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700225 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
226 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200228 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000229}
230
231
Eric Snowe3774162017-05-22 19:46:40 -0700232int64_t
233PyInterpreterState_GetID(PyInterpreterState *interp)
234{
235 if (interp == NULL) {
236 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
237 return -1;
238 }
239 return interp->id;
240}
241
242
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000243/* Default implementation for _PyThreadState_GetFrame */
244static struct _frame *
245threadstate_getframe(PyThreadState *self)
246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000248}
249
Victor Stinner45b9be52010-03-03 23:28:07 +0000250static PyThreadState *
251new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000252{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200253 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 if (_PyThreadState_GetFrame == NULL)
256 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 if (tstate != NULL) {
259 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 tstate->frame = NULL;
262 tstate->recursion_depth = 0;
263 tstate->overflowed = 0;
264 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700265 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 tstate->tracing = 0;
267 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 tstate->gilstate_counter = 0;
269 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 tstate->curexc_type = NULL;
275 tstate->curexc_value = NULL;
276 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000277
Mark Shannonae3087c2017-10-22 22:41:51 +0100278 tstate->exc_state.exc_type = NULL;
279 tstate->exc_state.exc_value = NULL;
280 tstate->exc_state.exc_traceback = NULL;
281 tstate->exc_state.previous_item = NULL;
282 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 tstate->c_profilefunc = NULL;
285 tstate->c_tracefunc = NULL;
286 tstate->c_profileobj = NULL;
287 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000288
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200289 tstate->trash_delete_nesting = 0;
290 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200291 tstate->on_delete = NULL;
292 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200293
Yury Selivanov75445082015-05-11 22:57:16 -0400294 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400295 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400296
Yury Selivanoveb636452016-09-08 22:01:51 -0700297 tstate->async_gen_firstiter = NULL;
298 tstate->async_gen_finalizer = NULL;
299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 if (init)
301 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200304 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200306 if (tstate->next)
307 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 interp->tstate_head = tstate;
309 HEAD_UNLOCK();
310 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000313}
314
Victor Stinner45b9be52010-03-03 23:28:07 +0000315PyThreadState *
316PyThreadState_New(PyInterpreterState *interp)
317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000319}
320
321PyThreadState *
322_PyThreadState_Prealloc(PyInterpreterState *interp)
323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000325}
326
327void
328_PyThreadState_Init(PyThreadState *tstate)
329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000331}
332
Martin v. Löwis1a214512008-06-11 05:26:20 +0000333PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200334PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000335{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200336 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100337 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000339 if (module->m_slots) {
340 return NULL;
341 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 if (index == 0)
343 return NULL;
344 if (state->modules_by_index == NULL)
345 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200346 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 return NULL;
348 res = PyList_GET_ITEM(state->modules_by_index, index);
349 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000350}
351
352int
353_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
354{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000355 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300356 if (!def) {
357 assert(PyErr_Occurred());
358 return -1;
359 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000360 if (def->m_slots) {
361 PyErr_SetString(PyExc_SystemError,
362 "PyState_AddModule called on module with slots");
363 return -1;
364 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100365 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 if (!state->modules_by_index) {
367 state->modules_by_index = PyList_New(0);
368 if (!state->modules_by_index)
369 return -1;
370 }
371 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
372 if (PyList_Append(state->modules_by_index, Py_None) < 0)
373 return -1;
374 Py_INCREF(module);
375 return PyList_SetItem(state->modules_by_index,
376 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000377}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000378
Martin v. Löwis7800f752012-06-22 12:20:55 +0200379int
380PyState_AddModule(PyObject* module, struct PyModuleDef* def)
381{
382 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100383 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200384 if (!def) {
385 Py_FatalError("PyState_AddModule: Module Definition is NULL");
386 return -1;
387 }
388 index = def->m_base.m_index;
389 if (state->modules_by_index) {
390 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
391 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
392 Py_FatalError("PyState_AddModule: Module already added!");
393 return -1;
394 }
395 }
396 }
397 return _PyState_AddModule(module, def);
398}
399
400int
401PyState_RemoveModule(struct PyModuleDef* def)
402{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000403 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200404 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000405 if (def->m_slots) {
406 PyErr_SetString(PyExc_SystemError,
407 "PyState_RemoveModule called on module with slots");
408 return -1;
409 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100410 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200411 if (index == 0) {
412 Py_FatalError("PyState_RemoveModule: Module index invalid.");
413 return -1;
414 }
415 if (state->modules_by_index == NULL) {
416 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
417 return -1;
418 }
419 if (index > PyList_GET_SIZE(state->modules_by_index)) {
420 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
421 return -1;
422 }
423 return PyList_SetItem(state->modules_by_index, index, Py_None);
424}
425
Antoine Pitrou40322e62013-08-11 00:30:09 +0200426/* used by import.c:PyImport_Cleanup */
427void
428_PyState_ClearModules(void)
429{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100430 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200431 if (state->modules_by_index) {
432 Py_ssize_t i;
433 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
434 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
435 if (PyModule_Check(m)) {
436 /* cleanup the saved copy of module dicts */
437 PyModuleDef *md = PyModule_GetDef(m);
438 if (md)
439 Py_CLEAR(md->m_base.m_copy);
440 }
441 }
442 /* Setting modules_by_index to NULL could be dangerous, so we
443 clear the list instead. */
444 if (PyList_SetSlice(state->modules_by_index,
445 0, PyList_GET_SIZE(state->modules_by_index),
446 NULL))
447 PyErr_WriteUnraisable(state->modules_by_index);
448 }
449}
450
Guido van Rossuma027efa1997-05-05 20:56:21 +0000451void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000452PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 if (Py_VerboseFlag && tstate->frame != NULL)
455 fprintf(stderr,
456 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 Py_CLEAR(tstate->dict);
461 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 Py_CLEAR(tstate->curexc_type);
464 Py_CLEAR(tstate->curexc_value);
465 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000466
Mark Shannonae3087c2017-10-22 22:41:51 +0100467 Py_CLEAR(tstate->exc_state.exc_type);
468 Py_CLEAR(tstate->exc_state.exc_value);
469 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300470
Mark Shannonae3087c2017-10-22 22:41:51 +0100471 /* The stack of exception states should contain just this thread. */
472 assert(tstate->exc_info->previous_item == NULL);
473 if (Py_VerboseFlag && tstate->exc_info != &tstate->exc_state) {
474 fprintf(stderr,
475 "PyThreadState_Clear: warning: thread still has a generator\n");
476 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 tstate->c_profilefunc = NULL;
479 tstate->c_tracefunc = NULL;
480 Py_CLEAR(tstate->c_profileobj);
481 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400482
483 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700484 Py_CLEAR(tstate->async_gen_firstiter);
485 Py_CLEAR(tstate->async_gen_finalizer);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000486}
487
488
Guido van Rossum29757862001-01-23 01:46:06 +0000489/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
490static void
491tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (tstate == NULL)
495 Py_FatalError("PyThreadState_Delete: NULL tstate");
496 interp = tstate->interp;
497 if (interp == NULL)
498 Py_FatalError("PyThreadState_Delete: NULL interp");
499 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200500 if (tstate->prev)
501 tstate->prev->next = tstate->next;
502 else
503 interp->tstate_head = tstate->next;
504 if (tstate->next)
505 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200507 if (tstate->on_delete != NULL) {
508 tstate->on_delete(tstate->on_delete_data);
509 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200510 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000511}
512
513
Guido van Rossum29757862001-01-23 01:46:06 +0000514void
515PyThreadState_Delete(PyThreadState *tstate)
516{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100517 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600519 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900520 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600521 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900522 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600523 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200524 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000525}
526
527
Guido van Rossum29757862001-01-23 01:46:06 +0000528void
529PyThreadState_DeleteCurrent()
530{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100531 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 if (tstate == NULL)
533 Py_FatalError(
534 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100535 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600536 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900537 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600538 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900539 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600540 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100541 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000543}
Guido van Rossum29757862001-01-23 01:46:06 +0000544
545
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200546/*
547 * Delete all thread states except the one passed as argument.
548 * Note that, if there is a current thread state, it *must* be the one
549 * passed as argument. Also, this won't touch any other interpreters
550 * than the current one, since we don't know which thread state should
551 * be kept in those other interpreteres.
552 */
553void
554_PyThreadState_DeleteExcept(PyThreadState *tstate)
555{
556 PyInterpreterState *interp = tstate->interp;
557 PyThreadState *p, *next, *garbage;
558 HEAD_LOCK();
559 /* Remove all thread states, except tstate, from the linked list of
560 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200561 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200562 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200563 if (garbage == tstate)
564 garbage = tstate->next;
565 if (tstate->prev)
566 tstate->prev->next = tstate->next;
567 if (tstate->next)
568 tstate->next->prev = tstate->prev;
569 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200570 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200571 HEAD_UNLOCK();
572 /* Clear and deallocate all stale thread states. Even if this
573 executes Python code, we should be safe since it executes
574 in the current thread, not one of the stale threads. */
575 for (p = garbage; p; p = next) {
576 next = p->next;
577 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200578 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200579 }
580}
581
582
Guido van Rossuma027efa1997-05-05 20:56:21 +0000583PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100584_PyThreadState_UncheckedGet(void)
585{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100586 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100587}
588
589
590PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000591PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000592{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100593 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 if (tstate == NULL)
595 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000598}
599
600
601PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000602PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000603{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100604 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000605
Victor Stinnerb02ef712016-01-22 14:09:55 +0100606 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 /* It should not be possible for more than one thread state
608 to be used for a thread. Check this the best we can in debug
609 builds.
610 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200611#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (newts) {
613 /* This can be called from PyEval_RestoreThread(). Similar
614 to it, we need to ensure errno doesn't change.
615 */
616 int err = errno;
617 PyThreadState *check = PyGILState_GetThisThreadState();
618 if (check && check->interp == newts->interp && check != newts)
619 Py_FatalError("Invalid thread state for this thread");
620 errno = err;
621 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000622#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000624}
Guido van Rossumede04391998-04-10 20:18:25 +0000625
626/* An extension mechanism to store arbitrary additional per-thread state.
627 PyThreadState_GetDict() returns a dictionary that can be used to hold such
628 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000629 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
630 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000631
632PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000633PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000634{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100635 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 if (tstate == NULL)
637 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 if (tstate->dict == NULL) {
640 PyObject *d;
641 tstate->dict = d = PyDict_New();
642 if (d == NULL)
643 PyErr_Clear();
644 }
645 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000646}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000647
648
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000649/* Asynchronously raise an exception in a thread.
650 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000651 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000652 to call this, or use ctypes. Must be called with the GIL held.
653 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
654 match any known thread id). Can be called with exc=NULL to clear an
655 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000656
657int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200658PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
659{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100660 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000663 /* Although the GIL is held, a few C API functions can be called
664 * without the GIL held, and in particular some that create and
665 * destroy thread and interpreter states. Those can mutate the
666 * list of thread states we're traversing, so to prevent that we lock
667 * head_mutex for the duration.
668 */
669 HEAD_LOCK();
670 for (p = interp->tstate_head; p != NULL; p = p->next) {
671 if (p->thread_id == id) {
672 /* Tricky: we need to decref the current value
673 * (if any) in p->async_exc, but that can in turn
674 * allow arbitrary Python code to run, including
675 * perhaps calls to this function. To prevent
676 * deadlock, we need to release head_mutex before
677 * the decref.
678 */
679 PyObject *old_exc = p->async_exc;
680 Py_XINCREF(exc);
681 p->async_exc = exc;
682 HEAD_UNLOCK();
683 Py_XDECREF(old_exc);
684 _PyEval_SignalAsyncExc();
685 return 1;
686 }
687 }
688 HEAD_UNLOCK();
689 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000690}
691
692
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000693/* Routines for advanced debuggers, requested by David Beazley.
694 Don't use unless you know what you are doing! */
695
696PyInterpreterState *
697PyInterpreterState_Head(void)
698{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600699 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000700}
701
702PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700703PyInterpreterState_Main(void)
704{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600705 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700706}
707
708PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000709PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000711}
712
713PyThreadState *
714PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000716}
717
718PyThreadState *
719PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000721}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000722
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000723/* The implementation of sys._current_frames(). This is intended to be
724 called with the GIL held, as it will be when called via
725 sys._current_frames(). It's possible it would work fine even without
726 the GIL held, but haven't thought enough about that.
727*/
728PyObject *
729_PyThread_CurrentFrames(void)
730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 PyObject *result;
732 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 result = PyDict_New();
735 if (result == NULL)
736 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 /* for i in all interpreters:
739 * for t in all of i's thread states:
740 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200741 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 * need to grab head_mutex for the duration.
743 */
744 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600745 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 PyThreadState *t;
747 for (t = i->tstate_head; t != NULL; t = t->next) {
748 PyObject *id;
749 int stat;
750 struct _frame *frame = t->frame;
751 if (frame == NULL)
752 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200753 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 if (id == NULL)
755 goto Fail;
756 stat = PyDict_SetItem(result, id, (PyObject *)frame);
757 Py_DECREF(id);
758 if (stat < 0)
759 goto Fail;
760 }
761 }
762 HEAD_UNLOCK();
763 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000764
765 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 HEAD_UNLOCK();
767 Py_DECREF(result);
768 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000769}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000770
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000771/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000772
773/* Keep this as a static, as it is not reliable! It can only
774 ever be compared to the state for the *current* thread.
775 * If not equal, then it doesn't matter that the actual
776 value may change immediately after comparison, as it can't
777 possibly change to the current thread's state.
778 * If equal, then the current thread holds the lock, so the value can't
779 change until we yield the lock.
780*/
781static int
782PyThreadState_IsCurrent(PyThreadState *tstate)
783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 /* Must be the tstate for this thread */
785 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100786 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000787}
788
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000789/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000790 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000791*/
Tim Peters19717fa2004-10-09 17:38:29 +0000792void
793_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900796 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
797 Py_FatalError("Could not allocate TSS entry");
798 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600799 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900800 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000804}
805
Victor Stinner861d9ab2016-03-16 22:45:24 +0100806PyInterpreterState *
807_PyGILState_GetInterpreterStateUnsafe(void)
808{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600809 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100810}
811
Tim Peters19717fa2004-10-09 17:38:29 +0000812void
813_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000814{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900815 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600816 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000817}
818
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900819/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200820 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900821 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200822 */
823void
824_PyGILState_Reinit(void)
825{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600826 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
827 if (_PyRuntime.interpreters.mutex == NULL)
828 Py_FatalError("Can't initialize threads for interpreter");
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200829 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900830 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
831 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
832 Py_FatalError("Could not allocate TSS entry");
833 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200834
Charles-François Natalia233df82011-11-22 19:49:51 +0100835 /* If the thread had an associated auto thread state, reassociate it with
836 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900837 if (tstate &&
838 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
839 {
840 Py_FatalError("Couldn't create autoTSSkey mapping");
841 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200842}
843
Michael W. Hudson188d4362005-06-20 16:52:57 +0000844/* When a thread state is created for a thread by some mechanism other than
845 PyGILState_Ensure, it's important that the GILState machinery knows about
846 it so it doesn't try to create another thread state for the thread (this is
847 a better fix for SF bug #1010677 than the first one attempted).
848*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000849static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000850_PyGILState_NoteThreadState(PyThreadState* tstate)
851{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900852 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +0000853 threadstate created in Py_Initialize(). Don't do anything for now
854 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600855 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000857
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900858 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 The only situation where you can legitimately have more than one
861 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100862 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000863
Victor Stinner590cebe2013-12-13 11:08:56 +0100864 You shouldn't really be using the PyGILState_ APIs anyway (see issues
865 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000866
Victor Stinner590cebe2013-12-13 11:08:56 +0100867 The first thread state created for that given OS level thread will
868 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900870 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
871 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
872 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600873 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900874 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600875 }
Victor Stinner590cebe2013-12-13 11:08:56 +0100876 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 /* PyGILState_Release must not try to delete this thread state. */
879 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000880}
881
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000882/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000883PyThreadState *
884PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000885{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600886 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900888 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000889}
890
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700891int
892PyGILState_Check(void)
893{
Victor Stinner8a1be612016-03-14 22:07:55 +0100894 PyThreadState *tstate;
895
896 if (!_PyGILState_check_enabled)
897 return 1;
898
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900899 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +0100900 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900901 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100902
903 tstate = GET_TSTATE();
904 if (tstate == NULL)
905 return 0;
906
907 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700908}
909
Tim Peters19717fa2004-10-09 17:38:29 +0000910PyGILState_STATE
911PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 int current;
914 PyThreadState *tcur;
915 /* Note that we do not auto-init Python here - apart from
916 potential races with 2 threads auto-initializing, pep-311
917 spells out other issues. Embedders are expected to have
918 called Py_Initialize() and usually PyEval_InitThreads().
919 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600920 /* Py_Initialize() hasn't been called! */
921 assert(_PyRuntime.gilstate.autoInterpreterState);
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900922 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 if (tcur == NULL) {
Victor Stinner62ca1002013-12-13 01:46:43 +0100924 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
925 called from a new thread for the first time, we need the create the
926 GIL. */
927 PyEval_InitThreads();
928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600930 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 if (tcur == NULL)
932 Py_FatalError("Couldn't create thread-state for new thread");
933 /* This is our thread state! We'll need to delete it in the
934 matching call to PyGILState_Release(). */
935 tcur->gilstate_counter = 0;
936 current = 0; /* new thread state is never current */
937 }
938 else
939 current = PyThreadState_IsCurrent(tcur);
940 if (current == 0)
941 PyEval_RestoreThread(tcur);
942 /* Update our counter in the thread-state - no need for locks:
943 - tcur will remain valid as we hold the GIL.
944 - the counter is safe as we are the only thread "allowed"
945 to modify this value
946 */
947 ++tcur->gilstate_counter;
948 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000949}
950
Tim Peters19717fa2004-10-09 17:38:29 +0000951void
952PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000953{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900954 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
955 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 if (tcur == NULL)
957 Py_FatalError("auto-releasing thread-state, "
958 "but no thread-state for this thread");
959 /* We must hold the GIL and have our thread state current */
960 /* XXX - remove the check - the assert should be fine,
961 but while this is very new (April 2003), the extra check
962 by release-only users can't hurt.
963 */
964 if (! PyThreadState_IsCurrent(tcur))
965 Py_FatalError("This thread state must be current when releasing");
966 assert(PyThreadState_IsCurrent(tcur));
967 --tcur->gilstate_counter;
968 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* If we're going to destroy this thread-state, we must
971 * clear it while the GIL is held, as destructors may run.
972 */
973 if (tcur->gilstate_counter == 0) {
974 /* can't have been locked when we created it */
975 assert(oldstate == PyGILState_UNLOCKED);
976 PyThreadState_Clear(tcur);
977 /* Delete the thread-state. Note this releases the GIL too!
978 * It's vital that the GIL be held here, to avoid shutdown
979 * races; see bugs 225673 and 1061968 (that nasty bug has a
980 * habit of coming back).
981 */
982 PyThreadState_DeleteCurrent();
983 }
984 /* Release the lock if necessary */
985 else if (oldstate == PyGILState_UNLOCKED)
986 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000987}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000988
Benjamin Peterson3bf01752012-04-13 18:06:36 -0400989
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000990#ifdef __cplusplus
991}
992#endif