blob: cf08a2b4c633f2ec82331435144b925fe4d8293c [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
9Always use malloc() and free() directly in this file. A number of these
10functions are advertised as safe to call when the GIL isn't held, and in
11a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's debugging
12obmalloc functions. Those aren't thread-safe (they rely on the GIL to avoid
13the expense of doing their own locking).
14-------------------------------------------------------------------------- */
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 *)
63 malloc(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();
151 free(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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 PyThreadState *tstate = (PyThreadState *)malloc(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;
185 tstate->tick_counter = 0;
186 tstate->gilstate_counter = 0;
187 tstate->async_exc = NULL;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000188#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000189 tstate->thread_id = PyThread_get_thread_ident();
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000190#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 tstate->thread_id = 0;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000192#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 tstate->curexc_type = NULL;
197 tstate->curexc_value = NULL;
198 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 tstate->exc_type = NULL;
201 tstate->exc_value = NULL;
202 tstate->exc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 tstate->c_profilefunc = NULL;
205 tstate->c_tracefunc = NULL;
206 tstate->c_profileobj = NULL;
207 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 if (init)
210 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 HEAD_LOCK();
213 tstate->next = interp->tstate_head;
214 interp->tstate_head = tstate;
215 HEAD_UNLOCK();
216 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000219}
220
Victor Stinner45b9be52010-03-03 23:28:07 +0000221PyThreadState *
222PyThreadState_New(PyInterpreterState *interp)
223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000225}
226
227PyThreadState *
228_PyThreadState_Prealloc(PyInterpreterState *interp)
229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000231}
232
233void
234_PyThreadState_Init(PyThreadState *tstate)
235{
236#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000238#endif
239}
240
Martin v. Löwis1a214512008-06-11 05:26:20 +0000241PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200242PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000243{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200244 Py_ssize_t index = module->m_base.m_index;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 PyInterpreterState *state = PyThreadState_GET()->interp;
246 PyObject *res;
247 if (index == 0)
248 return NULL;
249 if (state->modules_by_index == NULL)
250 return NULL;
251 if (index > PyList_GET_SIZE(state->modules_by_index))
252 return NULL;
253 res = PyList_GET_ITEM(state->modules_by_index, index);
254 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000255}
256
257int
258_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 PyInterpreterState *state = PyThreadState_GET()->interp;
261 if (!def)
262 return -1;
263 if (!state->modules_by_index) {
264 state->modules_by_index = PyList_New(0);
265 if (!state->modules_by_index)
266 return -1;
267 }
268 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
269 if (PyList_Append(state->modules_by_index, Py_None) < 0)
270 return -1;
271 Py_INCREF(module);
272 return PyList_SetItem(state->modules_by_index,
273 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000274}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000275
Martin v. Löwis7800f752012-06-22 12:20:55 +0200276int
277PyState_AddModule(PyObject* module, struct PyModuleDef* def)
278{
279 Py_ssize_t index;
280 PyInterpreterState *state = PyThreadState_GET()->interp;
281 if (!def) {
282 Py_FatalError("PyState_AddModule: Module Definition is NULL");
283 return -1;
284 }
285 index = def->m_base.m_index;
286 if (state->modules_by_index) {
287 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
288 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
289 Py_FatalError("PyState_AddModule: Module already added!");
290 return -1;
291 }
292 }
293 }
294 return _PyState_AddModule(module, def);
295}
296
297int
298PyState_RemoveModule(struct PyModuleDef* def)
299{
300 Py_ssize_t index = def->m_base.m_index;
301 PyInterpreterState *state = PyThreadState_GET()->interp;
302 if (index == 0) {
303 Py_FatalError("PyState_RemoveModule: Module index invalid.");
304 return -1;
305 }
306 if (state->modules_by_index == NULL) {
307 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
308 return -1;
309 }
310 if (index > PyList_GET_SIZE(state->modules_by_index)) {
311 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
312 return -1;
313 }
314 return PyList_SetItem(state->modules_by_index, index, Py_None);
315}
316
Guido van Rossuma027efa1997-05-05 20:56:21 +0000317void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000318PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 if (Py_VerboseFlag && tstate->frame != NULL)
321 fprintf(stderr,
322 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 Py_CLEAR(tstate->dict);
327 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 Py_CLEAR(tstate->curexc_type);
330 Py_CLEAR(tstate->curexc_value);
331 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 Py_CLEAR(tstate->exc_type);
334 Py_CLEAR(tstate->exc_value);
335 Py_CLEAR(tstate->exc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000337 tstate->c_profilefunc = NULL;
338 tstate->c_tracefunc = NULL;
339 Py_CLEAR(tstate->c_profileobj);
340 Py_CLEAR(tstate->c_traceobj);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000341}
342
343
Guido van Rossum29757862001-01-23 01:46:06 +0000344/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
345static void
346tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 PyInterpreterState *interp;
349 PyThreadState **p;
350 PyThreadState *prev_p = NULL;
351 if (tstate == NULL)
352 Py_FatalError("PyThreadState_Delete: NULL tstate");
353 interp = tstate->interp;
354 if (interp == NULL)
355 Py_FatalError("PyThreadState_Delete: NULL interp");
356 HEAD_LOCK();
357 for (p = &interp->tstate_head; ; p = &(*p)->next) {
358 if (*p == NULL)
359 Py_FatalError(
360 "PyThreadState_Delete: invalid tstate");
361 if (*p == tstate)
362 break;
363 /* Sanity check. These states should never happen but if
364 * they do we must abort. Otherwise we'll end up spinning in
365 * in a tight loop with the lock held. A similar check is done
366 * in thread.c find_key(). */
367 if (*p == prev_p)
368 Py_FatalError(
369 "PyThreadState_Delete: small circular list(!)"
370 " and tstate not found.");
371 prev_p = *p;
372 if ((*p)->next == interp->tstate_head)
373 Py_FatalError(
374 "PyThreadState_Delete: circular list(!) and"
375 " tstate not found.");
376 }
377 *p = tstate->next;
378 HEAD_UNLOCK();
379 free(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000380}
381
382
Guido van Rossum29757862001-01-23 01:46:06 +0000383void
384PyThreadState_Delete(PyThreadState *tstate)
385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 if (tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current))
387 Py_FatalError("PyThreadState_Delete: tstate is still current");
388 tstate_delete_common(tstate);
Tim Petersf4e69282006-02-27 17:15:31 +0000389#ifdef WITH_THREAD
Antoine Pitrou079ce542010-09-08 12:37:10 +0000390 if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 PyThread_delete_key_value(autoTLSkey);
Tim Petersf4e69282006-02-27 17:15:31 +0000392#endif /* WITH_THREAD */
Guido van Rossum29757862001-01-23 01:46:06 +0000393}
394
395
396#ifdef WITH_THREAD
397void
398PyThreadState_DeleteCurrent()
399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
401 &_PyThreadState_Current);
402 if (tstate == NULL)
403 Py_FatalError(
404 "PyThreadState_DeleteCurrent: no current tstate");
405 _Py_atomic_store_relaxed(&_PyThreadState_Current, NULL);
406 tstate_delete_common(tstate);
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);
409 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000410}
411#endif /* WITH_THREAD */
412
413
Guido van Rossuma027efa1997-05-05 20:56:21 +0000414PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000415PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
418 &_PyThreadState_Current);
419 if (tstate == NULL)
420 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000423}
424
425
426PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000427PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 PyThreadState *oldts = (PyThreadState*)_Py_atomic_load_relaxed(
430 &_PyThreadState_Current);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 _Py_atomic_store_relaxed(&_PyThreadState_Current, newts);
433 /* It should not be possible for more than one thread state
434 to be used for a thread. Check this the best we can in debug
435 builds.
436 */
Martin v. Löwis9e296252003-05-01 05:25:29 +0000437#if defined(Py_DEBUG) && defined(WITH_THREAD)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 if (newts) {
439 /* This can be called from PyEval_RestoreThread(). Similar
440 to it, we need to ensure errno doesn't change.
441 */
442 int err = errno;
443 PyThreadState *check = PyGILState_GetThisThreadState();
444 if (check && check->interp == newts->interp && check != newts)
445 Py_FatalError("Invalid thread state for this thread");
446 errno = err;
447 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000448#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000450}
Guido van Rossumede04391998-04-10 20:18:25 +0000451
452/* An extension mechanism to store arbitrary additional per-thread state.
453 PyThreadState_GetDict() returns a dictionary that can be used to hold such
454 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000455 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
456 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000457
458PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000459PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
462 &_PyThreadState_Current);
463 if (tstate == NULL)
464 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 if (tstate->dict == NULL) {
467 PyObject *d;
468 tstate->dict = d = PyDict_New();
469 if (d == NULL)
470 PyErr_Clear();
471 }
472 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000473}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000474
475
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000476/* Asynchronously raise an exception in a thread.
477 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000478 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000479 to call this, or use ctypes. Must be called with the GIL held.
480 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
481 match any known thread id). Can be called with exc=NULL to clear an
482 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000483
484int
485PyThreadState_SetAsyncExc(long id, PyObject *exc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 PyThreadState *tstate = PyThreadState_GET();
487 PyInterpreterState *interp = tstate->interp;
488 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 /* Although the GIL is held, a few C API functions can be called
491 * without the GIL held, and in particular some that create and
492 * destroy thread and interpreter states. Those can mutate the
493 * list of thread states we're traversing, so to prevent that we lock
494 * head_mutex for the duration.
495 */
496 HEAD_LOCK();
497 for (p = interp->tstate_head; p != NULL; p = p->next) {
498 if (p->thread_id == id) {
499 /* Tricky: we need to decref the current value
500 * (if any) in p->async_exc, but that can in turn
501 * allow arbitrary Python code to run, including
502 * perhaps calls to this function. To prevent
503 * deadlock, we need to release head_mutex before
504 * the decref.
505 */
506 PyObject *old_exc = p->async_exc;
507 Py_XINCREF(exc);
508 p->async_exc = exc;
509 HEAD_UNLOCK();
510 Py_XDECREF(old_exc);
511 _PyEval_SignalAsyncExc();
512 return 1;
513 }
514 }
515 HEAD_UNLOCK();
516 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000517}
518
519
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000520/* Routines for advanced debuggers, requested by David Beazley.
521 Don't use unless you know what you are doing! */
522
523PyInterpreterState *
524PyInterpreterState_Head(void)
525{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 return interp_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000527}
528
529PyInterpreterState *
530PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000532}
533
534PyThreadState *
535PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000537}
538
539PyThreadState *
540PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000542}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000543
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000544/* The implementation of sys._current_frames(). This is intended to be
545 called with the GIL held, as it will be when called via
546 sys._current_frames(). It's possible it would work fine even without
547 the GIL held, but haven't thought enough about that.
548*/
549PyObject *
550_PyThread_CurrentFrames(void)
551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 PyObject *result;
553 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 result = PyDict_New();
556 if (result == NULL)
557 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 /* for i in all interpreters:
560 * for t in all of i's thread states:
561 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200562 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 * need to grab head_mutex for the duration.
564 */
565 HEAD_LOCK();
566 for (i = interp_head; i != NULL; i = i->next) {
567 PyThreadState *t;
568 for (t = i->tstate_head; t != NULL; t = t->next) {
569 PyObject *id;
570 int stat;
571 struct _frame *frame = t->frame;
572 if (frame == NULL)
573 continue;
574 id = PyLong_FromLong(t->thread_id);
575 if (id == NULL)
576 goto Fail;
577 stat = PyDict_SetItem(result, id, (PyObject *)frame);
578 Py_DECREF(id);
579 if (stat < 0)
580 goto Fail;
581 }
582 }
583 HEAD_UNLOCK();
584 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000585
586 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 HEAD_UNLOCK();
588 Py_DECREF(result);
589 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000590}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000591
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000592/* Python "auto thread state" API. */
593#ifdef WITH_THREAD
594
595/* Keep this as a static, as it is not reliable! It can only
596 ever be compared to the state for the *current* thread.
597 * If not equal, then it doesn't matter that the actual
598 value may change immediately after comparison, as it can't
599 possibly change to the current thread's state.
600 * If equal, then the current thread holds the lock, so the value can't
601 change until we yield the lock.
602*/
603static int
604PyThreadState_IsCurrent(PyThreadState *tstate)
605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 /* Must be the tstate for this thread */
607 assert(PyGILState_GetThisThreadState()==tstate);
608 return tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000609}
610
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000611/* Internal initialization/finalization functions called by
612 Py_Initialize/Py_Finalize
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000613*/
Tim Peters19717fa2004-10-09 17:38:29 +0000614void
615_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 assert(i && t); /* must init with valid states */
618 autoTLSkey = PyThread_create_key();
Kristján Valur Jónsson2fea9b92010-09-20 02:11:49 +0000619 if (autoTLSkey == -1)
620 Py_FatalError("Could not allocate TLS entry");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 autoInterpreterState = i;
622 assert(PyThread_get_key_value(autoTLSkey) == NULL);
623 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000626}
627
Tim Peters19717fa2004-10-09 17:38:29 +0000628void
629_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000630{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 PyThread_delete_key(autoTLSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000633}
634
Charles-François Natalia233df82011-11-22 19:49:51 +0100635/* Reset the TLS key - called by PyOS_AfterFork().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200636 * This should not be necessary, but some - buggy - pthread implementations
Charles-François Natalia233df82011-11-22 19:49:51 +0100637 * don't reset TLS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200638 */
639void
640_PyGILState_Reinit(void)
641{
642 PyThreadState *tstate = PyGILState_GetThisThreadState();
643 PyThread_delete_key(autoTLSkey);
644 if ((autoTLSkey = PyThread_create_key()) == -1)
645 Py_FatalError("Could not allocate TLS entry");
646
Charles-François Natalia233df82011-11-22 19:49:51 +0100647 /* If the thread had an associated auto thread state, reassociate it with
648 * the new key. */
649 if (tstate && PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200650 Py_FatalError("Couldn't create autoTLSkey mapping");
651}
652
Michael W. Hudson188d4362005-06-20 16:52:57 +0000653/* When a thread state is created for a thread by some mechanism other than
654 PyGILState_Ensure, it's important that the GILState machinery knows about
655 it so it doesn't try to create another thread state for the thread (this is
656 a better fix for SF bug #1010677 than the first one attempted).
657*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000658static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000659_PyGILState_NoteThreadState(PyThreadState* tstate)
660{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000661 /* If autoTLSkey isn't initialized, this must be the very first
662 threadstate created in Py_Initialize(). Don't do anything for now
663 (we'll be back here when _PyGILState_Init is called). */
664 if (!autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 /* Stick the thread state for this thread in thread local storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 The only situation where you can legitimately have more than one
670 thread state for an OS level thread is when there are multiple
671 interpreters, when:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 a) You shouldn't really be using the PyGILState_ APIs anyway,
674 and:
Michael W. Hudson188d4362005-06-20 16:52:57 +0000675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 b) The slightly odd way PyThread_set_key_value works (see
677 comments by its implementation) means that the first thread
678 state created for that given OS level thread will "win",
679 which seems reasonable behaviour.
680 */
681 if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
682 Py_FatalError("Couldn't create autoTLSkey mapping");
Michael W. Hudson188d4362005-06-20 16:52:57 +0000683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000684 /* PyGILState_Release must not try to delete this thread state. */
685 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000686}
687
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000688/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000689PyThreadState *
690PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000691{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000692 if (autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 return NULL;
694 return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000695}
696
Tim Peters19717fa2004-10-09 17:38:29 +0000697PyGILState_STATE
698PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 int current;
701 PyThreadState *tcur;
702 /* Note that we do not auto-init Python here - apart from
703 potential races with 2 threads auto-initializing, pep-311
704 spells out other issues. Embedders are expected to have
705 called Py_Initialize() and usually PyEval_InitThreads().
706 */
707 assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */
708 tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey);
709 if (tcur == NULL) {
710 /* Create a new thread state for this thread */
711 tcur = PyThreadState_New(autoInterpreterState);
712 if (tcur == NULL)
713 Py_FatalError("Couldn't create thread-state for new thread");
714 /* This is our thread state! We'll need to delete it in the
715 matching call to PyGILState_Release(). */
716 tcur->gilstate_counter = 0;
717 current = 0; /* new thread state is never current */
718 }
719 else
720 current = PyThreadState_IsCurrent(tcur);
721 if (current == 0)
722 PyEval_RestoreThread(tcur);
723 /* Update our counter in the thread-state - no need for locks:
724 - tcur will remain valid as we hold the GIL.
725 - the counter is safe as we are the only thread "allowed"
726 to modify this value
727 */
728 ++tcur->gilstate_counter;
729 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000730}
731
Tim Peters19717fa2004-10-09 17:38:29 +0000732void
733PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
736 autoTLSkey);
737 if (tcur == NULL)
738 Py_FatalError("auto-releasing thread-state, "
739 "but no thread-state for this thread");
740 /* We must hold the GIL and have our thread state current */
741 /* XXX - remove the check - the assert should be fine,
742 but while this is very new (April 2003), the extra check
743 by release-only users can't hurt.
744 */
745 if (! PyThreadState_IsCurrent(tcur))
746 Py_FatalError("This thread state must be current when releasing");
747 assert(PyThreadState_IsCurrent(tcur));
748 --tcur->gilstate_counter;
749 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000751 /* If we're going to destroy this thread-state, we must
752 * clear it while the GIL is held, as destructors may run.
753 */
754 if (tcur->gilstate_counter == 0) {
755 /* can't have been locked when we created it */
756 assert(oldstate == PyGILState_UNLOCKED);
757 PyThreadState_Clear(tcur);
758 /* Delete the thread-state. Note this releases the GIL too!
759 * It's vital that the GIL be held here, to avoid shutdown
760 * races; see bugs 225673 and 1061968 (that nasty bug has a
761 * habit of coming back).
762 */
763 PyThreadState_DeleteCurrent();
764 }
765 /* Release the lock if necessary */
766 else if (oldstate == PyGILState_UNLOCKED)
767 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000768}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000769
Benjamin Peterson3bf01752012-04-13 18:06:36 -0400770#endif /* WITH_THREAD */
771
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000772#ifdef __cplusplus
773}
774#endif
775
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000776