blob: 9c25a26460ea439526c1e2dcc30e07c49b377804 [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
Marcel Plch776407f2017-12-20 11:17:58 +0100156 interp->pyexitfunc = NULL;
157 interp->pyexitmodule = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000158
Victor Stinnerd4341102017-11-23 00:12:09 +0100159 HEAD_LOCK();
160 interp->next = _PyRuntime.interpreters.head;
161 if (_PyRuntime.interpreters.main == NULL) {
162 _PyRuntime.interpreters.main = interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 }
Victor Stinnerd4341102017-11-23 00:12:09 +0100164 _PyRuntime.interpreters.head = interp;
165 if (_PyRuntime.interpreters.next_id < 0) {
166 /* overflow or Py_Initialize() not called! */
167 PyErr_SetString(PyExc_RuntimeError,
168 "failed to get an interpreter ID");
169 interp = NULL;
170 } else {
171 interp->id = _PyRuntime.interpreters.next_id;
172 _PyRuntime.interpreters.next_id += 1;
173 }
174 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000177}
178
179
180void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000181PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 PyThreadState *p;
184 HEAD_LOCK();
185 for (p = interp->tstate_head; p != NULL; p = p->next)
186 PyThreadState_Clear(p);
187 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100188 _PyCoreConfig_Clear(&interp->core_config);
189 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 Py_CLEAR(interp->codec_search_path);
191 Py_CLEAR(interp->codec_search_cache);
192 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700193 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 Py_CLEAR(interp->sysdict);
196 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200197 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400198 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300199 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200200#ifdef HAVE_FORK
201 Py_CLEAR(interp->before_forkers);
202 Py_CLEAR(interp->after_forkers_parent);
203 Py_CLEAR(interp->after_forkers_child);
204#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000205}
206
207
208static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000209zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 PyThreadState *p;
212 /* No need to lock the mutex here because this should only happen
213 when the threads are all really dead (XXX famous last words). */
214 while ((p = interp->tstate_head) != NULL) {
215 PyThreadState_Delete(p);
216 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000217}
218
219
220void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000221PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 PyInterpreterState **p;
224 zapthreads(interp);
225 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600226 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 if (*p == NULL)
228 Py_FatalError(
229 "PyInterpreterState_Delete: invalid interp");
230 if (*p == interp)
231 break;
232 }
233 if (interp->tstate_head != NULL)
234 Py_FatalError("PyInterpreterState_Delete: remaining threads");
235 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600236 if (_PyRuntime.interpreters.main == interp) {
237 _PyRuntime.interpreters.main = NULL;
238 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700239 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
240 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200242 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000243}
244
245
Eric Snowe3774162017-05-22 19:46:40 -0700246int64_t
247PyInterpreterState_GetID(PyInterpreterState *interp)
248{
249 if (interp == NULL) {
250 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
251 return -1;
252 }
253 return interp->id;
254}
255
256
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000257/* Default implementation for _PyThreadState_GetFrame */
258static struct _frame *
259threadstate_getframe(PyThreadState *self)
260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000262}
263
Victor Stinner45b9be52010-03-03 23:28:07 +0000264static PyThreadState *
265new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000266{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200267 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 if (_PyThreadState_GetFrame == NULL)
270 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 if (tstate != NULL) {
273 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 tstate->frame = NULL;
276 tstate->recursion_depth = 0;
277 tstate->overflowed = 0;
278 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700279 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 tstate->tracing = 0;
281 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 tstate->gilstate_counter = 0;
283 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 tstate->curexc_type = NULL;
289 tstate->curexc_value = NULL;
290 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000291
Mark Shannonae3087c2017-10-22 22:41:51 +0100292 tstate->exc_state.exc_type = NULL;
293 tstate->exc_state.exc_value = NULL;
294 tstate->exc_state.exc_traceback = NULL;
295 tstate->exc_state.previous_item = NULL;
296 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 tstate->c_profilefunc = NULL;
299 tstate->c_tracefunc = NULL;
300 tstate->c_profileobj = NULL;
301 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000302
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200303 tstate->trash_delete_nesting = 0;
304 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200305 tstate->on_delete = NULL;
306 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200307
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800308 tstate->coroutine_origin_tracking_depth = 0;
309
Yury Selivanov75445082015-05-11 22:57:16 -0400310 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400311 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400312
Yury Selivanoveb636452016-09-08 22:01:51 -0700313 tstate->async_gen_firstiter = NULL;
314 tstate->async_gen_finalizer = NULL;
315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 if (init)
317 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000318
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000319 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200320 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200322 if (tstate->next)
323 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 interp->tstate_head = tstate;
325 HEAD_UNLOCK();
326 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000329}
330
Victor Stinner45b9be52010-03-03 23:28:07 +0000331PyThreadState *
332PyThreadState_New(PyInterpreterState *interp)
333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000335}
336
337PyThreadState *
338_PyThreadState_Prealloc(PyInterpreterState *interp)
339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000341}
342
343void
344_PyThreadState_Init(PyThreadState *tstate)
345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000347}
348
Martin v. Löwis1a214512008-06-11 05:26:20 +0000349PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200350PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000351{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200352 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100353 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000355 if (module->m_slots) {
356 return NULL;
357 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 if (index == 0)
359 return NULL;
360 if (state->modules_by_index == NULL)
361 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200362 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 return NULL;
364 res = PyList_GET_ITEM(state->modules_by_index, index);
365 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000366}
367
368int
369_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
370{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000371 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300372 if (!def) {
373 assert(PyErr_Occurred());
374 return -1;
375 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000376 if (def->m_slots) {
377 PyErr_SetString(PyExc_SystemError,
378 "PyState_AddModule called on module with slots");
379 return -1;
380 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100381 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 if (!state->modules_by_index) {
383 state->modules_by_index = PyList_New(0);
384 if (!state->modules_by_index)
385 return -1;
386 }
387 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
388 if (PyList_Append(state->modules_by_index, Py_None) < 0)
389 return -1;
390 Py_INCREF(module);
391 return PyList_SetItem(state->modules_by_index,
392 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000393}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000394
Martin v. Löwis7800f752012-06-22 12:20:55 +0200395int
396PyState_AddModule(PyObject* module, struct PyModuleDef* def)
397{
398 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100399 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200400 if (!def) {
401 Py_FatalError("PyState_AddModule: Module Definition is NULL");
402 return -1;
403 }
404 index = def->m_base.m_index;
405 if (state->modules_by_index) {
406 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
407 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
408 Py_FatalError("PyState_AddModule: Module already added!");
409 return -1;
410 }
411 }
412 }
413 return _PyState_AddModule(module, def);
414}
415
416int
417PyState_RemoveModule(struct PyModuleDef* def)
418{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000419 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200420 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000421 if (def->m_slots) {
422 PyErr_SetString(PyExc_SystemError,
423 "PyState_RemoveModule called on module with slots");
424 return -1;
425 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100426 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200427 if (index == 0) {
428 Py_FatalError("PyState_RemoveModule: Module index invalid.");
429 return -1;
430 }
431 if (state->modules_by_index == NULL) {
432 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
433 return -1;
434 }
435 if (index > PyList_GET_SIZE(state->modules_by_index)) {
436 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
437 return -1;
438 }
439 return PyList_SetItem(state->modules_by_index, index, Py_None);
440}
441
Antoine Pitrou40322e62013-08-11 00:30:09 +0200442/* used by import.c:PyImport_Cleanup */
443void
444_PyState_ClearModules(void)
445{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100446 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200447 if (state->modules_by_index) {
448 Py_ssize_t i;
449 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
450 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
451 if (PyModule_Check(m)) {
452 /* cleanup the saved copy of module dicts */
453 PyModuleDef *md = PyModule_GetDef(m);
454 if (md)
455 Py_CLEAR(md->m_base.m_copy);
456 }
457 }
458 /* Setting modules_by_index to NULL could be dangerous, so we
459 clear the list instead. */
460 if (PyList_SetSlice(state->modules_by_index,
461 0, PyList_GET_SIZE(state->modules_by_index),
462 NULL))
463 PyErr_WriteUnraisable(state->modules_by_index);
464 }
465}
466
Guido van Rossuma027efa1997-05-05 20:56:21 +0000467void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000468PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 if (Py_VerboseFlag && tstate->frame != NULL)
471 fprintf(stderr,
472 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 Py_CLEAR(tstate->dict);
477 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 Py_CLEAR(tstate->curexc_type);
480 Py_CLEAR(tstate->curexc_value);
481 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000482
Mark Shannonae3087c2017-10-22 22:41:51 +0100483 Py_CLEAR(tstate->exc_state.exc_type);
484 Py_CLEAR(tstate->exc_state.exc_value);
485 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300486
Mark Shannonae3087c2017-10-22 22:41:51 +0100487 /* The stack of exception states should contain just this thread. */
488 assert(tstate->exc_info->previous_item == NULL);
489 if (Py_VerboseFlag && tstate->exc_info != &tstate->exc_state) {
490 fprintf(stderr,
491 "PyThreadState_Clear: warning: thread still has a generator\n");
492 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 tstate->c_profilefunc = NULL;
495 tstate->c_tracefunc = NULL;
496 Py_CLEAR(tstate->c_profileobj);
497 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400498
499 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700500 Py_CLEAR(tstate->async_gen_firstiter);
501 Py_CLEAR(tstate->async_gen_finalizer);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000502}
503
504
Guido van Rossum29757862001-01-23 01:46:06 +0000505/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
506static void
507tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 if (tstate == NULL)
511 Py_FatalError("PyThreadState_Delete: NULL tstate");
512 interp = tstate->interp;
513 if (interp == NULL)
514 Py_FatalError("PyThreadState_Delete: NULL interp");
515 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200516 if (tstate->prev)
517 tstate->prev->next = tstate->next;
518 else
519 interp->tstate_head = tstate->next;
520 if (tstate->next)
521 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200523 if (tstate->on_delete != NULL) {
524 tstate->on_delete(tstate->on_delete_data);
525 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200526 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000527}
528
529
Guido van Rossum29757862001-01-23 01:46:06 +0000530void
531PyThreadState_Delete(PyThreadState *tstate)
532{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100533 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600535 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900536 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600537 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900538 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600539 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200540 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000541}
542
543
Guido van Rossum29757862001-01-23 01:46:06 +0000544void
545PyThreadState_DeleteCurrent()
546{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100547 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 if (tstate == NULL)
549 Py_FatalError(
550 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100551 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600552 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900553 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600554 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900555 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600556 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100557 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000559}
Guido van Rossum29757862001-01-23 01:46:06 +0000560
561
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200562/*
563 * Delete all thread states except the one passed as argument.
564 * Note that, if there is a current thread state, it *must* be the one
565 * passed as argument. Also, this won't touch any other interpreters
566 * than the current one, since we don't know which thread state should
567 * be kept in those other interpreteres.
568 */
569void
570_PyThreadState_DeleteExcept(PyThreadState *tstate)
571{
572 PyInterpreterState *interp = tstate->interp;
573 PyThreadState *p, *next, *garbage;
574 HEAD_LOCK();
575 /* Remove all thread states, except tstate, from the linked list of
576 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200577 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200578 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200579 if (garbage == tstate)
580 garbage = tstate->next;
581 if (tstate->prev)
582 tstate->prev->next = tstate->next;
583 if (tstate->next)
584 tstate->next->prev = tstate->prev;
585 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200586 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200587 HEAD_UNLOCK();
588 /* Clear and deallocate all stale thread states. Even if this
589 executes Python code, we should be safe since it executes
590 in the current thread, not one of the stale threads. */
591 for (p = garbage; p; p = next) {
592 next = p->next;
593 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200594 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200595 }
596}
597
598
Guido van Rossuma027efa1997-05-05 20:56:21 +0000599PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100600_PyThreadState_UncheckedGet(void)
601{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100602 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100603}
604
605
606PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000607PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000608{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100609 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 if (tstate == NULL)
611 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000614}
615
616
617PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000618PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000619{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100620 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000621
Victor Stinnerb02ef712016-01-22 14:09:55 +0100622 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 /* It should not be possible for more than one thread state
624 to be used for a thread. Check this the best we can in debug
625 builds.
626 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200627#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 if (newts) {
629 /* This can be called from PyEval_RestoreThread(). Similar
630 to it, we need to ensure errno doesn't change.
631 */
632 int err = errno;
633 PyThreadState *check = PyGILState_GetThisThreadState();
634 if (check && check->interp == newts->interp && check != newts)
635 Py_FatalError("Invalid thread state for this thread");
636 errno = err;
637 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000638#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000640}
Guido van Rossumede04391998-04-10 20:18:25 +0000641
642/* An extension mechanism to store arbitrary additional per-thread state.
643 PyThreadState_GetDict() returns a dictionary that can be used to hold such
644 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000645 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
646 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000647
648PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000649PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000650{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100651 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 if (tstate == NULL)
653 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000655 if (tstate->dict == NULL) {
656 PyObject *d;
657 tstate->dict = d = PyDict_New();
658 if (d == NULL)
659 PyErr_Clear();
660 }
661 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000662}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000663
664
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000665/* Asynchronously raise an exception in a thread.
666 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000667 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000668 to call this, or use ctypes. Must be called with the GIL held.
669 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
670 match any known thread id). Can be called with exc=NULL to clear an
671 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000672
673int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200674PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
675{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100676 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 /* Although the GIL is held, a few C API functions can be called
680 * without the GIL held, and in particular some that create and
681 * destroy thread and interpreter states. Those can mutate the
682 * list of thread states we're traversing, so to prevent that we lock
683 * head_mutex for the duration.
684 */
685 HEAD_LOCK();
686 for (p = interp->tstate_head; p != NULL; p = p->next) {
687 if (p->thread_id == id) {
688 /* Tricky: we need to decref the current value
689 * (if any) in p->async_exc, but that can in turn
690 * allow arbitrary Python code to run, including
691 * perhaps calls to this function. To prevent
692 * deadlock, we need to release head_mutex before
693 * the decref.
694 */
695 PyObject *old_exc = p->async_exc;
696 Py_XINCREF(exc);
697 p->async_exc = exc;
698 HEAD_UNLOCK();
699 Py_XDECREF(old_exc);
700 _PyEval_SignalAsyncExc();
701 return 1;
702 }
703 }
704 HEAD_UNLOCK();
705 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000706}
707
708
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000709/* Routines for advanced debuggers, requested by David Beazley.
710 Don't use unless you know what you are doing! */
711
712PyInterpreterState *
713PyInterpreterState_Head(void)
714{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600715 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000716}
717
718PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700719PyInterpreterState_Main(void)
720{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600721 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700722}
723
724PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000725PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000727}
728
729PyThreadState *
730PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000732}
733
734PyThreadState *
735PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000737}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000738
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000739/* The implementation of sys._current_frames(). This is intended to be
740 called with the GIL held, as it will be when called via
741 sys._current_frames(). It's possible it would work fine even without
742 the GIL held, but haven't thought enough about that.
743*/
744PyObject *
745_PyThread_CurrentFrames(void)
746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 PyObject *result;
748 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 result = PyDict_New();
751 if (result == NULL)
752 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 /* for i in all interpreters:
755 * for t in all of i's thread states:
756 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200757 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 * need to grab head_mutex for the duration.
759 */
760 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600761 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 PyThreadState *t;
763 for (t = i->tstate_head; t != NULL; t = t->next) {
764 PyObject *id;
765 int stat;
766 struct _frame *frame = t->frame;
767 if (frame == NULL)
768 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200769 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 if (id == NULL)
771 goto Fail;
772 stat = PyDict_SetItem(result, id, (PyObject *)frame);
773 Py_DECREF(id);
774 if (stat < 0)
775 goto Fail;
776 }
777 }
778 HEAD_UNLOCK();
779 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000780
781 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 HEAD_UNLOCK();
783 Py_DECREF(result);
784 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000785}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000786
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000787/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000788
789/* Keep this as a static, as it is not reliable! It can only
790 ever be compared to the state for the *current* thread.
791 * If not equal, then it doesn't matter that the actual
792 value may change immediately after comparison, as it can't
793 possibly change to the current thread's state.
794 * If equal, then the current thread holds the lock, so the value can't
795 change until we yield the lock.
796*/
797static int
798PyThreadState_IsCurrent(PyThreadState *tstate)
799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 /* Must be the tstate for this thread */
801 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100802 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000803}
804
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000805/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000806 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000807*/
Tim Peters19717fa2004-10-09 17:38:29 +0000808void
809_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000810{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900812 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
813 Py_FatalError("Could not allocate TSS entry");
814 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600815 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900816 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000820}
821
Victor Stinner861d9ab2016-03-16 22:45:24 +0100822PyInterpreterState *
823_PyGILState_GetInterpreterStateUnsafe(void)
824{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600825 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100826}
827
Tim Peters19717fa2004-10-09 17:38:29 +0000828void
829_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000830{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900831 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600832 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000833}
834
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900835/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200836 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900837 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200838 */
839void
840_PyGILState_Reinit(void)
841{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600842 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
843 if (_PyRuntime.interpreters.mutex == NULL)
844 Py_FatalError("Can't initialize threads for interpreter");
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200845 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900846 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
847 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
848 Py_FatalError("Could not allocate TSS entry");
849 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200850
Charles-François Natalia233df82011-11-22 19:49:51 +0100851 /* If the thread had an associated auto thread state, reassociate it with
852 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900853 if (tstate &&
854 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
855 {
856 Py_FatalError("Couldn't create autoTSSkey mapping");
857 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200858}
859
Michael W. Hudson188d4362005-06-20 16:52:57 +0000860/* When a thread state is created for a thread by some mechanism other than
861 PyGILState_Ensure, it's important that the GILState machinery knows about
862 it so it doesn't try to create another thread state for the thread (this is
863 a better fix for SF bug #1010677 than the first one attempted).
864*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000865static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000866_PyGILState_NoteThreadState(PyThreadState* tstate)
867{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900868 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +0000869 threadstate created in Py_Initialize(). Don't do anything for now
870 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600871 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000873
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900874 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 The only situation where you can legitimately have more than one
877 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100878 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000879
Victor Stinner590cebe2013-12-13 11:08:56 +0100880 You shouldn't really be using the PyGILState_ APIs anyway (see issues
881 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000882
Victor Stinner590cebe2013-12-13 11:08:56 +0100883 The first thread state created for that given OS level thread will
884 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000885 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900886 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
887 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
888 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600889 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900890 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600891 }
Victor Stinner590cebe2013-12-13 11:08:56 +0100892 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 /* PyGILState_Release must not try to delete this thread state. */
895 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000896}
897
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000898/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000899PyThreadState *
900PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000901{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600902 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900904 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000905}
906
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700907int
908PyGILState_Check(void)
909{
Victor Stinner8a1be612016-03-14 22:07:55 +0100910 PyThreadState *tstate;
911
912 if (!_PyGILState_check_enabled)
913 return 1;
914
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900915 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +0100916 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900917 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100918
919 tstate = GET_TSTATE();
920 if (tstate == NULL)
921 return 0;
922
923 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700924}
925
Tim Peters19717fa2004-10-09 17:38:29 +0000926PyGILState_STATE
927PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 int current;
930 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100931 int need_init_threads = 0;
932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 /* Note that we do not auto-init Python here - apart from
934 potential races with 2 threads auto-initializing, pep-311
935 spells out other issues. Embedders are expected to have
936 called Py_Initialize() and usually PyEval_InitThreads().
937 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600938 /* Py_Initialize() hasn't been called! */
939 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100940
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900941 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100943 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +0100944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600946 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 if (tcur == NULL)
948 Py_FatalError("Couldn't create thread-state for new thread");
949 /* This is our thread state! We'll need to delete it in the
950 matching call to PyGILState_Release(). */
951 tcur->gilstate_counter = 0;
952 current = 0; /* new thread state is never current */
953 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100954 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100956 }
957
958 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100960 }
961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 /* Update our counter in the thread-state - no need for locks:
963 - tcur will remain valid as we hold the GIL.
964 - the counter is safe as we are the only thread "allowed"
965 to modify this value
966 */
967 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100968
969 if (need_init_threads) {
970 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
971 called from a new thread for the first time, we need the create the
972 GIL. */
973 PyEval_InitThreads();
974 }
975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000977}
978
Tim Peters19717fa2004-10-09 17:38:29 +0000979void
980PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000981{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900982 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
983 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 if (tcur == NULL)
985 Py_FatalError("auto-releasing thread-state, "
986 "but no thread-state for this thread");
987 /* We must hold the GIL and have our thread state current */
988 /* XXX - remove the check - the assert should be fine,
989 but while this is very new (April 2003), the extra check
990 by release-only users can't hurt.
991 */
992 if (! PyThreadState_IsCurrent(tcur))
993 Py_FatalError("This thread state must be current when releasing");
994 assert(PyThreadState_IsCurrent(tcur));
995 --tcur->gilstate_counter;
996 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 /* If we're going to destroy this thread-state, we must
999 * clear it while the GIL is held, as destructors may run.
1000 */
1001 if (tcur->gilstate_counter == 0) {
1002 /* can't have been locked when we created it */
1003 assert(oldstate == PyGILState_UNLOCKED);
1004 PyThreadState_Clear(tcur);
1005 /* Delete the thread-state. Note this releases the GIL too!
1006 * It's vital that the GIL be held here, to avoid shutdown
1007 * races; see bugs 225673 and 1061968 (that nasty bug has a
1008 * habit of coming back).
1009 */
1010 PyThreadState_DeleteCurrent();
1011 }
1012 /* Release the lock if necessary */
1013 else if (oldstate == PyGILState_UNLOCKED)
1014 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001015}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001016
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001017
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001018#ifdef __cplusplus
1019}
1020#endif