blob: 807ac4eb9d18bcfa573bf4a62dad853096ccbfcd [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
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 if (interp != NULL) {
Eric Snow93c92f72017-09-13 23:46:04 -0700110 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 interp->modules_by_index = NULL;
112 interp->sysdict = NULL;
113 interp->builtins = NULL;
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200114 interp->builtins_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 interp->tstate_head = NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600116 interp->check_interval = 100;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600117 interp->num_threads = 0;
118 interp->pythread_stacksize = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 interp->codec_search_path = NULL;
120 interp->codec_search_cache = NULL;
121 interp->codec_error_registry = NULL;
122 interp->codecs_initialized = 0;
Victor Stinner3cbf14b2011-04-27 00:24:21 +0200123 interp->fscodec_initialized = 0;
Brett Cannonfd074152012-04-14 14:10:13 -0400124 interp->importlib = NULL;
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300125 interp->import_func = NULL;
Brett Cannon3cebf932016-09-05 15:33:46 -0700126 interp->eval_frame = _PyEval_EvalFrameDefault;
Dino Viehlandf3cffd22017-06-21 14:44:36 -0700127 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000128#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300129#if HAVE_DECL_RTLD_NOW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000131#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000133#endif
134#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200135#ifdef HAVE_FORK
136 interp->before_forkers = NULL;
137 interp->after_forkers_parent = NULL;
138 interp->after_forkers_child = NULL;
139#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600142 interp->next = _PyRuntime.interpreters.head;
143 if (_PyRuntime.interpreters.main == NULL) {
144 _PyRuntime.interpreters.main = interp;
Eric Snow6b4be192017-05-22 21:36:03 -0700145 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600146 _PyRuntime.interpreters.head = interp;
147 if (_PyRuntime.interpreters.next_id < 0) {
Eric Snowe3774162017-05-22 19:46:40 -0700148 /* overflow or Py_Initialize() not called! */
149 PyErr_SetString(PyExc_RuntimeError,
150 "failed to get an interpreter ID");
151 interp = NULL;
152 } else {
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600153 interp->id = _PyRuntime.interpreters.next_id;
154 _PyRuntime.interpreters.next_id += 1;
Eric Snowe3774162017-05-22 19:46:40 -0700155 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000156 HEAD_UNLOCK();
157 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000159 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000160}
161
162
163void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000164PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 PyThreadState *p;
167 HEAD_LOCK();
168 for (p = interp->tstate_head; p != NULL; p = p->next)
169 PyThreadState_Clear(p);
170 HEAD_UNLOCK();
171 Py_CLEAR(interp->codec_search_path);
172 Py_CLEAR(interp->codec_search_cache);
173 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700174 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 Py_CLEAR(interp->sysdict);
177 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200178 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400179 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300180 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200181#ifdef HAVE_FORK
182 Py_CLEAR(interp->before_forkers);
183 Py_CLEAR(interp->after_forkers_parent);
184 Py_CLEAR(interp->after_forkers_child);
185#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000186}
187
188
189static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000190zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 PyThreadState *p;
193 /* No need to lock the mutex here because this should only happen
194 when the threads are all really dead (XXX famous last words). */
195 while ((p = interp->tstate_head) != NULL) {
196 PyThreadState_Delete(p);
197 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000198}
199
200
201void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000202PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 PyInterpreterState **p;
205 zapthreads(interp);
206 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600207 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 if (*p == NULL)
209 Py_FatalError(
210 "PyInterpreterState_Delete: invalid interp");
211 if (*p == interp)
212 break;
213 }
214 if (interp->tstate_head != NULL)
215 Py_FatalError("PyInterpreterState_Delete: remaining threads");
216 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600217 if (_PyRuntime.interpreters.main == interp) {
218 _PyRuntime.interpreters.main = NULL;
219 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700220 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
221 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200223 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000224}
225
226
Eric Snowe3774162017-05-22 19:46:40 -0700227int64_t
228PyInterpreterState_GetID(PyInterpreterState *interp)
229{
230 if (interp == NULL) {
231 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
232 return -1;
233 }
234 return interp->id;
235}
236
237
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000238/* Default implementation for _PyThreadState_GetFrame */
239static struct _frame *
240threadstate_getframe(PyThreadState *self)
241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000243}
244
Victor Stinner45b9be52010-03-03 23:28:07 +0000245static PyThreadState *
246new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000247{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200248 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 if (_PyThreadState_GetFrame == NULL)
251 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 if (tstate != NULL) {
254 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 tstate->frame = NULL;
257 tstate->recursion_depth = 0;
258 tstate->overflowed = 0;
259 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700260 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 tstate->tracing = 0;
262 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 tstate->gilstate_counter = 0;
264 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 tstate->curexc_type = NULL;
270 tstate->curexc_value = NULL;
271 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000272
Mark Shannonae3087c2017-10-22 22:41:51 +0100273 tstate->exc_state.exc_type = NULL;
274 tstate->exc_state.exc_value = NULL;
275 tstate->exc_state.exc_traceback = NULL;
276 tstate->exc_state.previous_item = NULL;
277 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 tstate->c_profilefunc = NULL;
280 tstate->c_tracefunc = NULL;
281 tstate->c_profileobj = NULL;
282 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000283
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200284 tstate->trash_delete_nesting = 0;
285 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200286 tstate->on_delete = NULL;
287 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200288
Yury Selivanov75445082015-05-11 22:57:16 -0400289 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400290 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400291
Yury Selivanoveb636452016-09-08 22:01:51 -0700292 tstate->async_gen_firstiter = NULL;
293 tstate->async_gen_finalizer = NULL;
294
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 if (init)
296 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200299 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200301 if (tstate->next)
302 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 interp->tstate_head = tstate;
304 HEAD_UNLOCK();
305 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000308}
309
Victor Stinner45b9be52010-03-03 23:28:07 +0000310PyThreadState *
311PyThreadState_New(PyInterpreterState *interp)
312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000313 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000314}
315
316PyThreadState *
317_PyThreadState_Prealloc(PyInterpreterState *interp)
318{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000320}
321
322void
323_PyThreadState_Init(PyThreadState *tstate)
324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000326}
327
Martin v. Löwis1a214512008-06-11 05:26:20 +0000328PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200329PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000330{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200331 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100332 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000334 if (module->m_slots) {
335 return NULL;
336 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 if (index == 0)
338 return NULL;
339 if (state->modules_by_index == NULL)
340 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200341 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 return NULL;
343 res = PyList_GET_ITEM(state->modules_by_index, index);
344 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000345}
346
347int
348_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
349{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000350 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300351 if (!def) {
352 assert(PyErr_Occurred());
353 return -1;
354 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000355 if (def->m_slots) {
356 PyErr_SetString(PyExc_SystemError,
357 "PyState_AddModule called on module with slots");
358 return -1;
359 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100360 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 if (!state->modules_by_index) {
362 state->modules_by_index = PyList_New(0);
363 if (!state->modules_by_index)
364 return -1;
365 }
366 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
367 if (PyList_Append(state->modules_by_index, Py_None) < 0)
368 return -1;
369 Py_INCREF(module);
370 return PyList_SetItem(state->modules_by_index,
371 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000372}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000373
Martin v. Löwis7800f752012-06-22 12:20:55 +0200374int
375PyState_AddModule(PyObject* module, struct PyModuleDef* def)
376{
377 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100378 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200379 if (!def) {
380 Py_FatalError("PyState_AddModule: Module Definition is NULL");
381 return -1;
382 }
383 index = def->m_base.m_index;
384 if (state->modules_by_index) {
385 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
386 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
387 Py_FatalError("PyState_AddModule: Module already added!");
388 return -1;
389 }
390 }
391 }
392 return _PyState_AddModule(module, def);
393}
394
395int
396PyState_RemoveModule(struct PyModuleDef* def)
397{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000398 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200399 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000400 if (def->m_slots) {
401 PyErr_SetString(PyExc_SystemError,
402 "PyState_RemoveModule called on module with slots");
403 return -1;
404 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100405 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200406 if (index == 0) {
407 Py_FatalError("PyState_RemoveModule: Module index invalid.");
408 return -1;
409 }
410 if (state->modules_by_index == NULL) {
411 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
412 return -1;
413 }
414 if (index > PyList_GET_SIZE(state->modules_by_index)) {
415 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
416 return -1;
417 }
418 return PyList_SetItem(state->modules_by_index, index, Py_None);
419}
420
Antoine Pitrou40322e62013-08-11 00:30:09 +0200421/* used by import.c:PyImport_Cleanup */
422void
423_PyState_ClearModules(void)
424{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100425 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200426 if (state->modules_by_index) {
427 Py_ssize_t i;
428 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
429 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
430 if (PyModule_Check(m)) {
431 /* cleanup the saved copy of module dicts */
432 PyModuleDef *md = PyModule_GetDef(m);
433 if (md)
434 Py_CLEAR(md->m_base.m_copy);
435 }
436 }
437 /* Setting modules_by_index to NULL could be dangerous, so we
438 clear the list instead. */
439 if (PyList_SetSlice(state->modules_by_index,
440 0, PyList_GET_SIZE(state->modules_by_index),
441 NULL))
442 PyErr_WriteUnraisable(state->modules_by_index);
443 }
444}
445
Guido van Rossuma027efa1997-05-05 20:56:21 +0000446void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000447PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 if (Py_VerboseFlag && tstate->frame != NULL)
450 fprintf(stderr,
451 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 Py_CLEAR(tstate->dict);
456 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 Py_CLEAR(tstate->curexc_type);
459 Py_CLEAR(tstate->curexc_value);
460 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000461
Mark Shannonae3087c2017-10-22 22:41:51 +0100462 Py_CLEAR(tstate->exc_state.exc_type);
463 Py_CLEAR(tstate->exc_state.exc_value);
464 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300465
Mark Shannonae3087c2017-10-22 22:41:51 +0100466 /* The stack of exception states should contain just this thread. */
467 assert(tstate->exc_info->previous_item == NULL);
468 if (Py_VerboseFlag && tstate->exc_info != &tstate->exc_state) {
469 fprintf(stderr,
470 "PyThreadState_Clear: warning: thread still has a generator\n");
471 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 tstate->c_profilefunc = NULL;
474 tstate->c_tracefunc = NULL;
475 Py_CLEAR(tstate->c_profileobj);
476 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400477
478 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700479 Py_CLEAR(tstate->async_gen_firstiter);
480 Py_CLEAR(tstate->async_gen_finalizer);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000481}
482
483
Guido van Rossum29757862001-01-23 01:46:06 +0000484/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
485static void
486tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 if (tstate == NULL)
490 Py_FatalError("PyThreadState_Delete: NULL tstate");
491 interp = tstate->interp;
492 if (interp == NULL)
493 Py_FatalError("PyThreadState_Delete: NULL interp");
494 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200495 if (tstate->prev)
496 tstate->prev->next = tstate->next;
497 else
498 interp->tstate_head = tstate->next;
499 if (tstate->next)
500 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200502 if (tstate->on_delete != NULL) {
503 tstate->on_delete(tstate->on_delete_data);
504 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200505 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000506}
507
508
Guido van Rossum29757862001-01-23 01:46:06 +0000509void
510PyThreadState_Delete(PyThreadState *tstate)
511{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100512 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600514 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900515 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600516 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900517 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600518 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200519 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000520}
521
522
Guido van Rossum29757862001-01-23 01:46:06 +0000523void
524PyThreadState_DeleteCurrent()
525{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100526 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 if (tstate == NULL)
528 Py_FatalError(
529 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100530 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600531 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900532 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600533 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900534 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600535 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100536 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000538}
Guido van Rossum29757862001-01-23 01:46:06 +0000539
540
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200541/*
542 * Delete all thread states except the one passed as argument.
543 * Note that, if there is a current thread state, it *must* be the one
544 * passed as argument. Also, this won't touch any other interpreters
545 * than the current one, since we don't know which thread state should
546 * be kept in those other interpreteres.
547 */
548void
549_PyThreadState_DeleteExcept(PyThreadState *tstate)
550{
551 PyInterpreterState *interp = tstate->interp;
552 PyThreadState *p, *next, *garbage;
553 HEAD_LOCK();
554 /* Remove all thread states, except tstate, from the linked list of
555 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200556 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200557 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200558 if (garbage == tstate)
559 garbage = tstate->next;
560 if (tstate->prev)
561 tstate->prev->next = tstate->next;
562 if (tstate->next)
563 tstate->next->prev = tstate->prev;
564 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200565 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200566 HEAD_UNLOCK();
567 /* Clear and deallocate all stale thread states. Even if this
568 executes Python code, we should be safe since it executes
569 in the current thread, not one of the stale threads. */
570 for (p = garbage; p; p = next) {
571 next = p->next;
572 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200573 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200574 }
575}
576
577
Guido van Rossuma027efa1997-05-05 20:56:21 +0000578PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100579_PyThreadState_UncheckedGet(void)
580{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100581 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100582}
583
584
585PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000586PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000587{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100588 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (tstate == NULL)
590 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000593}
594
595
596PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000597PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000598{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100599 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000600
Victor Stinnerb02ef712016-01-22 14:09:55 +0100601 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 /* It should not be possible for more than one thread state
603 to be used for a thread. Check this the best we can in debug
604 builds.
605 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200606#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 if (newts) {
608 /* This can be called from PyEval_RestoreThread(). Similar
609 to it, we need to ensure errno doesn't change.
610 */
611 int err = errno;
612 PyThreadState *check = PyGILState_GetThisThreadState();
613 if (check && check->interp == newts->interp && check != newts)
614 Py_FatalError("Invalid thread state for this thread");
615 errno = err;
616 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000617#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000619}
Guido van Rossumede04391998-04-10 20:18:25 +0000620
621/* An extension mechanism to store arbitrary additional per-thread state.
622 PyThreadState_GetDict() returns a dictionary that can be used to hold such
623 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000624 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
625 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000626
627PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000628PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000629{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100630 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 if (tstate == NULL)
632 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 if (tstate->dict == NULL) {
635 PyObject *d;
636 tstate->dict = d = PyDict_New();
637 if (d == NULL)
638 PyErr_Clear();
639 }
640 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000641}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000642
643
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000644/* Asynchronously raise an exception in a thread.
645 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000646 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000647 to call this, or use ctypes. Must be called with the GIL held.
648 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
649 match any known thread id). Can be called with exc=NULL to clear an
650 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000651
652int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200653PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
654{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100655 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 /* Although the GIL is held, a few C API functions can be called
659 * without the GIL held, and in particular some that create and
660 * destroy thread and interpreter states. Those can mutate the
661 * list of thread states we're traversing, so to prevent that we lock
662 * head_mutex for the duration.
663 */
664 HEAD_LOCK();
665 for (p = interp->tstate_head; p != NULL; p = p->next) {
666 if (p->thread_id == id) {
667 /* Tricky: we need to decref the current value
668 * (if any) in p->async_exc, but that can in turn
669 * allow arbitrary Python code to run, including
670 * perhaps calls to this function. To prevent
671 * deadlock, we need to release head_mutex before
672 * the decref.
673 */
674 PyObject *old_exc = p->async_exc;
675 Py_XINCREF(exc);
676 p->async_exc = exc;
677 HEAD_UNLOCK();
678 Py_XDECREF(old_exc);
679 _PyEval_SignalAsyncExc();
680 return 1;
681 }
682 }
683 HEAD_UNLOCK();
684 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000685}
686
687
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000688/* Routines for advanced debuggers, requested by David Beazley.
689 Don't use unless you know what you are doing! */
690
691PyInterpreterState *
692PyInterpreterState_Head(void)
693{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600694 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000695}
696
697PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700698PyInterpreterState_Main(void)
699{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600700 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700701}
702
703PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000704PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000706}
707
708PyThreadState *
709PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000711}
712
713PyThreadState *
714PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000716}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000717
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000718/* The implementation of sys._current_frames(). This is intended to be
719 called with the GIL held, as it will be when called via
720 sys._current_frames(). It's possible it would work fine even without
721 the GIL held, but haven't thought enough about that.
722*/
723PyObject *
724_PyThread_CurrentFrames(void)
725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 PyObject *result;
727 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 result = PyDict_New();
730 if (result == NULL)
731 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 /* for i in all interpreters:
734 * for t in all of i's thread states:
735 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200736 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 * need to grab head_mutex for the duration.
738 */
739 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600740 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 PyThreadState *t;
742 for (t = i->tstate_head; t != NULL; t = t->next) {
743 PyObject *id;
744 int stat;
745 struct _frame *frame = t->frame;
746 if (frame == NULL)
747 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200748 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 if (id == NULL)
750 goto Fail;
751 stat = PyDict_SetItem(result, id, (PyObject *)frame);
752 Py_DECREF(id);
753 if (stat < 0)
754 goto Fail;
755 }
756 }
757 HEAD_UNLOCK();
758 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000759
760 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 HEAD_UNLOCK();
762 Py_DECREF(result);
763 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000764}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000765
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000766/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000767
768/* Keep this as a static, as it is not reliable! It can only
769 ever be compared to the state for the *current* thread.
770 * If not equal, then it doesn't matter that the actual
771 value may change immediately after comparison, as it can't
772 possibly change to the current thread's state.
773 * If equal, then the current thread holds the lock, so the value can't
774 change until we yield the lock.
775*/
776static int
777PyThreadState_IsCurrent(PyThreadState *tstate)
778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 /* Must be the tstate for this thread */
780 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100781 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000782}
783
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000784/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000785 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000786*/
Tim Peters19717fa2004-10-09 17:38:29 +0000787void
788_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900791 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
792 Py_FatalError("Could not allocate TSS entry");
793 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600794 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900795 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000799}
800
Victor Stinner861d9ab2016-03-16 22:45:24 +0100801PyInterpreterState *
802_PyGILState_GetInterpreterStateUnsafe(void)
803{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600804 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100805}
806
Tim Peters19717fa2004-10-09 17:38:29 +0000807void
808_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000809{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900810 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600811 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000812}
813
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900814/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200815 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900816 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200817 */
818void
819_PyGILState_Reinit(void)
820{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600821 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
822 if (_PyRuntime.interpreters.mutex == NULL)
823 Py_FatalError("Can't initialize threads for interpreter");
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200824 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900825 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
826 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
827 Py_FatalError("Could not allocate TSS entry");
828 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200829
Charles-François Natalia233df82011-11-22 19:49:51 +0100830 /* If the thread had an associated auto thread state, reassociate it with
831 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900832 if (tstate &&
833 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
834 {
835 Py_FatalError("Couldn't create autoTSSkey mapping");
836 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200837}
838
Michael W. Hudson188d4362005-06-20 16:52:57 +0000839/* When a thread state is created for a thread by some mechanism other than
840 PyGILState_Ensure, it's important that the GILState machinery knows about
841 it so it doesn't try to create another thread state for the thread (this is
842 a better fix for SF bug #1010677 than the first one attempted).
843*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000844static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000845_PyGILState_NoteThreadState(PyThreadState* tstate)
846{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900847 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +0000848 threadstate created in Py_Initialize(). Don't do anything for now
849 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600850 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000852
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900853 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 The only situation where you can legitimately have more than one
856 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100857 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000858
Victor Stinner590cebe2013-12-13 11:08:56 +0100859 You shouldn't really be using the PyGILState_ APIs anyway (see issues
860 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000861
Victor Stinner590cebe2013-12-13 11:08:56 +0100862 The first thread state created for that given OS level thread will
863 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900865 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
866 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
867 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600868 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900869 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600870 }
Victor Stinner590cebe2013-12-13 11:08:56 +0100871 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 /* PyGILState_Release must not try to delete this thread state. */
874 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000875}
876
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000877/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000878PyThreadState *
879PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000880{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600881 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900883 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000884}
885
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700886int
887PyGILState_Check(void)
888{
Victor Stinner8a1be612016-03-14 22:07:55 +0100889 PyThreadState *tstate;
890
891 if (!_PyGILState_check_enabled)
892 return 1;
893
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900894 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +0100895 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900896 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100897
898 tstate = GET_TSTATE();
899 if (tstate == NULL)
900 return 0;
901
902 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700903}
904
Tim Peters19717fa2004-10-09 17:38:29 +0000905PyGILState_STATE
906PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 int current;
909 PyThreadState *tcur;
910 /* Note that we do not auto-init Python here - apart from
911 potential races with 2 threads auto-initializing, pep-311
912 spells out other issues. Embedders are expected to have
913 called Py_Initialize() and usually PyEval_InitThreads().
914 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600915 /* Py_Initialize() hasn't been called! */
916 assert(_PyRuntime.gilstate.autoInterpreterState);
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900917 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 if (tcur == NULL) {
Victor Stinner62ca1002013-12-13 01:46:43 +0100919 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
920 called from a new thread for the first time, we need the create the
921 GIL. */
922 PyEval_InitThreads();
923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600925 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 if (tcur == NULL)
927 Py_FatalError("Couldn't create thread-state for new thread");
928 /* This is our thread state! We'll need to delete it in the
929 matching call to PyGILState_Release(). */
930 tcur->gilstate_counter = 0;
931 current = 0; /* new thread state is never current */
932 }
933 else
934 current = PyThreadState_IsCurrent(tcur);
935 if (current == 0)
936 PyEval_RestoreThread(tcur);
937 /* Update our counter in the thread-state - no need for locks:
938 - tcur will remain valid as we hold the GIL.
939 - the counter is safe as we are the only thread "allowed"
940 to modify this value
941 */
942 ++tcur->gilstate_counter;
943 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000944}
945
Tim Peters19717fa2004-10-09 17:38:29 +0000946void
947PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000948{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900949 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
950 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 if (tcur == NULL)
952 Py_FatalError("auto-releasing thread-state, "
953 "but no thread-state for this thread");
954 /* We must hold the GIL and have our thread state current */
955 /* XXX - remove the check - the assert should be fine,
956 but while this is very new (April 2003), the extra check
957 by release-only users can't hurt.
958 */
959 if (! PyThreadState_IsCurrent(tcur))
960 Py_FatalError("This thread state must be current when releasing");
961 assert(PyThreadState_IsCurrent(tcur));
962 --tcur->gilstate_counter;
963 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 /* If we're going to destroy this thread-state, we must
966 * clear it while the GIL is held, as destructors may run.
967 */
968 if (tcur->gilstate_counter == 0) {
969 /* can't have been locked when we created it */
970 assert(oldstate == PyGILState_UNLOCKED);
971 PyThreadState_Clear(tcur);
972 /* Delete the thread-state. Note this releases the GIL too!
973 * It's vital that the GIL be held here, to avoid shutdown
974 * races; see bugs 225673 and 1061968 (that nasty bug has a
975 * habit of coming back).
976 */
977 PyThreadState_DeleteCurrent();
978 }
979 /* Release the lock if necessary */
980 else if (oldstate == PyGILState_UNLOCKED)
981 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000982}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000983
Benjamin Peterson3bf01752012-04-13 18:06:36 -0400984
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000985#ifdef __cplusplus
986}
987#endif