blob: ec7eb450b660a59130e756223fbab9337940ea8c [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 Stinner5d39e042017-11-29 17:20:38 +010038static _PyInitError
39_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060040{
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
Victor Stinner5d39e042017-11-29 17:20:38 +010062_PyInitError
63_PyRuntimeState_Init(_PyRuntimeState *runtime)
64{
65 /* Force default allocator, since _PyRuntimeState_Fini() must
66 use the same allocator than this function. */
67 PyMemAllocatorEx old_alloc;
68 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
69
70 _PyInitError err = _PyRuntimeState_Init_impl(runtime);
71
72 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
73 return err;
74}
75
Eric Snow2ebc5ce2017-09-07 23:51:28 -060076void
77_PyRuntimeState_Fini(_PyRuntimeState *runtime)
78{
Victor Stinner5d39e042017-11-29 17:20:38 +010079 /* Force the allocator used by _PyRuntimeState_Init(). */
80 PyMemAllocatorEx old_alloc;
81 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -080082
Eric Snow2ebc5ce2017-09-07 23:51:28 -060083 if (runtime->interpreters.mutex != NULL) {
84 PyThread_free_lock(runtime->interpreters.mutex);
85 runtime->interpreters.mutex = NULL;
86 }
Victor Stinnerccb04422017-11-16 03:20:31 -080087
88 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060089}
90
91#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
92 WAIT_LOCK)
93#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -070094
Michael W. Hudson188d4362005-06-20 16:52:57 +000095static void _PyGILState_NoteThreadState(PyThreadState* tstate);
96
Victor Stinnera7368ac2017-11-15 18:11:45 -080097_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060098_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -070099{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600100 runtime->interpreters.next_id = 0;
101 /* Since we only call _PyRuntimeState_Init() once per process
102 (see _PyRuntime_Initialize()), we make sure the mutex is
103 initialized here. */
104 if (runtime->interpreters.mutex == NULL) {
105 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnera7368ac2017-11-15 18:11:45 -0800106 if (runtime->interpreters.mutex == NULL) {
107 return _Py_INIT_ERR("Can't initialize threads for interpreter");
108 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600109 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800110 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700111}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000112
113PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000114PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200117 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000118
Victor Stinnerd4341102017-11-23 00:12:09 +0100119 if (interp == NULL) {
120 return NULL;
121 }
122
123
124 interp->modules = NULL;
125 interp->modules_by_index = NULL;
126 interp->sysdict = NULL;
127 interp->builtins = NULL;
128 interp->builtins_copy = NULL;
129 interp->tstate_head = NULL;
130 interp->check_interval = 100;
131 interp->num_threads = 0;
132 interp->pythread_stacksize = 0;
133 interp->codec_search_path = NULL;
134 interp->codec_search_cache = NULL;
135 interp->codec_error_registry = NULL;
136 interp->codecs_initialized = 0;
137 interp->fscodec_initialized = 0;
138 interp->core_config = _PyCoreConfig_INIT;
139 interp->config = _PyMainInterpreterConfig_INIT;
140 interp->importlib = NULL;
141 interp->import_func = NULL;
142 interp->eval_frame = _PyEval_EvalFrameDefault;
143 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000144#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300145#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100146 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000147#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100148 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000149#endif
150#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200151#ifdef HAVE_FORK
Victor Stinnerd4341102017-11-23 00:12:09 +0100152 interp->before_forkers = NULL;
153 interp->after_forkers_parent = NULL;
154 interp->after_forkers_child = NULL;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200155#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000156
Victor Stinnerd4341102017-11-23 00:12:09 +0100157 HEAD_LOCK();
158 interp->next = _PyRuntime.interpreters.head;
159 if (_PyRuntime.interpreters.main == NULL) {
160 _PyRuntime.interpreters.main = interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 }
Victor Stinnerd4341102017-11-23 00:12:09 +0100162 _PyRuntime.interpreters.head = interp;
163 if (_PyRuntime.interpreters.next_id < 0) {
164 /* overflow or Py_Initialize() not called! */
165 PyErr_SetString(PyExc_RuntimeError,
166 "failed to get an interpreter ID");
167 interp = NULL;
168 } else {
169 interp->id = _PyRuntime.interpreters.next_id;
170 _PyRuntime.interpreters.next_id += 1;
171 }
172 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000175}
176
177
178void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000179PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 PyThreadState *p;
182 HEAD_LOCK();
183 for (p = interp->tstate_head; p != NULL; p = p->next)
184 PyThreadState_Clear(p);
185 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100186 _PyCoreConfig_Clear(&interp->core_config);
187 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 Py_CLEAR(interp->codec_search_path);
189 Py_CLEAR(interp->codec_search_cache);
190 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700191 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 Py_CLEAR(interp->sysdict);
194 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200195 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400196 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300197 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200198#ifdef HAVE_FORK
199 Py_CLEAR(interp->before_forkers);
200 Py_CLEAR(interp->after_forkers_parent);
201 Py_CLEAR(interp->after_forkers_child);
202#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000203}
204
205
206static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000207zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000208{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 PyThreadState *p;
210 /* No need to lock the mutex here because this should only happen
211 when the threads are all really dead (XXX famous last words). */
212 while ((p = interp->tstate_head) != NULL) {
213 PyThreadState_Delete(p);
214 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000215}
216
217
218void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000219PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000220{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 PyInterpreterState **p;
222 zapthreads(interp);
223 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600224 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 if (*p == NULL)
226 Py_FatalError(
227 "PyInterpreterState_Delete: invalid interp");
228 if (*p == interp)
229 break;
230 }
231 if (interp->tstate_head != NULL)
232 Py_FatalError("PyInterpreterState_Delete: remaining threads");
233 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600234 if (_PyRuntime.interpreters.main == interp) {
235 _PyRuntime.interpreters.main = NULL;
236 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700237 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
238 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200240 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000241}
242
243
Eric Snowe3774162017-05-22 19:46:40 -0700244int64_t
245PyInterpreterState_GetID(PyInterpreterState *interp)
246{
247 if (interp == NULL) {
248 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
249 return -1;
250 }
251 return interp->id;
252}
253
254
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000255/* Default implementation for _PyThreadState_GetFrame */
256static struct _frame *
257threadstate_getframe(PyThreadState *self)
258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000260}
261
Victor Stinner45b9be52010-03-03 23:28:07 +0000262static PyThreadState *
263new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000264{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200265 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 if (_PyThreadState_GetFrame == NULL)
268 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 if (tstate != NULL) {
271 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000273 tstate->frame = NULL;
274 tstate->recursion_depth = 0;
275 tstate->overflowed = 0;
276 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700277 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 tstate->tracing = 0;
279 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 tstate->gilstate_counter = 0;
281 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 tstate->curexc_type = NULL;
287 tstate->curexc_value = NULL;
288 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000289
Mark Shannonae3087c2017-10-22 22:41:51 +0100290 tstate->exc_state.exc_type = NULL;
291 tstate->exc_state.exc_value = NULL;
292 tstate->exc_state.exc_traceback = NULL;
293 tstate->exc_state.previous_item = NULL;
294 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 tstate->c_profilefunc = NULL;
297 tstate->c_tracefunc = NULL;
298 tstate->c_profileobj = NULL;
299 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000300
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200301 tstate->trash_delete_nesting = 0;
302 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200303 tstate->on_delete = NULL;
304 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200305
Yury Selivanov75445082015-05-11 22:57:16 -0400306 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400307 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400308
Yury Selivanoveb636452016-09-08 22:01:51 -0700309 tstate->async_gen_firstiter = NULL;
310 tstate->async_gen_finalizer = NULL;
311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 if (init)
313 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000314
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200316 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200318 if (tstate->next)
319 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 interp->tstate_head = tstate;
321 HEAD_UNLOCK();
322 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000325}
326
Victor Stinner45b9be52010-03-03 23:28:07 +0000327PyThreadState *
328PyThreadState_New(PyInterpreterState *interp)
329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000331}
332
333PyThreadState *
334_PyThreadState_Prealloc(PyInterpreterState *interp)
335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000336 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000337}
338
339void
340_PyThreadState_Init(PyThreadState *tstate)
341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000343}
344
Martin v. Löwis1a214512008-06-11 05:26:20 +0000345PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200346PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000347{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200348 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100349 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000350 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000351 if (module->m_slots) {
352 return NULL;
353 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 if (index == 0)
355 return NULL;
356 if (state->modules_by_index == NULL)
357 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200358 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 return NULL;
360 res = PyList_GET_ITEM(state->modules_by_index, index);
361 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000362}
363
364int
365_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
366{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000367 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300368 if (!def) {
369 assert(PyErr_Occurred());
370 return -1;
371 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000372 if (def->m_slots) {
373 PyErr_SetString(PyExc_SystemError,
374 "PyState_AddModule called on module with slots");
375 return -1;
376 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100377 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 if (!state->modules_by_index) {
379 state->modules_by_index = PyList_New(0);
380 if (!state->modules_by_index)
381 return -1;
382 }
383 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
384 if (PyList_Append(state->modules_by_index, Py_None) < 0)
385 return -1;
386 Py_INCREF(module);
387 return PyList_SetItem(state->modules_by_index,
388 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000389}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000390
Martin v. Löwis7800f752012-06-22 12:20:55 +0200391int
392PyState_AddModule(PyObject* module, struct PyModuleDef* def)
393{
394 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100395 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200396 if (!def) {
397 Py_FatalError("PyState_AddModule: Module Definition is NULL");
398 return -1;
399 }
400 index = def->m_base.m_index;
401 if (state->modules_by_index) {
402 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
403 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
404 Py_FatalError("PyState_AddModule: Module already added!");
405 return -1;
406 }
407 }
408 }
409 return _PyState_AddModule(module, def);
410}
411
412int
413PyState_RemoveModule(struct PyModuleDef* def)
414{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000415 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200416 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000417 if (def->m_slots) {
418 PyErr_SetString(PyExc_SystemError,
419 "PyState_RemoveModule called on module with slots");
420 return -1;
421 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100422 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200423 if (index == 0) {
424 Py_FatalError("PyState_RemoveModule: Module index invalid.");
425 return -1;
426 }
427 if (state->modules_by_index == NULL) {
428 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
429 return -1;
430 }
431 if (index > PyList_GET_SIZE(state->modules_by_index)) {
432 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
433 return -1;
434 }
435 return PyList_SetItem(state->modules_by_index, index, Py_None);
436}
437
Antoine Pitrou40322e62013-08-11 00:30:09 +0200438/* used by import.c:PyImport_Cleanup */
439void
440_PyState_ClearModules(void)
441{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100442 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200443 if (state->modules_by_index) {
444 Py_ssize_t i;
445 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
446 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
447 if (PyModule_Check(m)) {
448 /* cleanup the saved copy of module dicts */
449 PyModuleDef *md = PyModule_GetDef(m);
450 if (md)
451 Py_CLEAR(md->m_base.m_copy);
452 }
453 }
454 /* Setting modules_by_index to NULL could be dangerous, so we
455 clear the list instead. */
456 if (PyList_SetSlice(state->modules_by_index,
457 0, PyList_GET_SIZE(state->modules_by_index),
458 NULL))
459 PyErr_WriteUnraisable(state->modules_by_index);
460 }
461}
462
Guido van Rossuma027efa1997-05-05 20:56:21 +0000463void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000464PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 if (Py_VerboseFlag && tstate->frame != NULL)
467 fprintf(stderr,
468 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 Py_CLEAR(tstate->dict);
473 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 Py_CLEAR(tstate->curexc_type);
476 Py_CLEAR(tstate->curexc_value);
477 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000478
Mark Shannonae3087c2017-10-22 22:41:51 +0100479 Py_CLEAR(tstate->exc_state.exc_type);
480 Py_CLEAR(tstate->exc_state.exc_value);
481 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300482
Mark Shannonae3087c2017-10-22 22:41:51 +0100483 /* The stack of exception states should contain just this thread. */
484 assert(tstate->exc_info->previous_item == NULL);
485 if (Py_VerboseFlag && tstate->exc_info != &tstate->exc_state) {
486 fprintf(stderr,
487 "PyThreadState_Clear: warning: thread still has a generator\n");
488 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 tstate->c_profilefunc = NULL;
491 tstate->c_tracefunc = NULL;
492 Py_CLEAR(tstate->c_profileobj);
493 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400494
495 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700496 Py_CLEAR(tstate->async_gen_firstiter);
497 Py_CLEAR(tstate->async_gen_finalizer);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000498}
499
500
Guido van Rossum29757862001-01-23 01:46:06 +0000501/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
502static void
503tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 if (tstate == NULL)
507 Py_FatalError("PyThreadState_Delete: NULL tstate");
508 interp = tstate->interp;
509 if (interp == NULL)
510 Py_FatalError("PyThreadState_Delete: NULL interp");
511 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200512 if (tstate->prev)
513 tstate->prev->next = tstate->next;
514 else
515 interp->tstate_head = tstate->next;
516 if (tstate->next)
517 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200519 if (tstate->on_delete != NULL) {
520 tstate->on_delete(tstate->on_delete_data);
521 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200522 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000523}
524
525
Guido van Rossum29757862001-01-23 01:46:06 +0000526void
527PyThreadState_Delete(PyThreadState *tstate)
528{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100529 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 Py_FatalError("PyThreadState_Delete: tstate is still current");
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 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200536 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000537}
538
539
Guido van Rossum29757862001-01-23 01:46:06 +0000540void
541PyThreadState_DeleteCurrent()
542{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100543 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 if (tstate == NULL)
545 Py_FatalError(
546 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100547 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600548 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900549 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600550 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900551 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600552 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100553 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000555}
Guido van Rossum29757862001-01-23 01:46:06 +0000556
557
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200558/*
559 * Delete all thread states except the one passed as argument.
560 * Note that, if there is a current thread state, it *must* be the one
561 * passed as argument. Also, this won't touch any other interpreters
562 * than the current one, since we don't know which thread state should
563 * be kept in those other interpreteres.
564 */
565void
566_PyThreadState_DeleteExcept(PyThreadState *tstate)
567{
568 PyInterpreterState *interp = tstate->interp;
569 PyThreadState *p, *next, *garbage;
570 HEAD_LOCK();
571 /* Remove all thread states, except tstate, from the linked list of
572 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200573 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200574 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200575 if (garbage == tstate)
576 garbage = tstate->next;
577 if (tstate->prev)
578 tstate->prev->next = tstate->next;
579 if (tstate->next)
580 tstate->next->prev = tstate->prev;
581 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200582 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200583 HEAD_UNLOCK();
584 /* Clear and deallocate all stale thread states. Even if this
585 executes Python code, we should be safe since it executes
586 in the current thread, not one of the stale threads. */
587 for (p = garbage; p; p = next) {
588 next = p->next;
589 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200590 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200591 }
592}
593
594
Guido van Rossuma027efa1997-05-05 20:56:21 +0000595PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100596_PyThreadState_UncheckedGet(void)
597{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100598 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100599}
600
601
602PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000603PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000604{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100605 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (tstate == NULL)
607 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000610}
611
612
613PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000614PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000615{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100616 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000617
Victor Stinnerb02ef712016-01-22 14:09:55 +0100618 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 /* It should not be possible for more than one thread state
620 to be used for a thread. Check this the best we can in debug
621 builds.
622 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200623#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 if (newts) {
625 /* This can be called from PyEval_RestoreThread(). Similar
626 to it, we need to ensure errno doesn't change.
627 */
628 int err = errno;
629 PyThreadState *check = PyGILState_GetThisThreadState();
630 if (check && check->interp == newts->interp && check != newts)
631 Py_FatalError("Invalid thread state for this thread");
632 errno = err;
633 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000634#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000636}
Guido van Rossumede04391998-04-10 20:18:25 +0000637
638/* An extension mechanism to store arbitrary additional per-thread state.
639 PyThreadState_GetDict() returns a dictionary that can be used to hold such
640 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000641 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
642 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000643
644PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000645PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000646{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100647 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 if (tstate == NULL)
649 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 if (tstate->dict == NULL) {
652 PyObject *d;
653 tstate->dict = d = PyDict_New();
654 if (d == NULL)
655 PyErr_Clear();
656 }
657 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000658}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000659
660
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000661/* Asynchronously raise an exception in a thread.
662 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000663 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000664 to call this, or use ctypes. Must be called with the GIL held.
665 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
666 match any known thread id). Can be called with exc=NULL to clear an
667 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000668
669int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200670PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
671{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100672 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 /* Although the GIL is held, a few C API functions can be called
676 * without the GIL held, and in particular some that create and
677 * destroy thread and interpreter states. Those can mutate the
678 * list of thread states we're traversing, so to prevent that we lock
679 * head_mutex for the duration.
680 */
681 HEAD_LOCK();
682 for (p = interp->tstate_head; p != NULL; p = p->next) {
683 if (p->thread_id == id) {
684 /* Tricky: we need to decref the current value
685 * (if any) in p->async_exc, but that can in turn
686 * allow arbitrary Python code to run, including
687 * perhaps calls to this function. To prevent
688 * deadlock, we need to release head_mutex before
689 * the decref.
690 */
691 PyObject *old_exc = p->async_exc;
692 Py_XINCREF(exc);
693 p->async_exc = exc;
694 HEAD_UNLOCK();
695 Py_XDECREF(old_exc);
696 _PyEval_SignalAsyncExc();
697 return 1;
698 }
699 }
700 HEAD_UNLOCK();
701 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000702}
703
704
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000705/* Routines for advanced debuggers, requested by David Beazley.
706 Don't use unless you know what you are doing! */
707
708PyInterpreterState *
709PyInterpreterState_Head(void)
710{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600711 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000712}
713
714PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700715PyInterpreterState_Main(void)
716{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600717 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700718}
719
720PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000721PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000723}
724
725PyThreadState *
726PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000728}
729
730PyThreadState *
731PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000733}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000734
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000735/* The implementation of sys._current_frames(). This is intended to be
736 called with the GIL held, as it will be when called via
737 sys._current_frames(). It's possible it would work fine even without
738 the GIL held, but haven't thought enough about that.
739*/
740PyObject *
741_PyThread_CurrentFrames(void)
742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 PyObject *result;
744 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 result = PyDict_New();
747 if (result == NULL)
748 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 /* for i in all interpreters:
751 * for t in all of i's thread states:
752 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200753 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 * need to grab head_mutex for the duration.
755 */
756 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600757 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 PyThreadState *t;
759 for (t = i->tstate_head; t != NULL; t = t->next) {
760 PyObject *id;
761 int stat;
762 struct _frame *frame = t->frame;
763 if (frame == NULL)
764 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200765 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 if (id == NULL)
767 goto Fail;
768 stat = PyDict_SetItem(result, id, (PyObject *)frame);
769 Py_DECREF(id);
770 if (stat < 0)
771 goto Fail;
772 }
773 }
774 HEAD_UNLOCK();
775 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000776
777 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 HEAD_UNLOCK();
779 Py_DECREF(result);
780 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000781}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000782
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000783/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000784
785/* Keep this as a static, as it is not reliable! It can only
786 ever be compared to the state for the *current* thread.
787 * If not equal, then it doesn't matter that the actual
788 value may change immediately after comparison, as it can't
789 possibly change to the current thread's state.
790 * If equal, then the current thread holds the lock, so the value can't
791 change until we yield the lock.
792*/
793static int
794PyThreadState_IsCurrent(PyThreadState *tstate)
795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 /* Must be the tstate for this thread */
797 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100798 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000799}
800
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000801/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000802 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000803*/
Tim Peters19717fa2004-10-09 17:38:29 +0000804void
805_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000806{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900808 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
809 Py_FatalError("Could not allocate TSS entry");
810 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600811 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900812 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000816}
817
Victor Stinner861d9ab2016-03-16 22:45:24 +0100818PyInterpreterState *
819_PyGILState_GetInterpreterStateUnsafe(void)
820{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600821 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100822}
823
Tim Peters19717fa2004-10-09 17:38:29 +0000824void
825_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000826{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900827 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600828 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000829}
830
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900831/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200832 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900833 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200834 */
835void
836_PyGILState_Reinit(void)
837{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600838 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
839 if (_PyRuntime.interpreters.mutex == NULL)
840 Py_FatalError("Can't initialize threads for interpreter");
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200841 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900842 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
843 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
844 Py_FatalError("Could not allocate TSS entry");
845 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200846
Charles-François Natalia233df82011-11-22 19:49:51 +0100847 /* If the thread had an associated auto thread state, reassociate it with
848 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900849 if (tstate &&
850 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
851 {
852 Py_FatalError("Couldn't create autoTSSkey mapping");
853 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200854}
855
Michael W. Hudson188d4362005-06-20 16:52:57 +0000856/* When a thread state is created for a thread by some mechanism other than
857 PyGILState_Ensure, it's important that the GILState machinery knows about
858 it so it doesn't try to create another thread state for the thread (this is
859 a better fix for SF bug #1010677 than the first one attempted).
860*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000861static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000862_PyGILState_NoteThreadState(PyThreadState* tstate)
863{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900864 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +0000865 threadstate created in Py_Initialize(). Don't do anything for now
866 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600867 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000869
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900870 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 The only situation where you can legitimately have more than one
873 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100874 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000875
Victor Stinner590cebe2013-12-13 11:08:56 +0100876 You shouldn't really be using the PyGILState_ APIs anyway (see issues
877 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000878
Victor Stinner590cebe2013-12-13 11:08:56 +0100879 The first thread state created for that given OS level thread will
880 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900882 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
883 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
884 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600885 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900886 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600887 }
Victor Stinner590cebe2013-12-13 11:08:56 +0100888 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 /* PyGILState_Release must not try to delete this thread state. */
891 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000892}
893
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000894/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000895PyThreadState *
896PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000897{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600898 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900900 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000901}
902
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700903int
904PyGILState_Check(void)
905{
Victor Stinner8a1be612016-03-14 22:07:55 +0100906 PyThreadState *tstate;
907
908 if (!_PyGILState_check_enabled)
909 return 1;
910
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900911 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +0100912 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900913 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100914
915 tstate = GET_TSTATE();
916 if (tstate == NULL)
917 return 0;
918
919 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700920}
921
Tim Peters19717fa2004-10-09 17:38:29 +0000922PyGILState_STATE
923PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 int current;
926 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100927 int need_init_threads = 0;
928
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 /* Note that we do not auto-init Python here - apart from
930 potential races with 2 threads auto-initializing, pep-311
931 spells out other issues. Embedders are expected to have
932 called Py_Initialize() and usually PyEval_InitThreads().
933 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600934 /* Py_Initialize() hasn't been called! */
935 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100936
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900937 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100939 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +0100940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600942 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 if (tcur == NULL)
944 Py_FatalError("Couldn't create thread-state for new thread");
945 /* This is our thread state! We'll need to delete it in the
946 matching call to PyGILState_Release(). */
947 tcur->gilstate_counter = 0;
948 current = 0; /* new thread state is never current */
949 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100950 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100952 }
953
954 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100956 }
957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 /* Update our counter in the thread-state - no need for locks:
959 - tcur will remain valid as we hold the GIL.
960 - the counter is safe as we are the only thread "allowed"
961 to modify this value
962 */
963 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100964
965 if (need_init_threads) {
966 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
967 called from a new thread for the first time, we need the create the
968 GIL. */
969 PyEval_InitThreads();
970 }
971
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000973}
974
Tim Peters19717fa2004-10-09 17:38:29 +0000975void
976PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000977{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900978 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
979 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 if (tcur == NULL)
981 Py_FatalError("auto-releasing thread-state, "
982 "but no thread-state for this thread");
983 /* We must hold the GIL and have our thread state current */
984 /* XXX - remove the check - the assert should be fine,
985 but while this is very new (April 2003), the extra check
986 by release-only users can't hurt.
987 */
988 if (! PyThreadState_IsCurrent(tcur))
989 Py_FatalError("This thread state must be current when releasing");
990 assert(PyThreadState_IsCurrent(tcur));
991 --tcur->gilstate_counter;
992 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 /* If we're going to destroy this thread-state, we must
995 * clear it while the GIL is held, as destructors may run.
996 */
997 if (tcur->gilstate_counter == 0) {
998 /* can't have been locked when we created it */
999 assert(oldstate == PyGILState_UNLOCKED);
1000 PyThreadState_Clear(tcur);
1001 /* Delete the thread-state. Note this releases the GIL too!
1002 * It's vital that the GIL be held here, to avoid shutdown
1003 * races; see bugs 225673 and 1061968 (that nasty bug has a
1004 * habit of coming back).
1005 */
1006 PyThreadState_DeleteCurrent();
1007 }
1008 /* Release the lock if necessary */
1009 else if (oldstate == PyGILState_UNLOCKED)
1010 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001011}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001012
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001013
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001014#ifdef __cplusplus
1015}
1016#endif