blob: a56e3089694ec588a2fca1c4ff86b3350758628d [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"
5
Tim Peters84705582004-10-10 02:47:33 +00006/* --------------------------------------------------------------------------
7CAUTION
8
Victor Stinner1a7425f2013-07-07 16:25:15 +02009Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
10number of these functions are advertised as safe to call when the GIL isn't
11held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
12debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
13to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000014-------------------------------------------------------------------------- */
15
Martin v. Löwisf0473d52001-07-18 16:17:16 +000016#ifdef HAVE_DLOPEN
17#ifdef HAVE_DLFCN_H
18#include <dlfcn.h>
19#endif
20#ifndef RTLD_LAZY
21#define RTLD_LAZY 1
22#endif
23#endif
24
Benjamin Peterson43162b82012-04-13 11:58:27 -040025#ifdef __cplusplus
26extern "C" {
27#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000028
Guido van Rossum1d5ad901999-06-18 14:22:24 +000029#ifdef WITH_THREAD
30#include "pythread.h"
31static PyThread_type_lock head_mutex = NULL; /* Protects interp->tstate_head */
Moshe Zadka9fb6af92000-08-04 21:27:47 +000032#define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock()))
Guido van Rossum1d5ad901999-06-18 14:22:24 +000033#define HEAD_LOCK() PyThread_acquire_lock(head_mutex, WAIT_LOCK)
34#define HEAD_UNLOCK() PyThread_release_lock(head_mutex)
Michael W. Hudson188d4362005-06-20 16:52:57 +000035
36/* The single PyInterpreterState used by this process'
37 GILState implementation
38*/
39static PyInterpreterState *autoInterpreterState = NULL;
40static int autoTLSkey = 0;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000041#else
42#define HEAD_INIT() /* Nothing */
43#define HEAD_LOCK() /* Nothing */
44#define HEAD_UNLOCK() /* Nothing */
45#endif
46
Guido van Rossum25ce5661997-08-02 03:10:38 +000047static PyInterpreterState *interp_head = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +000048
Jeffrey Yasskin39370832010-05-03 19:29:34 +000049/* Assuming the current thread holds the GIL, this is the
50 PyThreadState for the current thread. */
51_Py_atomic_address _PyThreadState_Current = {NULL};
Guido van Rossum6297a7a2003-02-19 15:53:17 +000052PyThreadFrameGetter _PyThreadState_GetFrame = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +000053
Michael W. Hudsonce7da6c2005-09-30 08:20:24 +000054#ifdef WITH_THREAD
Michael W. Hudson188d4362005-06-20 16:52:57 +000055static void _PyGILState_NoteThreadState(PyThreadState* tstate);
Michael W. Hudsonce7da6c2005-09-30 08:20:24 +000056#endif
Michael W. Hudson188d4362005-06-20 16:52:57 +000057
Guido van Rossuma027efa1997-05-05 20:56:21 +000058
59PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000060PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +000061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +020063 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +000064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 if (interp != NULL) {
66 HEAD_INIT();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000067#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000068 if (head_mutex == NULL)
69 Py_FatalError("Can't initialize threads for interpreter");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000070#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 interp->modules_by_index = NULL;
73 interp->sysdict = NULL;
74 interp->builtins = NULL;
75 interp->tstate_head = NULL;
76 interp->codec_search_path = NULL;
77 interp->codec_search_cache = NULL;
78 interp->codec_error_registry = NULL;
79 interp->codecs_initialized = 0;
Victor Stinner3cbf14b2011-04-27 00:24:21 +020080 interp->fscodec_initialized = 0;
Brett Cannonfd074152012-04-14 14:10:13 -040081 interp->importlib = NULL;
Martin v. Löwisf0473d52001-07-18 16:17:16 +000082#ifdef HAVE_DLOPEN
83#ifdef RTLD_NOW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +000085#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +000087#endif
88#endif
Martin v. Löwisf30d60e2004-06-08 08:17:44 +000089#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000090 interp->tscdump = 0;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +000091#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +000092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 HEAD_LOCK();
94 interp->next = interp_head;
95 interp_head = interp;
96 HEAD_UNLOCK();
97 }
Guido van Rossum25ce5661997-08-02 03:10:38 +000098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000100}
101
102
103void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000104PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 PyThreadState *p;
107 HEAD_LOCK();
108 for (p = interp->tstate_head; p != NULL; p = p->next)
109 PyThreadState_Clear(p);
110 HEAD_UNLOCK();
111 Py_CLEAR(interp->codec_search_path);
112 Py_CLEAR(interp->codec_search_cache);
113 Py_CLEAR(interp->codec_error_registry);
114 Py_CLEAR(interp->modules);
115 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 Py_CLEAR(interp->sysdict);
117 Py_CLEAR(interp->builtins);
Brett Cannonfd074152012-04-14 14:10:13 -0400118 Py_CLEAR(interp->importlib);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000119}
120
121
122static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000123zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000125 PyThreadState *p;
126 /* No need to lock the mutex here because this should only happen
127 when the threads are all really dead (XXX famous last words). */
128 while ((p = interp->tstate_head) != NULL) {
129 PyThreadState_Delete(p);
130 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000131}
132
133
134void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000135PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 PyInterpreterState **p;
138 zapthreads(interp);
139 HEAD_LOCK();
140 for (p = &interp_head; ; p = &(*p)->next) {
141 if (*p == NULL)
142 Py_FatalError(
143 "PyInterpreterState_Delete: invalid interp");
144 if (*p == interp)
145 break;
146 }
147 if (interp->tstate_head != NULL)
148 Py_FatalError("PyInterpreterState_Delete: remaining threads");
149 *p = interp->next;
150 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200151 PyMem_RawFree(interp);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100152#ifdef WITH_THREAD
153 if (interp_head == NULL && head_mutex != NULL) {
154 PyThread_free_lock(head_mutex);
155 head_mutex = NULL;
156 }
157#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +0000158}
159
160
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000161/* Default implementation for _PyThreadState_GetFrame */
162static struct _frame *
163threadstate_getframe(PyThreadState *self)
164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000166}
167
Victor Stinner45b9be52010-03-03 23:28:07 +0000168static PyThreadState *
169new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000170{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200171 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 if (_PyThreadState_GetFrame == NULL)
174 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000176 if (tstate != NULL) {
177 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 tstate->frame = NULL;
180 tstate->recursion_depth = 0;
181 tstate->overflowed = 0;
182 tstate->recursion_critical = 0;
183 tstate->tracing = 0;
184 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 tstate->gilstate_counter = 0;
186 tstate->async_exc = NULL;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000187#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 tstate->thread_id = PyThread_get_thread_ident();
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000189#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 tstate->thread_id = 0;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000191#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 tstate->curexc_type = NULL;
196 tstate->curexc_value = NULL;
197 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 tstate->exc_type = NULL;
200 tstate->exc_value = NULL;
201 tstate->exc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 tstate->c_profilefunc = NULL;
204 tstate->c_tracefunc = NULL;
205 tstate->c_profileobj = NULL;
206 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000207
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200208 tstate->trash_delete_nesting = 0;
209 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200210 tstate->on_delete = NULL;
211 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 if (init)
214 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200217 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200219 if (tstate->next)
220 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 interp->tstate_head = tstate;
222 HEAD_UNLOCK();
223 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000226}
227
Victor Stinner45b9be52010-03-03 23:28:07 +0000228PyThreadState *
229PyThreadState_New(PyInterpreterState *interp)
230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000232}
233
234PyThreadState *
235_PyThreadState_Prealloc(PyInterpreterState *interp)
236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000238}
239
240void
241_PyThreadState_Init(PyThreadState *tstate)
242{
243#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000245#endif
246}
247
Martin v. Löwis1a214512008-06-11 05:26:20 +0000248PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200249PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000250{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200251 Py_ssize_t index = module->m_base.m_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 PyInterpreterState *state = PyThreadState_GET()->interp;
253 PyObject *res;
254 if (index == 0)
255 return NULL;
256 if (state->modules_by_index == NULL)
257 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200258 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 return NULL;
260 res = PyList_GET_ITEM(state->modules_by_index, index);
261 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000262}
263
264int
265_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 PyInterpreterState *state = PyThreadState_GET()->interp;
268 if (!def)
269 return -1;
270 if (!state->modules_by_index) {
271 state->modules_by_index = PyList_New(0);
272 if (!state->modules_by_index)
273 return -1;
274 }
275 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
276 if (PyList_Append(state->modules_by_index, Py_None) < 0)
277 return -1;
278 Py_INCREF(module);
279 return PyList_SetItem(state->modules_by_index,
280 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000281}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000282
Martin v. Löwis7800f752012-06-22 12:20:55 +0200283int
284PyState_AddModule(PyObject* module, struct PyModuleDef* def)
285{
286 Py_ssize_t index;
287 PyInterpreterState *state = PyThreadState_GET()->interp;
288 if (!def) {
289 Py_FatalError("PyState_AddModule: Module Definition is NULL");
290 return -1;
291 }
292 index = def->m_base.m_index;
293 if (state->modules_by_index) {
294 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
295 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
296 Py_FatalError("PyState_AddModule: Module already added!");
297 return -1;
298 }
299 }
300 }
301 return _PyState_AddModule(module, def);
302}
303
304int
305PyState_RemoveModule(struct PyModuleDef* def)
306{
307 Py_ssize_t index = def->m_base.m_index;
308 PyInterpreterState *state = PyThreadState_GET()->interp;
309 if (index == 0) {
310 Py_FatalError("PyState_RemoveModule: Module index invalid.");
311 return -1;
312 }
313 if (state->modules_by_index == NULL) {
314 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
315 return -1;
316 }
317 if (index > PyList_GET_SIZE(state->modules_by_index)) {
318 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
319 return -1;
320 }
321 return PyList_SetItem(state->modules_by_index, index, Py_None);
322}
323
Antoine Pitrou40322e62013-08-11 00:30:09 +0200324/* used by import.c:PyImport_Cleanup */
325void
326_PyState_ClearModules(void)
327{
328 PyInterpreterState *state = PyThreadState_GET()->interp;
329 if (state->modules_by_index) {
330 Py_ssize_t i;
331 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
332 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
333 if (PyModule_Check(m)) {
334 /* cleanup the saved copy of module dicts */
335 PyModuleDef *md = PyModule_GetDef(m);
336 if (md)
337 Py_CLEAR(md->m_base.m_copy);
338 }
339 }
340 /* Setting modules_by_index to NULL could be dangerous, so we
341 clear the list instead. */
342 if (PyList_SetSlice(state->modules_by_index,
343 0, PyList_GET_SIZE(state->modules_by_index),
344 NULL))
345 PyErr_WriteUnraisable(state->modules_by_index);
346 }
347}
348
Guido van Rossuma027efa1997-05-05 20:56:21 +0000349void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000350PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 if (Py_VerboseFlag && tstate->frame != NULL)
353 fprintf(stderr,
354 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 Py_CLEAR(tstate->dict);
359 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 Py_CLEAR(tstate->curexc_type);
362 Py_CLEAR(tstate->curexc_value);
363 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 Py_CLEAR(tstate->exc_type);
366 Py_CLEAR(tstate->exc_value);
367 Py_CLEAR(tstate->exc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000368
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 tstate->c_profilefunc = NULL;
370 tstate->c_tracefunc = NULL;
371 Py_CLEAR(tstate->c_profileobj);
372 Py_CLEAR(tstate->c_traceobj);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000373}
374
375
Guido van Rossum29757862001-01-23 01:46:06 +0000376/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
377static void
378tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 if (tstate == NULL)
382 Py_FatalError("PyThreadState_Delete: NULL tstate");
383 interp = tstate->interp;
384 if (interp == NULL)
385 Py_FatalError("PyThreadState_Delete: NULL interp");
386 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200387 if (tstate->prev)
388 tstate->prev->next = tstate->next;
389 else
390 interp->tstate_head = tstate->next;
391 if (tstate->next)
392 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200394 if (tstate->on_delete != NULL) {
395 tstate->on_delete(tstate->on_delete_data);
396 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200397 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000398}
399
400
Guido van Rossum29757862001-01-23 01:46:06 +0000401void
402PyThreadState_Delete(PyThreadState *tstate)
403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 if (tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current))
405 Py_FatalError("PyThreadState_Delete: tstate is still current");
Tim Petersf4e69282006-02-27 17:15:31 +0000406#ifdef WITH_THREAD
Antoine Pitrou079ce542010-09-08 12:37:10 +0000407 if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 PyThread_delete_key_value(autoTLSkey);
Tim Petersf4e69282006-02-27 17:15:31 +0000409#endif /* WITH_THREAD */
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200410 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000411}
412
413
414#ifdef WITH_THREAD
415void
416PyThreadState_DeleteCurrent()
417{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
419 &_PyThreadState_Current);
420 if (tstate == NULL)
421 Py_FatalError(
422 "PyThreadState_DeleteCurrent: no current tstate");
423 _Py_atomic_store_relaxed(&_PyThreadState_Current, NULL);
Antoine Pitrou079ce542010-09-08 12:37:10 +0000424 if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 PyThread_delete_key_value(autoTLSkey);
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200426 tstate_delete_common(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000428}
429#endif /* WITH_THREAD */
430
431
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200432/*
433 * Delete all thread states except the one passed as argument.
434 * Note that, if there is a current thread state, it *must* be the one
435 * passed as argument. Also, this won't touch any other interpreters
436 * than the current one, since we don't know which thread state should
437 * be kept in those other interpreteres.
438 */
439void
440_PyThreadState_DeleteExcept(PyThreadState *tstate)
441{
442 PyInterpreterState *interp = tstate->interp;
443 PyThreadState *p, *next, *garbage;
444 HEAD_LOCK();
445 /* Remove all thread states, except tstate, from the linked list of
446 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200447 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200448 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200449 if (garbage == tstate)
450 garbage = tstate->next;
451 if (tstate->prev)
452 tstate->prev->next = tstate->next;
453 if (tstate->next)
454 tstate->next->prev = tstate->prev;
455 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200456 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200457 HEAD_UNLOCK();
458 /* Clear and deallocate all stale thread states. Even if this
459 executes Python code, we should be safe since it executes
460 in the current thread, not one of the stale threads. */
461 for (p = garbage; p; p = next) {
462 next = p->next;
463 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200464 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200465 }
466}
467
468
Guido van Rossuma027efa1997-05-05 20:56:21 +0000469PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000470PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
473 &_PyThreadState_Current);
474 if (tstate == NULL)
475 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000478}
479
480
481PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000482PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 PyThreadState *oldts = (PyThreadState*)_Py_atomic_load_relaxed(
485 &_PyThreadState_Current);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 _Py_atomic_store_relaxed(&_PyThreadState_Current, newts);
488 /* It should not be possible for more than one thread state
489 to be used for a thread. Check this the best we can in debug
490 builds.
491 */
Martin v. Löwis9e296252003-05-01 05:25:29 +0000492#if defined(Py_DEBUG) && defined(WITH_THREAD)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (newts) {
494 /* This can be called from PyEval_RestoreThread(). Similar
495 to it, we need to ensure errno doesn't change.
496 */
497 int err = errno;
498 PyThreadState *check = PyGILState_GetThisThreadState();
499 if (check && check->interp == newts->interp && check != newts)
500 Py_FatalError("Invalid thread state for this thread");
501 errno = err;
502 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000503#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000505}
Guido van Rossumede04391998-04-10 20:18:25 +0000506
507/* An extension mechanism to store arbitrary additional per-thread state.
508 PyThreadState_GetDict() returns a dictionary that can be used to hold such
509 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000510 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
511 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000512
513PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000514PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
517 &_PyThreadState_Current);
518 if (tstate == NULL)
519 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (tstate->dict == NULL) {
522 PyObject *d;
523 tstate->dict = d = PyDict_New();
524 if (d == NULL)
525 PyErr_Clear();
526 }
527 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000528}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000529
530
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000531/* Asynchronously raise an exception in a thread.
532 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000533 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000534 to call this, or use ctypes. Must be called with the GIL held.
535 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
536 match any known thread id). Can be called with exc=NULL to clear an
537 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000538
539int
540PyThreadState_SetAsyncExc(long id, PyObject *exc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 PyThreadState *tstate = PyThreadState_GET();
542 PyInterpreterState *interp = tstate->interp;
543 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 /* Although the GIL is held, a few C API functions can be called
546 * without the GIL held, and in particular some that create and
547 * destroy thread and interpreter states. Those can mutate the
548 * list of thread states we're traversing, so to prevent that we lock
549 * head_mutex for the duration.
550 */
551 HEAD_LOCK();
552 for (p = interp->tstate_head; p != NULL; p = p->next) {
553 if (p->thread_id == id) {
554 /* Tricky: we need to decref the current value
555 * (if any) in p->async_exc, but that can in turn
556 * allow arbitrary Python code to run, including
557 * perhaps calls to this function. To prevent
558 * deadlock, we need to release head_mutex before
559 * the decref.
560 */
561 PyObject *old_exc = p->async_exc;
562 Py_XINCREF(exc);
563 p->async_exc = exc;
564 HEAD_UNLOCK();
565 Py_XDECREF(old_exc);
566 _PyEval_SignalAsyncExc();
567 return 1;
568 }
569 }
570 HEAD_UNLOCK();
571 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000572}
573
574
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000575/* Routines for advanced debuggers, requested by David Beazley.
576 Don't use unless you know what you are doing! */
577
578PyInterpreterState *
579PyInterpreterState_Head(void)
580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 return interp_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000582}
583
584PyInterpreterState *
585PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000587}
588
589PyThreadState *
590PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000592}
593
594PyThreadState *
595PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000597}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000598
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000599/* The implementation of sys._current_frames(). This is intended to be
600 called with the GIL held, as it will be when called via
601 sys._current_frames(). It's possible it would work fine even without
602 the GIL held, but haven't thought enough about that.
603*/
604PyObject *
605_PyThread_CurrentFrames(void)
606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 PyObject *result;
608 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 result = PyDict_New();
611 if (result == NULL)
612 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 /* for i in all interpreters:
615 * for t in all of i's thread states:
616 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200617 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 * need to grab head_mutex for the duration.
619 */
620 HEAD_LOCK();
621 for (i = interp_head; i != NULL; i = i->next) {
622 PyThreadState *t;
623 for (t = i->tstate_head; t != NULL; t = t->next) {
624 PyObject *id;
625 int stat;
626 struct _frame *frame = t->frame;
627 if (frame == NULL)
628 continue;
629 id = PyLong_FromLong(t->thread_id);
630 if (id == NULL)
631 goto Fail;
632 stat = PyDict_SetItem(result, id, (PyObject *)frame);
633 Py_DECREF(id);
634 if (stat < 0)
635 goto Fail;
636 }
637 }
638 HEAD_UNLOCK();
639 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000640
641 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 HEAD_UNLOCK();
643 Py_DECREF(result);
644 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000645}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000646
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000647/* Python "auto thread state" API. */
648#ifdef WITH_THREAD
649
650/* Keep this as a static, as it is not reliable! It can only
651 ever be compared to the state for the *current* thread.
652 * If not equal, then it doesn't matter that the actual
653 value may change immediately after comparison, as it can't
654 possibly change to the current thread's state.
655 * If equal, then the current thread holds the lock, so the value can't
656 change until we yield the lock.
657*/
658static int
659PyThreadState_IsCurrent(PyThreadState *tstate)
660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 /* Must be the tstate for this thread */
662 assert(PyGILState_GetThisThreadState()==tstate);
663 return tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000664}
665
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000666/* Internal initialization/finalization functions called by
667 Py_Initialize/Py_Finalize
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000668*/
Tim Peters19717fa2004-10-09 17:38:29 +0000669void
670_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 assert(i && t); /* must init with valid states */
673 autoTLSkey = PyThread_create_key();
Kristján Valur Jónsson2fea9b92010-09-20 02:11:49 +0000674 if (autoTLSkey == -1)
675 Py_FatalError("Could not allocate TLS entry");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 autoInterpreterState = i;
677 assert(PyThread_get_key_value(autoTLSkey) == NULL);
678 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000681}
682
Tim Peters19717fa2004-10-09 17:38:29 +0000683void
684_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 PyThread_delete_key(autoTLSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000688}
689
Charles-François Natalia233df82011-11-22 19:49:51 +0100690/* Reset the TLS key - called by PyOS_AfterFork().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200691 * This should not be necessary, but some - buggy - pthread implementations
Charles-François Natalia233df82011-11-22 19:49:51 +0100692 * don't reset TLS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200693 */
694void
695_PyGILState_Reinit(void)
696{
697 PyThreadState *tstate = PyGILState_GetThisThreadState();
698 PyThread_delete_key(autoTLSkey);
699 if ((autoTLSkey = PyThread_create_key()) == -1)
700 Py_FatalError("Could not allocate TLS entry");
701
Charles-François Natalia233df82011-11-22 19:49:51 +0100702 /* If the thread had an associated auto thread state, reassociate it with
703 * the new key. */
704 if (tstate && PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200705 Py_FatalError("Couldn't create autoTLSkey mapping");
706}
707
Michael W. Hudson188d4362005-06-20 16:52:57 +0000708/* When a thread state is created for a thread by some mechanism other than
709 PyGILState_Ensure, it's important that the GILState machinery knows about
710 it so it doesn't try to create another thread state for the thread (this is
711 a better fix for SF bug #1010677 than the first one attempted).
712*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000713static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000714_PyGILState_NoteThreadState(PyThreadState* tstate)
715{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000716 /* If autoTLSkey isn't initialized, this must be the very first
717 threadstate created in Py_Initialize(). Don't do anything for now
718 (we'll be back here when _PyGILState_Init is called). */
719 if (!autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 /* Stick the thread state for this thread in thread local storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 The only situation where you can legitimately have more than one
725 thread state for an OS level thread is when there are multiple
726 interpreters, when:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 a) You shouldn't really be using the PyGILState_ APIs anyway,
729 and:
Michael W. Hudson188d4362005-06-20 16:52:57 +0000730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 b) The slightly odd way PyThread_set_key_value works (see
732 comments by its implementation) means that the first thread
733 state created for that given OS level thread will "win",
734 which seems reasonable behaviour.
735 */
736 if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
737 Py_FatalError("Couldn't create autoTLSkey mapping");
Michael W. Hudson188d4362005-06-20 16:52:57 +0000738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 /* PyGILState_Release must not try to delete this thread state. */
740 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000741}
742
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000743/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000744PyThreadState *
745PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000746{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000747 if (autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 return NULL;
749 return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000750}
751
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700752int
753PyGILState_Check(void)
754{
755 /* can't use PyThreadState_Get() since it will assert that it has the GIL */
756 PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
757 &_PyThreadState_Current);
758 return tstate && (tstate == PyGILState_GetThisThreadState());
759}
760
Tim Peters19717fa2004-10-09 17:38:29 +0000761PyGILState_STATE
762PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000764 int current;
765 PyThreadState *tcur;
766 /* Note that we do not auto-init Python here - apart from
767 potential races with 2 threads auto-initializing, pep-311
768 spells out other issues. Embedders are expected to have
769 called Py_Initialize() and usually PyEval_InitThreads().
770 */
771 assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */
772 tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey);
773 if (tcur == NULL) {
Victor Stinner62ca1002013-12-13 01:46:43 +0100774 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
775 called from a new thread for the first time, we need the create the
776 GIL. */
777 PyEval_InitThreads();
778
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 /* Create a new thread state for this thread */
780 tcur = PyThreadState_New(autoInterpreterState);
781 if (tcur == NULL)
782 Py_FatalError("Couldn't create thread-state for new thread");
783 /* This is our thread state! We'll need to delete it in the
784 matching call to PyGILState_Release(). */
785 tcur->gilstate_counter = 0;
786 current = 0; /* new thread state is never current */
787 }
788 else
789 current = PyThreadState_IsCurrent(tcur);
790 if (current == 0)
791 PyEval_RestoreThread(tcur);
792 /* Update our counter in the thread-state - no need for locks:
793 - tcur will remain valid as we hold the GIL.
794 - the counter is safe as we are the only thread "allowed"
795 to modify this value
796 */
797 ++tcur->gilstate_counter;
798 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000799}
800
Tim Peters19717fa2004-10-09 17:38:29 +0000801void
802PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
805 autoTLSkey);
806 if (tcur == NULL)
807 Py_FatalError("auto-releasing thread-state, "
808 "but no thread-state for this thread");
809 /* We must hold the GIL and have our thread state current */
810 /* XXX - remove the check - the assert should be fine,
811 but while this is very new (April 2003), the extra check
812 by release-only users can't hurt.
813 */
814 if (! PyThreadState_IsCurrent(tcur))
815 Py_FatalError("This thread state must be current when releasing");
816 assert(PyThreadState_IsCurrent(tcur));
817 --tcur->gilstate_counter;
818 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000819
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 /* If we're going to destroy this thread-state, we must
821 * clear it while the GIL is held, as destructors may run.
822 */
823 if (tcur->gilstate_counter == 0) {
824 /* can't have been locked when we created it */
825 assert(oldstate == PyGILState_UNLOCKED);
826 PyThreadState_Clear(tcur);
827 /* Delete the thread-state. Note this releases the GIL too!
828 * It's vital that the GIL be held here, to avoid shutdown
829 * races; see bugs 225673 and 1061968 (that nasty bug has a
830 * habit of coming back).
831 */
832 PyThreadState_DeleteCurrent();
833 }
834 /* Release the lock if necessary */
835 else if (oldstate == PyGILState_UNLOCKED)
836 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000837}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000838
Benjamin Peterson3bf01752012-04-13 18:06:36 -0400839#endif /* WITH_THREAD */
840
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000841#ifdef __cplusplus
842}
843#endif
844
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000845