blob: ecf921d0c25c53fa5fa305397ff07c6ef2059217 [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 _PyGC_Initialize(&runtime->gc);
44 _PyEval_Initialize(&runtime->ceval);
Michael W. Hudson188d4362005-06-20 16:52:57 +000045
Eric Snow2ebc5ce2017-09-07 23:51:28 -060046 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080047
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090048 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
49 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080050 Py_tss_t initial = Py_tss_NEEDS_INIT;
51 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000052
Eric Snow2ebc5ce2017-09-07 23:51:28 -060053 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080054 if (runtime->interpreters.mutex == NULL) {
55 return _Py_INIT_ERR("Can't initialize threads for interpreter");
56 }
57
Eric Snow2ebc5ce2017-09-07 23:51:28 -060058 runtime->interpreters.next_id = -1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080059 return _Py_INIT_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060060}
Eric Snow05351c12017-09-05 21:43:08 -070061
Eric Snow2ebc5ce2017-09-07 23:51:28 -060062void
63_PyRuntimeState_Fini(_PyRuntimeState *runtime)
64{
Victor Stinnerccb04422017-11-16 03:20:31 -080065 /* Use the same memory allocator than _PyRuntimeState_Init() */
66 PyMemAllocatorEx old_alloc, raw_alloc;
67 PyMem_GetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
68 _PyMem_GetDefaultRawAllocator(&raw_alloc);
69 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &raw_alloc);
70
Eric Snow2ebc5ce2017-09-07 23:51:28 -060071 if (runtime->interpreters.mutex != NULL) {
72 PyThread_free_lock(runtime->interpreters.mutex);
73 runtime->interpreters.mutex = NULL;
74 }
Victor Stinnerccb04422017-11-16 03:20:31 -080075
76 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060077}
78
79#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
80 WAIT_LOCK)
81#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -070082
Michael W. Hudson188d4362005-06-20 16:52:57 +000083static void _PyGILState_NoteThreadState(PyThreadState* tstate);
84
Victor Stinnera7368ac2017-11-15 18:11:45 -080085_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060086_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -070087{
Eric Snow2ebc5ce2017-09-07 23:51:28 -060088 runtime->interpreters.next_id = 0;
89 /* Since we only call _PyRuntimeState_Init() once per process
90 (see _PyRuntime_Initialize()), we make sure the mutex is
91 initialized here. */
92 if (runtime->interpreters.mutex == NULL) {
93 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnera7368ac2017-11-15 18:11:45 -080094 if (runtime->interpreters.mutex == NULL) {
95 return _Py_INIT_ERR("Can't initialize threads for interpreter");
96 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060097 }
Victor Stinnera7368ac2017-11-15 18:11:45 -080098 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -070099}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000100
101PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000102PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200105 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000106
Victor Stinnerd4341102017-11-23 00:12:09 +0100107 if (interp == NULL) {
108 return NULL;
109 }
110
111
112 interp->modules = NULL;
113 interp->modules_by_index = NULL;
114 interp->sysdict = NULL;
115 interp->builtins = NULL;
116 interp->builtins_copy = NULL;
117 interp->tstate_head = NULL;
118 interp->check_interval = 100;
119 interp->num_threads = 0;
120 interp->pythread_stacksize = 0;
121 interp->codec_search_path = NULL;
122 interp->codec_search_cache = NULL;
123 interp->codec_error_registry = NULL;
124 interp->codecs_initialized = 0;
125 interp->fscodec_initialized = 0;
126 interp->core_config = _PyCoreConfig_INIT;
127 interp->config = _PyMainInterpreterConfig_INIT;
128 interp->importlib = NULL;
129 interp->import_func = NULL;
130 interp->eval_frame = _PyEval_EvalFrameDefault;
131 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000132#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300133#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100134 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000135#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100136 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000137#endif
138#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200139#ifdef HAVE_FORK
Victor Stinnerd4341102017-11-23 00:12:09 +0100140 interp->before_forkers = NULL;
141 interp->after_forkers_parent = NULL;
142 interp->after_forkers_child = NULL;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200143#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000144
Victor Stinnerd4341102017-11-23 00:12:09 +0100145 HEAD_LOCK();
146 interp->next = _PyRuntime.interpreters.head;
147 if (_PyRuntime.interpreters.main == NULL) {
148 _PyRuntime.interpreters.main = interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000149 }
Victor Stinnerd4341102017-11-23 00:12:09 +0100150 _PyRuntime.interpreters.head = interp;
151 if (_PyRuntime.interpreters.next_id < 0) {
152 /* overflow or Py_Initialize() not called! */
153 PyErr_SetString(PyExc_RuntimeError,
154 "failed to get an interpreter ID");
155 interp = NULL;
156 } else {
157 interp->id = _PyRuntime.interpreters.next_id;
158 _PyRuntime.interpreters.next_id += 1;
159 }
160 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000161
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000163}
164
165
166void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000167PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 PyThreadState *p;
170 HEAD_LOCK();
171 for (p = interp->tstate_head; p != NULL; p = p->next)
172 PyThreadState_Clear(p);
173 HEAD_UNLOCK();
174 Py_CLEAR(interp->codec_search_path);
175 Py_CLEAR(interp->codec_search_cache);
176 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700177 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 Py_CLEAR(interp->sysdict);
180 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200181 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400182 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300183 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200184#ifdef HAVE_FORK
185 Py_CLEAR(interp->before_forkers);
186 Py_CLEAR(interp->after_forkers_parent);
187 Py_CLEAR(interp->after_forkers_child);
188#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000189}
190
191
192static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000193zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 PyThreadState *p;
196 /* No need to lock the mutex here because this should only happen
197 when the threads are all really dead (XXX famous last words). */
198 while ((p = interp->tstate_head) != NULL) {
199 PyThreadState_Delete(p);
200 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000201}
202
203
204void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000205PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 PyInterpreterState **p;
208 zapthreads(interp);
209 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600210 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 if (*p == NULL)
212 Py_FatalError(
213 "PyInterpreterState_Delete: invalid interp");
214 if (*p == interp)
215 break;
216 }
217 if (interp->tstate_head != NULL)
218 Py_FatalError("PyInterpreterState_Delete: remaining threads");
219 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600220 if (_PyRuntime.interpreters.main == interp) {
221 _PyRuntime.interpreters.main = NULL;
222 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700223 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
224 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200226 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000227}
228
229
Eric Snowe3774162017-05-22 19:46:40 -0700230int64_t
231PyInterpreterState_GetID(PyInterpreterState *interp)
232{
233 if (interp == NULL) {
234 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
235 return -1;
236 }
237 return interp->id;
238}
239
240
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000241/* Default implementation for _PyThreadState_GetFrame */
242static struct _frame *
243threadstate_getframe(PyThreadState *self)
244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000246}
247
Victor Stinner45b9be52010-03-03 23:28:07 +0000248static PyThreadState *
249new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000250{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200251 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000252
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 if (_PyThreadState_GetFrame == NULL)
254 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 if (tstate != NULL) {
257 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 tstate->frame = NULL;
260 tstate->recursion_depth = 0;
261 tstate->overflowed = 0;
262 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700263 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 tstate->tracing = 0;
265 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 tstate->gilstate_counter = 0;
267 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 tstate->curexc_type = NULL;
273 tstate->curexc_value = NULL;
274 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000275
Mark Shannonae3087c2017-10-22 22:41:51 +0100276 tstate->exc_state.exc_type = NULL;
277 tstate->exc_state.exc_value = NULL;
278 tstate->exc_state.exc_traceback = NULL;
279 tstate->exc_state.previous_item = NULL;
280 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 tstate->c_profilefunc = NULL;
283 tstate->c_tracefunc = NULL;
284 tstate->c_profileobj = NULL;
285 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000286
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200287 tstate->trash_delete_nesting = 0;
288 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200289 tstate->on_delete = NULL;
290 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200291
Yury Selivanov75445082015-05-11 22:57:16 -0400292 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400293 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400294
Yury Selivanoveb636452016-09-08 22:01:51 -0700295 tstate->async_gen_firstiter = NULL;
296 tstate->async_gen_finalizer = NULL;
297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 if (init)
299 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000300
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200302 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200304 if (tstate->next)
305 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 interp->tstate_head = tstate;
307 HEAD_UNLOCK();
308 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000311}
312
Victor Stinner45b9be52010-03-03 23:28:07 +0000313PyThreadState *
314PyThreadState_New(PyInterpreterState *interp)
315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000317}
318
319PyThreadState *
320_PyThreadState_Prealloc(PyInterpreterState *interp)
321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000323}
324
325void
326_PyThreadState_Init(PyThreadState *tstate)
327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000329}
330
Martin v. Löwis1a214512008-06-11 05:26:20 +0000331PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200332PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000333{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200334 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100335 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000337 if (module->m_slots) {
338 return NULL;
339 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 if (index == 0)
341 return NULL;
342 if (state->modules_by_index == NULL)
343 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200344 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 return NULL;
346 res = PyList_GET_ITEM(state->modules_by_index, index);
347 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000348}
349
350int
351_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
352{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000353 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300354 if (!def) {
355 assert(PyErr_Occurred());
356 return -1;
357 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000358 if (def->m_slots) {
359 PyErr_SetString(PyExc_SystemError,
360 "PyState_AddModule called on module with slots");
361 return -1;
362 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100363 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (!state->modules_by_index) {
365 state->modules_by_index = PyList_New(0);
366 if (!state->modules_by_index)
367 return -1;
368 }
369 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
370 if (PyList_Append(state->modules_by_index, Py_None) < 0)
371 return -1;
372 Py_INCREF(module);
373 return PyList_SetItem(state->modules_by_index,
374 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000375}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000376
Martin v. Löwis7800f752012-06-22 12:20:55 +0200377int
378PyState_AddModule(PyObject* module, struct PyModuleDef* def)
379{
380 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100381 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200382 if (!def) {
383 Py_FatalError("PyState_AddModule: Module Definition is NULL");
384 return -1;
385 }
386 index = def->m_base.m_index;
387 if (state->modules_by_index) {
388 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
389 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
390 Py_FatalError("PyState_AddModule: Module already added!");
391 return -1;
392 }
393 }
394 }
395 return _PyState_AddModule(module, def);
396}
397
398int
399PyState_RemoveModule(struct PyModuleDef* def)
400{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000401 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200402 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000403 if (def->m_slots) {
404 PyErr_SetString(PyExc_SystemError,
405 "PyState_RemoveModule called on module with slots");
406 return -1;
407 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100408 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200409 if (index == 0) {
410 Py_FatalError("PyState_RemoveModule: Module index invalid.");
411 return -1;
412 }
413 if (state->modules_by_index == NULL) {
414 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
415 return -1;
416 }
417 if (index > PyList_GET_SIZE(state->modules_by_index)) {
418 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
419 return -1;
420 }
421 return PyList_SetItem(state->modules_by_index, index, Py_None);
422}
423
Antoine Pitrou40322e62013-08-11 00:30:09 +0200424/* used by import.c:PyImport_Cleanup */
425void
426_PyState_ClearModules(void)
427{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100428 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200429 if (state->modules_by_index) {
430 Py_ssize_t i;
431 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
432 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
433 if (PyModule_Check(m)) {
434 /* cleanup the saved copy of module dicts */
435 PyModuleDef *md = PyModule_GetDef(m);
436 if (md)
437 Py_CLEAR(md->m_base.m_copy);
438 }
439 }
440 /* Setting modules_by_index to NULL could be dangerous, so we
441 clear the list instead. */
442 if (PyList_SetSlice(state->modules_by_index,
443 0, PyList_GET_SIZE(state->modules_by_index),
444 NULL))
445 PyErr_WriteUnraisable(state->modules_by_index);
446 }
447}
448
Guido van Rossuma027efa1997-05-05 20:56:21 +0000449void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000450PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000452 if (Py_VerboseFlag && tstate->frame != NULL)
453 fprintf(stderr,
454 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 Py_CLEAR(tstate->dict);
459 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 Py_CLEAR(tstate->curexc_type);
462 Py_CLEAR(tstate->curexc_value);
463 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000464
Mark Shannonae3087c2017-10-22 22:41:51 +0100465 Py_CLEAR(tstate->exc_state.exc_type);
466 Py_CLEAR(tstate->exc_state.exc_value);
467 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300468
Mark Shannonae3087c2017-10-22 22:41:51 +0100469 /* The stack of exception states should contain just this thread. */
470 assert(tstate->exc_info->previous_item == NULL);
471 if (Py_VerboseFlag && tstate->exc_info != &tstate->exc_state) {
472 fprintf(stderr,
473 "PyThreadState_Clear: warning: thread still has a generator\n");
474 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 tstate->c_profilefunc = NULL;
477 tstate->c_tracefunc = NULL;
478 Py_CLEAR(tstate->c_profileobj);
479 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400480
481 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700482 Py_CLEAR(tstate->async_gen_firstiter);
483 Py_CLEAR(tstate->async_gen_finalizer);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000484}
485
486
Guido van Rossum29757862001-01-23 01:46:06 +0000487/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
488static void
489tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 if (tstate == NULL)
493 Py_FatalError("PyThreadState_Delete: NULL tstate");
494 interp = tstate->interp;
495 if (interp == NULL)
496 Py_FatalError("PyThreadState_Delete: NULL interp");
497 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200498 if (tstate->prev)
499 tstate->prev->next = tstate->next;
500 else
501 interp->tstate_head = tstate->next;
502 if (tstate->next)
503 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200505 if (tstate->on_delete != NULL) {
506 tstate->on_delete(tstate->on_delete_data);
507 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200508 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000509}
510
511
Guido van Rossum29757862001-01-23 01:46:06 +0000512void
513PyThreadState_Delete(PyThreadState *tstate)
514{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100515 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600517 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900518 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600519 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900520 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600521 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200522 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000523}
524
525
Guido van Rossum29757862001-01-23 01:46:06 +0000526void
527PyThreadState_DeleteCurrent()
528{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100529 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 if (tstate == NULL)
531 Py_FatalError(
532 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100533 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600534 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900535 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600536 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900537 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600538 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100539 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000541}
Guido van Rossum29757862001-01-23 01:46:06 +0000542
543
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200544/*
545 * Delete all thread states except the one passed as argument.
546 * Note that, if there is a current thread state, it *must* be the one
547 * passed as argument. Also, this won't touch any other interpreters
548 * than the current one, since we don't know which thread state should
549 * be kept in those other interpreteres.
550 */
551void
552_PyThreadState_DeleteExcept(PyThreadState *tstate)
553{
554 PyInterpreterState *interp = tstate->interp;
555 PyThreadState *p, *next, *garbage;
556 HEAD_LOCK();
557 /* Remove all thread states, except tstate, from the linked list of
558 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200559 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200560 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200561 if (garbage == tstate)
562 garbage = tstate->next;
563 if (tstate->prev)
564 tstate->prev->next = tstate->next;
565 if (tstate->next)
566 tstate->next->prev = tstate->prev;
567 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200568 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200569 HEAD_UNLOCK();
570 /* Clear and deallocate all stale thread states. Even if this
571 executes Python code, we should be safe since it executes
572 in the current thread, not one of the stale threads. */
573 for (p = garbage; p; p = next) {
574 next = p->next;
575 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200576 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200577 }
578}
579
580
Guido van Rossuma027efa1997-05-05 20:56:21 +0000581PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100582_PyThreadState_UncheckedGet(void)
583{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100584 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100585}
586
587
588PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000589PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000590{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100591 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (tstate == NULL)
593 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000596}
597
598
599PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000600PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000601{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100602 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000603
Victor Stinnerb02ef712016-01-22 14:09:55 +0100604 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 /* It should not be possible for more than one thread state
606 to be used for a thread. Check this the best we can in debug
607 builds.
608 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200609#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (newts) {
611 /* This can be called from PyEval_RestoreThread(). Similar
612 to it, we need to ensure errno doesn't change.
613 */
614 int err = errno;
615 PyThreadState *check = PyGILState_GetThisThreadState();
616 if (check && check->interp == newts->interp && check != newts)
617 Py_FatalError("Invalid thread state for this thread");
618 errno = err;
619 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000620#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000622}
Guido van Rossumede04391998-04-10 20:18:25 +0000623
624/* An extension mechanism to store arbitrary additional per-thread state.
625 PyThreadState_GetDict() returns a dictionary that can be used to hold such
626 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000627 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
628 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000629
630PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000631PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000632{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100633 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 if (tstate == NULL)
635 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 if (tstate->dict == NULL) {
638 PyObject *d;
639 tstate->dict = d = PyDict_New();
640 if (d == NULL)
641 PyErr_Clear();
642 }
643 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000644}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000645
646
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000647/* Asynchronously raise an exception in a thread.
648 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000649 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000650 to call this, or use ctypes. Must be called with the GIL held.
651 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
652 match any known thread id). Can be called with exc=NULL to clear an
653 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000654
655int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200656PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
657{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100658 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 /* Although the GIL is held, a few C API functions can be called
662 * without the GIL held, and in particular some that create and
663 * destroy thread and interpreter states. Those can mutate the
664 * list of thread states we're traversing, so to prevent that we lock
665 * head_mutex for the duration.
666 */
667 HEAD_LOCK();
668 for (p = interp->tstate_head; p != NULL; p = p->next) {
669 if (p->thread_id == id) {
670 /* Tricky: we need to decref the current value
671 * (if any) in p->async_exc, but that can in turn
672 * allow arbitrary Python code to run, including
673 * perhaps calls to this function. To prevent
674 * deadlock, we need to release head_mutex before
675 * the decref.
676 */
677 PyObject *old_exc = p->async_exc;
678 Py_XINCREF(exc);
679 p->async_exc = exc;
680 HEAD_UNLOCK();
681 Py_XDECREF(old_exc);
682 _PyEval_SignalAsyncExc();
683 return 1;
684 }
685 }
686 HEAD_UNLOCK();
687 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000688}
689
690
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000691/* Routines for advanced debuggers, requested by David Beazley.
692 Don't use unless you know what you are doing! */
693
694PyInterpreterState *
695PyInterpreterState_Head(void)
696{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600697 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000698}
699
700PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700701PyInterpreterState_Main(void)
702{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600703 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700704}
705
706PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000707PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000709}
710
711PyThreadState *
712PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000714}
715
716PyThreadState *
717PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000719}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000720
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000721/* The implementation of sys._current_frames(). This is intended to be
722 called with the GIL held, as it will be when called via
723 sys._current_frames(). It's possible it would work fine even without
724 the GIL held, but haven't thought enough about that.
725*/
726PyObject *
727_PyThread_CurrentFrames(void)
728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 PyObject *result;
730 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 result = PyDict_New();
733 if (result == NULL)
734 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 /* for i in all interpreters:
737 * for t in all of i's thread states:
738 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200739 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 * need to grab head_mutex for the duration.
741 */
742 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600743 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 PyThreadState *t;
745 for (t = i->tstate_head; t != NULL; t = t->next) {
746 PyObject *id;
747 int stat;
748 struct _frame *frame = t->frame;
749 if (frame == NULL)
750 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200751 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 if (id == NULL)
753 goto Fail;
754 stat = PyDict_SetItem(result, id, (PyObject *)frame);
755 Py_DECREF(id);
756 if (stat < 0)
757 goto Fail;
758 }
759 }
760 HEAD_UNLOCK();
761 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000762
763 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 HEAD_UNLOCK();
765 Py_DECREF(result);
766 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000767}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000768
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000769/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000770
771/* Keep this as a static, as it is not reliable! It can only
772 ever be compared to the state for the *current* thread.
773 * If not equal, then it doesn't matter that the actual
774 value may change immediately after comparison, as it can't
775 possibly change to the current thread's state.
776 * If equal, then the current thread holds the lock, so the value can't
777 change until we yield the lock.
778*/
779static int
780PyThreadState_IsCurrent(PyThreadState *tstate)
781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 /* Must be the tstate for this thread */
783 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100784 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000785}
786
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000787/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000788 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000789*/
Tim Peters19717fa2004-10-09 17:38:29 +0000790void
791_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000792{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000793 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900794 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
795 Py_FatalError("Could not allocate TSS entry");
796 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600797 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900798 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000802}
803
Victor Stinner861d9ab2016-03-16 22:45:24 +0100804PyInterpreterState *
805_PyGILState_GetInterpreterStateUnsafe(void)
806{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600807 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100808}
809
Tim Peters19717fa2004-10-09 17:38:29 +0000810void
811_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000812{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900813 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600814 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000815}
816
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900817/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200818 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900819 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200820 */
821void
822_PyGILState_Reinit(void)
823{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600824 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
825 if (_PyRuntime.interpreters.mutex == NULL)
826 Py_FatalError("Can't initialize threads for interpreter");
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200827 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900828 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
829 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
830 Py_FatalError("Could not allocate TSS entry");
831 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200832
Charles-François Natalia233df82011-11-22 19:49:51 +0100833 /* If the thread had an associated auto thread state, reassociate it with
834 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900835 if (tstate &&
836 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
837 {
838 Py_FatalError("Couldn't create autoTSSkey mapping");
839 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200840}
841
Michael W. Hudson188d4362005-06-20 16:52:57 +0000842/* When a thread state is created for a thread by some mechanism other than
843 PyGILState_Ensure, it's important that the GILState machinery knows about
844 it so it doesn't try to create another thread state for the thread (this is
845 a better fix for SF bug #1010677 than the first one attempted).
846*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000847static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000848_PyGILState_NoteThreadState(PyThreadState* tstate)
849{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900850 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +0000851 threadstate created in Py_Initialize(). Don't do anything for now
852 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600853 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000855
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900856 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 The only situation where you can legitimately have more than one
859 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100860 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000861
Victor Stinner590cebe2013-12-13 11:08:56 +0100862 You shouldn't really be using the PyGILState_ APIs anyway (see issues
863 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000864
Victor Stinner590cebe2013-12-13 11:08:56 +0100865 The first thread state created for that given OS level thread will
866 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900868 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
869 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
870 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600871 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900872 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600873 }
Victor Stinner590cebe2013-12-13 11:08:56 +0100874 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 /* PyGILState_Release must not try to delete this thread state. */
877 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000878}
879
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000880/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000881PyThreadState *
882PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000883{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600884 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900886 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000887}
888
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700889int
890PyGILState_Check(void)
891{
Victor Stinner8a1be612016-03-14 22:07:55 +0100892 PyThreadState *tstate;
893
894 if (!_PyGILState_check_enabled)
895 return 1;
896
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900897 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +0100898 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900899 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100900
901 tstate = GET_TSTATE();
902 if (tstate == NULL)
903 return 0;
904
905 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700906}
907
Tim Peters19717fa2004-10-09 17:38:29 +0000908PyGILState_STATE
909PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 int current;
912 PyThreadState *tcur;
913 /* Note that we do not auto-init Python here - apart from
914 potential races with 2 threads auto-initializing, pep-311
915 spells out other issues. Embedders are expected to have
916 called Py_Initialize() and usually PyEval_InitThreads().
917 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600918 /* Py_Initialize() hasn't been called! */
919 assert(_PyRuntime.gilstate.autoInterpreterState);
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900920 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 if (tcur == NULL) {
Victor Stinner62ca1002013-12-13 01:46:43 +0100922 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
923 called from a new thread for the first time, we need the create the
924 GIL. */
925 PyEval_InitThreads();
926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600928 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 if (tcur == NULL)
930 Py_FatalError("Couldn't create thread-state for new thread");
931 /* This is our thread state! We'll need to delete it in the
932 matching call to PyGILState_Release(). */
933 tcur->gilstate_counter = 0;
934 current = 0; /* new thread state is never current */
935 }
936 else
937 current = PyThreadState_IsCurrent(tcur);
938 if (current == 0)
939 PyEval_RestoreThread(tcur);
940 /* Update our counter in the thread-state - no need for locks:
941 - tcur will remain valid as we hold the GIL.
942 - the counter is safe as we are the only thread "allowed"
943 to modify this value
944 */
945 ++tcur->gilstate_counter;
946 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000947}
948
Tim Peters19717fa2004-10-09 17:38:29 +0000949void
950PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000951{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900952 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
953 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (tcur == NULL)
955 Py_FatalError("auto-releasing thread-state, "
956 "but no thread-state for this thread");
957 /* We must hold the GIL and have our thread state current */
958 /* XXX - remove the check - the assert should be fine,
959 but while this is very new (April 2003), the extra check
960 by release-only users can't hurt.
961 */
962 if (! PyThreadState_IsCurrent(tcur))
963 Py_FatalError("This thread state must be current when releasing");
964 assert(PyThreadState_IsCurrent(tcur));
965 --tcur->gilstate_counter;
966 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 /* If we're going to destroy this thread-state, we must
969 * clear it while the GIL is held, as destructors may run.
970 */
971 if (tcur->gilstate_counter == 0) {
972 /* can't have been locked when we created it */
973 assert(oldstate == PyGILState_UNLOCKED);
974 PyThreadState_Clear(tcur);
975 /* Delete the thread-state. Note this releases the GIL too!
976 * It's vital that the GIL be held here, to avoid shutdown
977 * races; see bugs 225673 and 1061968 (that nasty bug has a
978 * habit of coming back).
979 */
980 PyThreadState_DeleteCurrent();
981 }
982 /* Release the lock if necessary */
983 else if (oldstate == PyGILState_UNLOCKED)
984 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000985}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000986
Benjamin Peterson3bf01752012-04-13 18:06:36 -0400987
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000988#ifdef __cplusplus
989}
990#endif