blob: 40699af499496327ab481f249972e1803ab56523 [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
25
Guido van Rossum1d5ad901999-06-18 14:22:24 +000026#ifdef WITH_THREAD
27#include "pythread.h"
28static PyThread_type_lock head_mutex = NULL; /* Protects interp->tstate_head */
Moshe Zadka9fb6af92000-08-04 21:27:47 +000029#define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock()))
Guido van Rossum1d5ad901999-06-18 14:22:24 +000030#define HEAD_LOCK() PyThread_acquire_lock(head_mutex, WAIT_LOCK)
31#define HEAD_UNLOCK() PyThread_release_lock(head_mutex)
Michael W. Hudson188d4362005-06-20 16:52:57 +000032
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000033#ifdef __cplusplus
34extern "C" {
35#endif
36
Michael W. Hudson188d4362005-06-20 16:52:57 +000037/* The single PyInterpreterState used by this process'
38 GILState implementation
39*/
40static PyInterpreterState *autoInterpreterState = NULL;
41static int autoTLSkey = 0;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000042#else
43#define HEAD_INIT() /* Nothing */
44#define HEAD_LOCK() /* Nothing */
45#define HEAD_UNLOCK() /* Nothing */
46#endif
47
Guido van Rossum25ce5661997-08-02 03:10:38 +000048static PyInterpreterState *interp_head = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +000049
Jeffrey Yasskin39370832010-05-03 19:29:34 +000050/* Assuming the current thread holds the GIL, this is the
51 PyThreadState for the current thread. */
52_Py_atomic_address _PyThreadState_Current = {NULL};
Guido van Rossum6297a7a2003-02-19 15:53:17 +000053PyThreadFrameGetter _PyThreadState_GetFrame = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +000054
Michael W. Hudsonce7da6c2005-09-30 08:20:24 +000055#ifdef WITH_THREAD
Michael W. Hudson188d4362005-06-20 16:52:57 +000056static void _PyGILState_NoteThreadState(PyThreadState* tstate);
Michael W. Hudsonce7da6c2005-09-30 08:20:24 +000057#endif
Michael W. Hudson188d4362005-06-20 16:52:57 +000058
Guido van Rossuma027efa1997-05-05 20:56:21 +000059
60PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000061PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +000062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyInterpreterState *interp = (PyInterpreterState *)
64 malloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +000065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000066 if (interp != NULL) {
67 HEAD_INIT();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000068#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 if (head_mutex == NULL)
70 Py_FatalError("Can't initialize threads for interpreter");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000071#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 interp->modules = NULL;
73 interp->modules_reloading = NULL;
74 interp->modules_by_index = NULL;
75 interp->sysdict = NULL;
76 interp->builtins = NULL;
77 interp->tstate_head = NULL;
78 interp->codec_search_path = NULL;
79 interp->codec_search_cache = NULL;
80 interp->codec_error_registry = NULL;
81 interp->codecs_initialized = 0;
Victor Stinner3cbf14b2011-04-27 00:24:21 +020082 interp->fscodec_initialized = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +000083#ifdef HAVE_DLOPEN
84#ifdef RTLD_NOW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +000086#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +000088#endif
89#endif
Martin v. Löwisf30d60e2004-06-08 08:17:44 +000090#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 interp->tscdump = 0;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +000092#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +000093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 HEAD_LOCK();
95 interp->next = interp_head;
96 interp_head = interp;
97 HEAD_UNLOCK();
98 }
Guido van Rossum25ce5661997-08-02 03:10:38 +000099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000101}
102
103
104void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000105PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000106{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 PyThreadState *p;
108 HEAD_LOCK();
109 for (p = interp->tstate_head; p != NULL; p = p->next)
110 PyThreadState_Clear(p);
111 HEAD_UNLOCK();
112 Py_CLEAR(interp->codec_search_path);
113 Py_CLEAR(interp->codec_search_cache);
114 Py_CLEAR(interp->codec_error_registry);
115 Py_CLEAR(interp->modules);
116 Py_CLEAR(interp->modules_by_index);
117 Py_CLEAR(interp->modules_reloading);
118 Py_CLEAR(interp->sysdict);
119 Py_CLEAR(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000120}
121
122
123static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000124zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 PyThreadState *p;
127 /* No need to lock the mutex here because this should only happen
128 when the threads are all really dead (XXX famous last words). */
129 while ((p = interp->tstate_head) != NULL) {
130 PyThreadState_Delete(p);
131 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000132}
133
134
135void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000136PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 PyInterpreterState **p;
139 zapthreads(interp);
140 HEAD_LOCK();
141 for (p = &interp_head; ; p = &(*p)->next) {
142 if (*p == NULL)
143 Py_FatalError(
144 "PyInterpreterState_Delete: invalid interp");
145 if (*p == interp)
146 break;
147 }
148 if (interp->tstate_head != NULL)
149 Py_FatalError("PyInterpreterState_Delete: remaining threads");
150 *p = interp->next;
151 HEAD_UNLOCK();
152 free(interp);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100153#ifdef WITH_THREAD
154 if (interp_head == NULL && head_mutex != NULL) {
155 PyThread_free_lock(head_mutex);
156 head_mutex = NULL;
157 }
158#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +0000159}
160
161
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000162/* Default implementation for _PyThreadState_GetFrame */
163static struct _frame *
164threadstate_getframe(PyThreadState *self)
165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000167}
168
Victor Stinner45b9be52010-03-03 23:28:07 +0000169static PyThreadState *
170new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 PyThreadState *tstate = (PyThreadState *)malloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000174 if (_PyThreadState_GetFrame == NULL)
175 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 if (tstate != NULL) {
178 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 tstate->frame = NULL;
181 tstate->recursion_depth = 0;
182 tstate->overflowed = 0;
183 tstate->recursion_critical = 0;
184 tstate->tracing = 0;
185 tstate->use_tracing = 0;
186 tstate->tick_counter = 0;
187 tstate->gilstate_counter = 0;
188 tstate->async_exc = NULL;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000189#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 tstate->thread_id = PyThread_get_thread_ident();
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000191#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 tstate->thread_id = 0;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000193#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000197 tstate->curexc_type = NULL;
198 tstate->curexc_value = NULL;
199 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 tstate->exc_type = NULL;
202 tstate->exc_value = NULL;
203 tstate->exc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 tstate->c_profilefunc = NULL;
206 tstate->c_tracefunc = NULL;
207 tstate->c_profileobj = NULL;
208 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 if (init)
211 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 HEAD_LOCK();
214 tstate->next = interp->tstate_head;
215 interp->tstate_head = tstate;
216 HEAD_UNLOCK();
217 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000220}
221
Victor Stinner45b9be52010-03-03 23:28:07 +0000222PyThreadState *
223PyThreadState_New(PyInterpreterState *interp)
224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000226}
227
228PyThreadState *
229_PyThreadState_Prealloc(PyInterpreterState *interp)
230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000232}
233
234void
235_PyThreadState_Init(PyThreadState *tstate)
236{
237#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000239#endif
240}
241
Martin v. Löwis1a214512008-06-11 05:26:20 +0000242PyObject*
243PyState_FindModule(struct PyModuleDef* m)
244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 Py_ssize_t index = m->m_base.m_index;
246 PyInterpreterState *state = PyThreadState_GET()->interp;
247 PyObject *res;
248 if (index == 0)
249 return NULL;
250 if (state->modules_by_index == NULL)
251 return NULL;
252 if (index > PyList_GET_SIZE(state->modules_by_index))
253 return NULL;
254 res = PyList_GET_ITEM(state->modules_by_index, index);
255 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000256}
257
258int
259_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 PyInterpreterState *state = PyThreadState_GET()->interp;
262 if (!def)
263 return -1;
264 if (!state->modules_by_index) {
265 state->modules_by_index = PyList_New(0);
266 if (!state->modules_by_index)
267 return -1;
268 }
269 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
270 if (PyList_Append(state->modules_by_index, Py_None) < 0)
271 return -1;
272 Py_INCREF(module);
273 return PyList_SetItem(state->modules_by_index,
274 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000275}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000276
277void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000278PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 if (Py_VerboseFlag && tstate->frame != NULL)
281 fprintf(stderr,
282 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 Py_CLEAR(tstate->dict);
287 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 Py_CLEAR(tstate->curexc_type);
290 Py_CLEAR(tstate->curexc_value);
291 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 Py_CLEAR(tstate->exc_type);
294 Py_CLEAR(tstate->exc_value);
295 Py_CLEAR(tstate->exc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 tstate->c_profilefunc = NULL;
298 tstate->c_tracefunc = NULL;
299 Py_CLEAR(tstate->c_profileobj);
300 Py_CLEAR(tstate->c_traceobj);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000301}
302
303
Guido van Rossum29757862001-01-23 01:46:06 +0000304/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
305static void
306tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 PyInterpreterState *interp;
309 PyThreadState **p;
310 PyThreadState *prev_p = NULL;
311 if (tstate == NULL)
312 Py_FatalError("PyThreadState_Delete: NULL tstate");
313 interp = tstate->interp;
314 if (interp == NULL)
315 Py_FatalError("PyThreadState_Delete: NULL interp");
316 HEAD_LOCK();
317 for (p = &interp->tstate_head; ; p = &(*p)->next) {
318 if (*p == NULL)
319 Py_FatalError(
320 "PyThreadState_Delete: invalid tstate");
321 if (*p == tstate)
322 break;
323 /* Sanity check. These states should never happen but if
324 * they do we must abort. Otherwise we'll end up spinning in
325 * in a tight loop with the lock held. A similar check is done
326 * in thread.c find_key(). */
327 if (*p == prev_p)
328 Py_FatalError(
329 "PyThreadState_Delete: small circular list(!)"
330 " and tstate not found.");
331 prev_p = *p;
332 if ((*p)->next == interp->tstate_head)
333 Py_FatalError(
334 "PyThreadState_Delete: circular list(!) and"
335 " tstate not found.");
336 }
337 *p = tstate->next;
338 HEAD_UNLOCK();
339 free(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000340}
341
342
Guido van Rossum29757862001-01-23 01:46:06 +0000343void
344PyThreadState_Delete(PyThreadState *tstate)
345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 if (tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current))
347 Py_FatalError("PyThreadState_Delete: tstate is still current");
348 tstate_delete_common(tstate);
Tim Petersf4e69282006-02-27 17:15:31 +0000349#ifdef WITH_THREAD
Antoine Pitrou079ce542010-09-08 12:37:10 +0000350 if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 PyThread_delete_key_value(autoTLSkey);
Tim Petersf4e69282006-02-27 17:15:31 +0000352#endif /* WITH_THREAD */
Guido van Rossum29757862001-01-23 01:46:06 +0000353}
354
355
356#ifdef WITH_THREAD
357void
358PyThreadState_DeleteCurrent()
359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
361 &_PyThreadState_Current);
362 if (tstate == NULL)
363 Py_FatalError(
364 "PyThreadState_DeleteCurrent: no current tstate");
365 _Py_atomic_store_relaxed(&_PyThreadState_Current, NULL);
366 tstate_delete_common(tstate);
Antoine Pitrou079ce542010-09-08 12:37:10 +0000367 if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 PyThread_delete_key_value(autoTLSkey);
369 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000370}
371#endif /* WITH_THREAD */
372
373
Guido van Rossuma027efa1997-05-05 20:56:21 +0000374PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000375PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
378 &_PyThreadState_Current);
379 if (tstate == NULL)
380 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000383}
384
385
386PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000387PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 PyThreadState *oldts = (PyThreadState*)_Py_atomic_load_relaxed(
390 &_PyThreadState_Current);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 _Py_atomic_store_relaxed(&_PyThreadState_Current, newts);
393 /* It should not be possible for more than one thread state
394 to be used for a thread. Check this the best we can in debug
395 builds.
396 */
Martin v. Löwis9e296252003-05-01 05:25:29 +0000397#if defined(Py_DEBUG) && defined(WITH_THREAD)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 if (newts) {
399 /* This can be called from PyEval_RestoreThread(). Similar
400 to it, we need to ensure errno doesn't change.
401 */
402 int err = errno;
403 PyThreadState *check = PyGILState_GetThisThreadState();
404 if (check && check->interp == newts->interp && check != newts)
405 Py_FatalError("Invalid thread state for this thread");
406 errno = err;
407 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000408#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000410}
Guido van Rossumede04391998-04-10 20:18:25 +0000411
412/* An extension mechanism to store arbitrary additional per-thread state.
413 PyThreadState_GetDict() returns a dictionary that can be used to hold such
414 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000415 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
416 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000417
418PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000419PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
422 &_PyThreadState_Current);
423 if (tstate == NULL)
424 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 if (tstate->dict == NULL) {
427 PyObject *d;
428 tstate->dict = d = PyDict_New();
429 if (d == NULL)
430 PyErr_Clear();
431 }
432 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000433}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000434
435
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000436/* Asynchronously raise an exception in a thread.
437 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000438 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000439 to call this, or use ctypes. Must be called with the GIL held.
440 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
441 match any known thread id). Can be called with exc=NULL to clear an
442 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000443
444int
445PyThreadState_SetAsyncExc(long id, PyObject *exc) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 PyThreadState *tstate = PyThreadState_GET();
447 PyInterpreterState *interp = tstate->interp;
448 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 /* Although the GIL is held, a few C API functions can be called
451 * without the GIL held, and in particular some that create and
452 * destroy thread and interpreter states. Those can mutate the
453 * list of thread states we're traversing, so to prevent that we lock
454 * head_mutex for the duration.
455 */
456 HEAD_LOCK();
457 for (p = interp->tstate_head; p != NULL; p = p->next) {
458 if (p->thread_id == id) {
459 /* Tricky: we need to decref the current value
460 * (if any) in p->async_exc, but that can in turn
461 * allow arbitrary Python code to run, including
462 * perhaps calls to this function. To prevent
463 * deadlock, we need to release head_mutex before
464 * the decref.
465 */
466 PyObject *old_exc = p->async_exc;
467 Py_XINCREF(exc);
468 p->async_exc = exc;
469 HEAD_UNLOCK();
470 Py_XDECREF(old_exc);
471 _PyEval_SignalAsyncExc();
472 return 1;
473 }
474 }
475 HEAD_UNLOCK();
476 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000477}
478
479
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000480/* Routines for advanced debuggers, requested by David Beazley.
481 Don't use unless you know what you are doing! */
482
483PyInterpreterState *
484PyInterpreterState_Head(void)
485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 return interp_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000487}
488
489PyInterpreterState *
490PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000492}
493
494PyThreadState *
495PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000497}
498
499PyThreadState *
500PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000502}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000503
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000504/* The implementation of sys._current_frames(). This is intended to be
505 called with the GIL held, as it will be when called via
506 sys._current_frames(). It's possible it would work fine even without
507 the GIL held, but haven't thought enough about that.
508*/
509PyObject *
510_PyThread_CurrentFrames(void)
511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 PyObject *result;
513 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 result = PyDict_New();
516 if (result == NULL)
517 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 /* for i in all interpreters:
520 * for t in all of i's thread states:
521 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200522 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 * need to grab head_mutex for the duration.
524 */
525 HEAD_LOCK();
526 for (i = interp_head; i != NULL; i = i->next) {
527 PyThreadState *t;
528 for (t = i->tstate_head; t != NULL; t = t->next) {
529 PyObject *id;
530 int stat;
531 struct _frame *frame = t->frame;
532 if (frame == NULL)
533 continue;
534 id = PyLong_FromLong(t->thread_id);
535 if (id == NULL)
536 goto Fail;
537 stat = PyDict_SetItem(result, id, (PyObject *)frame);
538 Py_DECREF(id);
539 if (stat < 0)
540 goto Fail;
541 }
542 }
543 HEAD_UNLOCK();
544 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000545
546 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 HEAD_UNLOCK();
548 Py_DECREF(result);
549 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000550}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000551
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000552/* Python "auto thread state" API. */
553#ifdef WITH_THREAD
554
555/* Keep this as a static, as it is not reliable! It can only
556 ever be compared to the state for the *current* thread.
557 * If not equal, then it doesn't matter that the actual
558 value may change immediately after comparison, as it can't
559 possibly change to the current thread's state.
560 * If equal, then the current thread holds the lock, so the value can't
561 change until we yield the lock.
562*/
563static int
564PyThreadState_IsCurrent(PyThreadState *tstate)
565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 /* Must be the tstate for this thread */
567 assert(PyGILState_GetThisThreadState()==tstate);
568 return tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000569}
570
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000571/* Internal initialization/finalization functions called by
572 Py_Initialize/Py_Finalize
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000573*/
Tim Peters19717fa2004-10-09 17:38:29 +0000574void
575_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 assert(i && t); /* must init with valid states */
578 autoTLSkey = PyThread_create_key();
Kristján Valur Jónsson2fea9b92010-09-20 02:11:49 +0000579 if (autoTLSkey == -1)
580 Py_FatalError("Could not allocate TLS entry");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 autoInterpreterState = i;
582 assert(PyThread_get_key_value(autoTLSkey) == NULL);
583 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000586}
587
Tim Peters19717fa2004-10-09 17:38:29 +0000588void
589_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 PyThread_delete_key(autoTLSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000593}
594
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200595/* Reset the TLS key - called by PyOS_AfterFork.
596 * This should not be necessary, but some - buggy - pthread implementations
597 * don't flush TLS on fork, see issue #10517.
598 */
599void
600_PyGILState_Reinit(void)
601{
602 PyThreadState *tstate = PyGILState_GetThisThreadState();
603 PyThread_delete_key(autoTLSkey);
604 if ((autoTLSkey = PyThread_create_key()) == -1)
605 Py_FatalError("Could not allocate TLS entry");
606
607 /* re-associate the current thread state with the new key */
608 if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
609 Py_FatalError("Couldn't create autoTLSkey mapping");
610}
611
Michael W. Hudson188d4362005-06-20 16:52:57 +0000612/* When a thread state is created for a thread by some mechanism other than
613 PyGILState_Ensure, it's important that the GILState machinery knows about
614 it so it doesn't try to create another thread state for the thread (this is
615 a better fix for SF bug #1010677 than the first one attempted).
616*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000617static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000618_PyGILState_NoteThreadState(PyThreadState* tstate)
619{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000620 /* If autoTLSkey isn't initialized, this must be the very first
621 threadstate created in Py_Initialize(). Don't do anything for now
622 (we'll be back here when _PyGILState_Init is called). */
623 if (!autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 /* Stick the thread state for this thread in thread local storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 The only situation where you can legitimately have more than one
629 thread state for an OS level thread is when there are multiple
630 interpreters, when:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 a) You shouldn't really be using the PyGILState_ APIs anyway,
633 and:
Michael W. Hudson188d4362005-06-20 16:52:57 +0000634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 b) The slightly odd way PyThread_set_key_value works (see
636 comments by its implementation) means that the first thread
637 state created for that given OS level thread will "win",
638 which seems reasonable behaviour.
639 */
640 if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
641 Py_FatalError("Couldn't create autoTLSkey mapping");
Michael W. Hudson188d4362005-06-20 16:52:57 +0000642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 /* PyGILState_Release must not try to delete this thread state. */
644 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000645}
646
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000647/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000648PyThreadState *
649PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000650{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000651 if (autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 return NULL;
653 return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000654}
655
Tim Peters19717fa2004-10-09 17:38:29 +0000656PyGILState_STATE
657PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000658{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 int current;
660 PyThreadState *tcur;
661 /* Note that we do not auto-init Python here - apart from
662 potential races with 2 threads auto-initializing, pep-311
663 spells out other issues. Embedders are expected to have
664 called Py_Initialize() and usually PyEval_InitThreads().
665 */
666 assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */
667 tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey);
668 if (tcur == NULL) {
669 /* Create a new thread state for this thread */
670 tcur = PyThreadState_New(autoInterpreterState);
671 if (tcur == NULL)
672 Py_FatalError("Couldn't create thread-state for new thread");
673 /* This is our thread state! We'll need to delete it in the
674 matching call to PyGILState_Release(). */
675 tcur->gilstate_counter = 0;
676 current = 0; /* new thread state is never current */
677 }
678 else
679 current = PyThreadState_IsCurrent(tcur);
680 if (current == 0)
681 PyEval_RestoreThread(tcur);
682 /* Update our counter in the thread-state - no need for locks:
683 - tcur will remain valid as we hold the GIL.
684 - the counter is safe as we are the only thread "allowed"
685 to modify this value
686 */
687 ++tcur->gilstate_counter;
688 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000689}
690
Tim Peters19717fa2004-10-09 17:38:29 +0000691void
692PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
695 autoTLSkey);
696 if (tcur == NULL)
697 Py_FatalError("auto-releasing thread-state, "
698 "but no thread-state for this thread");
699 /* We must hold the GIL and have our thread state current */
700 /* XXX - remove the check - the assert should be fine,
701 but while this is very new (April 2003), the extra check
702 by release-only users can't hurt.
703 */
704 if (! PyThreadState_IsCurrent(tcur))
705 Py_FatalError("This thread state must be current when releasing");
706 assert(PyThreadState_IsCurrent(tcur));
707 --tcur->gilstate_counter;
708 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000709
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 /* If we're going to destroy this thread-state, we must
711 * clear it while the GIL is held, as destructors may run.
712 */
713 if (tcur->gilstate_counter == 0) {
714 /* can't have been locked when we created it */
715 assert(oldstate == PyGILState_UNLOCKED);
716 PyThreadState_Clear(tcur);
717 /* Delete the thread-state. Note this releases the GIL too!
718 * It's vital that the GIL be held here, to avoid shutdown
719 * races; see bugs 225673 and 1061968 (that nasty bug has a
720 * habit of coming back).
721 */
722 PyThreadState_DeleteCurrent();
723 }
724 /* Release the lock if necessary */
725 else if (oldstate == PyGILState_UNLOCKED)
726 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000727}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000728
729#ifdef __cplusplus
730}
731#endif
732
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000733#endif /* WITH_THREAD */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000734
735