blob: 36566b767155b318408798080e12dd4882317872 [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"
Victor Stinnerf684d832019-03-01 03:44:13 +01005#include "pycore_coreconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01006#include "pycore_pymem.h"
7#include "pycore_pystate.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +00008
Victor Stinner9204fb82018-10-30 15:13:17 +01009#define _PyThreadState_SET(value) \
10 _Py_atomic_store_relaxed(&_PyRuntime.gilstate.tstate_current, \
11 (uintptr_t)(value))
Victor Stinnerb02ef712016-01-22 14:09:55 +010012
Victor Stinnerbfd316e2016-01-20 11:12:38 +010013
Tim Peters84705582004-10-10 02:47:33 +000014/* --------------------------------------------------------------------------
15CAUTION
16
Victor Stinner1a7425f2013-07-07 16:25:15 +020017Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
18number of these functions are advertised as safe to call when the GIL isn't
19held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
20debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
21to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000022-------------------------------------------------------------------------- */
23
Martin v. Löwisf0473d52001-07-18 16:17:16 +000024#ifdef HAVE_DLOPEN
25#ifdef HAVE_DLFCN_H
26#include <dlfcn.h>
27#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030028#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000029#define RTLD_LAZY 1
30#endif
31#endif
32
Benjamin Peterson43162b82012-04-13 11:58:27 -040033#ifdef __cplusplus
34extern "C" {
35#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000036
Victor Stinner5d39e042017-11-29 17:20:38 +010037static _PyInitError
38_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060039{
40 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010041
Eric Snow2ebc5ce2017-09-07 23:51:28 -060042 _PyGC_Initialize(&runtime->gc);
43 _PyEval_Initialize(&runtime->ceval);
Michael W. Hudson188d4362005-06-20 16:52:57 +000044
Eric Snow2ebc5ce2017-09-07 23:51:28 -060045 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080046
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090047 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
48 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080049 Py_tss_t initial = Py_tss_NEEDS_INIT;
50 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000051
Eric Snow2ebc5ce2017-09-07 23:51:28 -060052 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080053 if (runtime->interpreters.mutex == NULL) {
54 return _Py_INIT_ERR("Can't initialize threads for interpreter");
55 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060056 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070057
58 runtime->xidregistry.mutex = PyThread_allocate_lock();
59 if (runtime->xidregistry.mutex == NULL) {
60 return _Py_INIT_ERR("Can't initialize threads for cross-interpreter data registry");
61 }
62
Eric Snow8479a342019-03-08 23:44:33 -070063 // Set it to the ID of the main thread of the main interpreter.
64 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070065
Victor Stinnerf7e5b562017-11-15 15:48:08 -080066 return _Py_INIT_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060067}
Eric Snow05351c12017-09-05 21:43:08 -070068
Victor Stinner5d39e042017-11-29 17:20:38 +010069_PyInitError
70_PyRuntimeState_Init(_PyRuntimeState *runtime)
71{
72 /* Force default allocator, since _PyRuntimeState_Fini() must
73 use the same allocator than this function. */
74 PyMemAllocatorEx old_alloc;
75 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
76
77 _PyInitError err = _PyRuntimeState_Init_impl(runtime);
78
79 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
80 return err;
81}
82
Eric Snow2ebc5ce2017-09-07 23:51:28 -060083void
84_PyRuntimeState_Fini(_PyRuntimeState *runtime)
85{
Victor Stinner5d39e042017-11-29 17:20:38 +010086 /* Force the allocator used by _PyRuntimeState_Init(). */
87 PyMemAllocatorEx old_alloc;
88 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -080089
Eric Snow2ebc5ce2017-09-07 23:51:28 -060090 if (runtime->interpreters.mutex != NULL) {
91 PyThread_free_lock(runtime->interpreters.mutex);
92 runtime->interpreters.mutex = NULL;
93 }
Victor Stinnerccb04422017-11-16 03:20:31 -080094
Stéphane Wirtel943395f2019-03-19 11:51:32 +010095 if (runtime->xidregistry.mutex != NULL) {
96 PyThread_free_lock(runtime->xidregistry.mutex);
97 runtime->xidregistry.mutex = NULL;
98 }
99
Victor Stinnerccb04422017-11-16 03:20:31 -0800100 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600101}
102
Eric Snow8479a342019-03-08 23:44:33 -0700103/* This function is called from PyOS_AfterFork_Child to ensure that
104 * newly created child processes do not share locks with the parent.
105 */
106
107void
108_PyRuntimeState_ReInitThreads(void)
109{
110 // This was initially set in _PyRuntimeState_Init().
111 _PyRuntime.main_thread = PyThread_get_thread_ident();
112
113 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
114 if (_PyRuntime.interpreters.mutex == NULL) {
115 Py_FatalError("Can't initialize lock for runtime interpreters");
116 }
117
118 _PyRuntime.interpreters.main->id_mutex = PyThread_allocate_lock();
119 if (_PyRuntime.interpreters.main->id_mutex == NULL) {
120 Py_FatalError("Can't initialize ID lock for main interpreter");
121 }
122
123 _PyRuntime.xidregistry.mutex = PyThread_allocate_lock();
124 if (_PyRuntime.xidregistry.mutex == NULL) {
125 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
126 }
127}
128
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600129#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
130 WAIT_LOCK)
131#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700132
Michael W. Hudson188d4362005-06-20 16:52:57 +0000133static void _PyGILState_NoteThreadState(PyThreadState* tstate);
134
Victor Stinnera7368ac2017-11-15 18:11:45 -0800135_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600136_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700137{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600138 runtime->interpreters.next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100139
140 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
141 Create a new mutex if needed. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600142 if (runtime->interpreters.mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100143 /* Force default allocator, since _PyRuntimeState_Fini() must
144 use the same allocator than this function. */
145 PyMemAllocatorEx old_alloc;
146 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
147
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600148 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100149
150 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
151
Victor Stinnera7368ac2017-11-15 18:11:45 -0800152 if (runtime->interpreters.mutex == NULL) {
153 return _Py_INIT_ERR("Can't initialize threads for interpreter");
154 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600155 }
Victor Stinner5d926472018-03-06 14:31:37 +0100156
Victor Stinnera7368ac2017-11-15 18:11:45 -0800157 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700158}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000159
160PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000161PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200164 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000165
Victor Stinnerd4341102017-11-23 00:12:09 +0100166 if (interp == NULL) {
167 return NULL;
168 }
169
Eric Snow5be45a62019-03-08 22:47:07 -0700170 memset(interp, 0, sizeof(*interp));
Eric Snow4c6955e2018-02-16 18:53:40 -0700171 interp->id_refcount = -1;
Victor Stinnerd4341102017-11-23 00:12:09 +0100172 interp->check_interval = 100;
Victor Stinnerd4341102017-11-23 00:12:09 +0100173 interp->core_config = _PyCoreConfig_INIT;
174 interp->config = _PyMainInterpreterConfig_INIT;
Victor Stinnerd4341102017-11-23 00:12:09 +0100175 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000176#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300177#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100178 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000179#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100180 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000181#endif
182#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000183
Victor Stinnerd4341102017-11-23 00:12:09 +0100184 HEAD_LOCK();
Victor Stinnerd4341102017-11-23 00:12:09 +0100185 if (_PyRuntime.interpreters.next_id < 0) {
186 /* overflow or Py_Initialize() not called! */
187 PyErr_SetString(PyExc_RuntimeError,
188 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100189 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100190 interp = NULL;
191 } else {
192 interp->id = _PyRuntime.interpreters.next_id;
193 _PyRuntime.interpreters.next_id += 1;
Pablo Galindo95d630e2018-08-31 22:49:29 +0100194 interp->next = _PyRuntime.interpreters.head;
195 if (_PyRuntime.interpreters.main == NULL) {
196 _PyRuntime.interpreters.main = interp;
197 }
198 _PyRuntime.interpreters.head = interp;
Victor Stinnerd4341102017-11-23 00:12:09 +0100199 }
200 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000201
Pablo Galindo95d630e2018-08-31 22:49:29 +0100202 if (interp == NULL) {
203 return NULL;
204 }
205
Yury Selivanovf23746a2018-01-22 19:11:18 -0500206 interp->tstate_next_unique_id = 0;
207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000209}
210
211
212void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000213PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 PyThreadState *p;
216 HEAD_LOCK();
217 for (p = interp->tstate_head; p != NULL; p = p->next)
218 PyThreadState_Clear(p);
219 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100220 _PyCoreConfig_Clear(&interp->core_config);
221 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 Py_CLEAR(interp->codec_search_path);
223 Py_CLEAR(interp->codec_search_cache);
224 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700225 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000226 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 Py_CLEAR(interp->sysdict);
228 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200229 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400230 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300231 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600232 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200233#ifdef HAVE_FORK
234 Py_CLEAR(interp->before_forkers);
235 Py_CLEAR(interp->after_forkers_parent);
236 Py_CLEAR(interp->after_forkers_child);
237#endif
Eric Snow5be45a62019-03-08 22:47:07 -0700238 // XXX Once we have one allocator per interpreter (i.e.
239 // per-interpreter GC) we must ensure that all of the interpreter's
240 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000241}
242
243
244static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000245zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 PyThreadState *p;
248 /* No need to lock the mutex here because this should only happen
249 when the threads are all really dead (XXX famous last words). */
250 while ((p = interp->tstate_head) != NULL) {
251 PyThreadState_Delete(p);
252 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000253}
254
255
256void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000257PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 PyInterpreterState **p;
260 zapthreads(interp);
261 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600262 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 if (*p == NULL)
264 Py_FatalError(
265 "PyInterpreterState_Delete: invalid interp");
266 if (*p == interp)
267 break;
268 }
269 if (interp->tstate_head != NULL)
270 Py_FatalError("PyInterpreterState_Delete: remaining threads");
271 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600272 if (_PyRuntime.interpreters.main == interp) {
273 _PyRuntime.interpreters.main = NULL;
274 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700275 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
276 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 HEAD_UNLOCK();
Eric Snow4c6955e2018-02-16 18:53:40 -0700278 if (interp->id_mutex != NULL) {
279 PyThread_free_lock(interp->id_mutex);
280 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200281 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000282}
283
284
Eric Snow59032962018-09-14 14:17:20 -0700285/*
286 * Delete all interpreter states except the main interpreter. If there
287 * is a current interpreter state, it *must* be the main interpreter.
288 */
289void
290_PyInterpreterState_DeleteExceptMain()
291{
292 PyThreadState *tstate = PyThreadState_Swap(NULL);
293 if (tstate != NULL && tstate->interp != _PyRuntime.interpreters.main) {
294 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
295 }
296
297 HEAD_LOCK();
298 PyInterpreterState *interp = _PyRuntime.interpreters.head;
299 _PyRuntime.interpreters.head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100300 while (interp != NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700301 if (interp == _PyRuntime.interpreters.main) {
302 _PyRuntime.interpreters.main->next = NULL;
303 _PyRuntime.interpreters.head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100304 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700305 continue;
306 }
307
308 PyInterpreterState_Clear(interp); // XXX must activate?
309 zapthreads(interp);
310 if (interp->id_mutex != NULL) {
311 PyThread_free_lock(interp->id_mutex);
312 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100313 PyInterpreterState *prev_interp = interp;
314 interp = interp->next;
315 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700316 }
317 HEAD_UNLOCK();
318
319 if (_PyRuntime.interpreters.head == NULL) {
320 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
321 }
322 PyThreadState_Swap(tstate);
323}
324
325
Victor Stinnercaba55b2018-08-03 15:33:52 +0200326PyInterpreterState *
327_PyInterpreterState_Get(void)
328{
Victor Stinner50b48572018-11-01 01:51:40 +0100329 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200330 if (tstate == NULL) {
331 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
332 }
333 PyInterpreterState *interp = tstate->interp;
334 if (interp == NULL) {
335 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
336 }
337 return interp;
338}
339
340
Eric Snowe3774162017-05-22 19:46:40 -0700341int64_t
342PyInterpreterState_GetID(PyInterpreterState *interp)
343{
344 if (interp == NULL) {
345 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
346 return -1;
347 }
348 return interp->id;
349}
350
351
Eric Snow5be45a62019-03-08 22:47:07 -0700352static PyInterpreterState *
353interp_look_up_id(PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700354{
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100355 PyInterpreterState *interp = PyInterpreterState_Head();
356 while (interp != NULL) {
357 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700358 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100359 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700360 }
361 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100362 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700363 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100364 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700365 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100366 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700367}
368
Eric Snow5be45a62019-03-08 22:47:07 -0700369PyInterpreterState *
370_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
371{
372 PyInterpreterState *interp = NULL;
373 if (requested_id >= 0) {
374 HEAD_LOCK();
375 interp = interp_look_up_id(requested_id);
376 HEAD_UNLOCK();
377 }
378 if (interp == NULL && !PyErr_Occurred()) {
379 PyErr_Format(PyExc_RuntimeError,
380 "unrecognized interpreter ID %lld", requested_id);
381 }
382 return interp;
383}
384
Eric Snow4c6955e2018-02-16 18:53:40 -0700385
386int
387_PyInterpreterState_IDInitref(PyInterpreterState *interp)
388{
389 if (interp->id_mutex != NULL) {
390 return 0;
391 }
392 interp->id_mutex = PyThread_allocate_lock();
393 if (interp->id_mutex == NULL) {
394 PyErr_SetString(PyExc_RuntimeError,
395 "failed to create init interpreter ID mutex");
396 return -1;
397 }
398 interp->id_refcount = 0;
399 return 0;
400}
401
402
403void
404_PyInterpreterState_IDIncref(PyInterpreterState *interp)
405{
406 if (interp->id_mutex == NULL) {
407 return;
408 }
409 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
410 interp->id_refcount += 1;
411 PyThread_release_lock(interp->id_mutex);
412}
413
414
415void
416_PyInterpreterState_IDDecref(PyInterpreterState *interp)
417{
418 if (interp->id_mutex == NULL) {
419 return;
420 }
421 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
422 assert(interp->id_refcount != 0);
423 interp->id_refcount -= 1;
424 int64_t refcount = interp->id_refcount;
425 PyThread_release_lock(interp->id_mutex);
426
Eric Snowc11183c2019-03-15 16:35:46 -0600427 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700428 // XXX Using the "head" thread isn't strictly correct.
429 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
430 // XXX Possible GILState issues?
431 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700432 Py_EndInterpreter(tstate);
433 PyThreadState_Swap(save_tstate);
434 }
435}
436
Eric Snowc11183c2019-03-15 16:35:46 -0600437int
438_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
439{
440 return interp->requires_idref;
441}
442
443void
444_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
445{
446 interp->requires_idref = required ? 1 : 0;
447}
448
Eric Snowbe3b2952019-02-23 11:35:52 -0700449_PyCoreConfig *
450_PyInterpreterState_GetCoreConfig(PyInterpreterState *interp)
451{
452 return &interp->core_config;
453}
454
455_PyMainInterpreterConfig *
456_PyInterpreterState_GetMainConfig(PyInterpreterState *interp)
457{
458 return &interp->config;
459}
Eric Snow4c6955e2018-02-16 18:53:40 -0700460
Eric Snowc11183c2019-03-15 16:35:46 -0600461PyObject *
462_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
463{
464 if (interp->modules == NULL) {
465 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
466 return NULL;
467 }
468 return PyMapping_GetItemString(interp->modules, "__main__");
469}
470
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600471PyObject *
472PyInterpreterState_GetDict(PyInterpreterState *interp)
473{
474 if (interp->dict == NULL) {
475 interp->dict = PyDict_New();
476 if (interp->dict == NULL) {
477 PyErr_Clear();
478 }
479 }
480 /* Returning NULL means no per-interpreter dict is available. */
481 return interp->dict;
482}
483
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000484/* Default implementation for _PyThreadState_GetFrame */
485static struct _frame *
486threadstate_getframe(PyThreadState *self)
487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000489}
490
Victor Stinner45b9be52010-03-03 23:28:07 +0000491static PyThreadState *
492new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000493{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200494 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 if (_PyThreadState_GetFrame == NULL)
497 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 if (tstate != NULL) {
500 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 tstate->frame = NULL;
503 tstate->recursion_depth = 0;
504 tstate->overflowed = 0;
505 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700506 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 tstate->tracing = 0;
508 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 tstate->gilstate_counter = 0;
510 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 tstate->curexc_type = NULL;
516 tstate->curexc_value = NULL;
517 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000518
Mark Shannonae3087c2017-10-22 22:41:51 +0100519 tstate->exc_state.exc_type = NULL;
520 tstate->exc_state.exc_value = NULL;
521 tstate->exc_state.exc_traceback = NULL;
522 tstate->exc_state.previous_item = NULL;
523 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 tstate->c_profilefunc = NULL;
526 tstate->c_tracefunc = NULL;
527 tstate->c_profileobj = NULL;
528 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000529
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200530 tstate->trash_delete_nesting = 0;
531 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200532 tstate->on_delete = NULL;
533 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200534
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800535 tstate->coroutine_origin_tracking_depth = 0;
536
Yury Selivanov75445082015-05-11 22:57:16 -0400537 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400538 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400539
Yury Selivanoveb636452016-09-08 22:01:51 -0700540 tstate->async_gen_firstiter = NULL;
541 tstate->async_gen_finalizer = NULL;
542
Yury Selivanovf23746a2018-01-22 19:11:18 -0500543 tstate->context = NULL;
544 tstate->context_ver = 1;
545
546 tstate->id = ++interp->tstate_next_unique_id;
547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 if (init)
549 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200552 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200554 if (tstate->next)
555 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 interp->tstate_head = tstate;
557 HEAD_UNLOCK();
558 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000561}
562
Victor Stinner45b9be52010-03-03 23:28:07 +0000563PyThreadState *
564PyThreadState_New(PyInterpreterState *interp)
565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000567}
568
569PyThreadState *
570_PyThreadState_Prealloc(PyInterpreterState *interp)
571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000573}
574
575void
576_PyThreadState_Init(PyThreadState *tstate)
577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000579}
580
Martin v. Löwis1a214512008-06-11 05:26:20 +0000581PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200582PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000583{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200584 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100585 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000587 if (module->m_slots) {
588 return NULL;
589 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (index == 0)
591 return NULL;
592 if (state->modules_by_index == NULL)
593 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200594 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 return NULL;
596 res = PyList_GET_ITEM(state->modules_by_index, index);
597 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000598}
599
600int
601_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
602{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000603 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300604 if (!def) {
605 assert(PyErr_Occurred());
606 return -1;
607 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000608 if (def->m_slots) {
609 PyErr_SetString(PyExc_SystemError,
610 "PyState_AddModule called on module with slots");
611 return -1;
612 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100613 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (!state->modules_by_index) {
615 state->modules_by_index = PyList_New(0);
616 if (!state->modules_by_index)
617 return -1;
618 }
619 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
620 if (PyList_Append(state->modules_by_index, Py_None) < 0)
621 return -1;
622 Py_INCREF(module);
623 return PyList_SetItem(state->modules_by_index,
624 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000625}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000626
Martin v. Löwis7800f752012-06-22 12:20:55 +0200627int
628PyState_AddModule(PyObject* module, struct PyModuleDef* def)
629{
630 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100631 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200632 if (!def) {
633 Py_FatalError("PyState_AddModule: Module Definition is NULL");
634 return -1;
635 }
636 index = def->m_base.m_index;
637 if (state->modules_by_index) {
638 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
639 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
640 Py_FatalError("PyState_AddModule: Module already added!");
641 return -1;
642 }
643 }
644 }
645 return _PyState_AddModule(module, def);
646}
647
648int
649PyState_RemoveModule(struct PyModuleDef* def)
650{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000651 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200652 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000653 if (def->m_slots) {
654 PyErr_SetString(PyExc_SystemError,
655 "PyState_RemoveModule called on module with slots");
656 return -1;
657 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100658 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200659 if (index == 0) {
660 Py_FatalError("PyState_RemoveModule: Module index invalid.");
661 return -1;
662 }
663 if (state->modules_by_index == NULL) {
664 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
665 return -1;
666 }
667 if (index > PyList_GET_SIZE(state->modules_by_index)) {
668 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
669 return -1;
670 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700671 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200672 return PyList_SetItem(state->modules_by_index, index, Py_None);
673}
674
Antoine Pitrou40322e62013-08-11 00:30:09 +0200675/* used by import.c:PyImport_Cleanup */
676void
677_PyState_ClearModules(void)
678{
Victor Stinner9204fb82018-10-30 15:13:17 +0100679 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200680 if (state->modules_by_index) {
681 Py_ssize_t i;
682 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
683 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
684 if (PyModule_Check(m)) {
685 /* cleanup the saved copy of module dicts */
686 PyModuleDef *md = PyModule_GetDef(m);
687 if (md)
688 Py_CLEAR(md->m_base.m_copy);
689 }
690 }
691 /* Setting modules_by_index to NULL could be dangerous, so we
692 clear the list instead. */
693 if (PyList_SetSlice(state->modules_by_index,
694 0, PyList_GET_SIZE(state->modules_by_index),
695 NULL))
696 PyErr_WriteUnraisable(state->modules_by_index);
697 }
698}
699
Guido van Rossuma027efa1997-05-05 20:56:21 +0000700void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000701PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000702{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200703 int verbose = tstate->interp->core_config.verbose;
704
705 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 fprintf(stderr,
707 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 Py_CLEAR(tstate->dict);
712 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 Py_CLEAR(tstate->curexc_type);
715 Py_CLEAR(tstate->curexc_value);
716 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000717
Mark Shannonae3087c2017-10-22 22:41:51 +0100718 Py_CLEAR(tstate->exc_state.exc_type);
719 Py_CLEAR(tstate->exc_state.exc_value);
720 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300721
Mark Shannonae3087c2017-10-22 22:41:51 +0100722 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200723 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100724 fprintf(stderr,
725 "PyThreadState_Clear: warning: thread still has a generator\n");
726 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 tstate->c_profilefunc = NULL;
729 tstate->c_tracefunc = NULL;
730 Py_CLEAR(tstate->c_profileobj);
731 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400732
733 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700734 Py_CLEAR(tstate->async_gen_firstiter);
735 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500736
737 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000738}
739
740
Guido van Rossum29757862001-01-23 01:46:06 +0000741/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
742static void
743tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000744{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 if (tstate == NULL)
747 Py_FatalError("PyThreadState_Delete: NULL tstate");
748 interp = tstate->interp;
749 if (interp == NULL)
750 Py_FatalError("PyThreadState_Delete: NULL interp");
751 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200752 if (tstate->prev)
753 tstate->prev->next = tstate->next;
754 else
755 interp->tstate_head = tstate->next;
756 if (tstate->next)
757 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200759 if (tstate->on_delete != NULL) {
760 tstate->on_delete(tstate->on_delete_data);
761 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200762 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000763}
764
765
Guido van Rossum29757862001-01-23 01:46:06 +0000766void
767PyThreadState_Delete(PyThreadState *tstate)
768{
Victor Stinner50b48572018-11-01 01:51:40 +0100769 if (tstate == _PyThreadState_GET())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600771 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900772 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600773 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900774 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600775 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200776 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000777}
778
779
Guido van Rossum29757862001-01-23 01:46:06 +0000780void
781PyThreadState_DeleteCurrent()
782{
Victor Stinner50b48572018-11-01 01:51:40 +0100783 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 if (tstate == NULL)
785 Py_FatalError(
786 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100787 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600788 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900789 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600790 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900791 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600792 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100793 _PyThreadState_SET(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000795}
Guido van Rossum29757862001-01-23 01:46:06 +0000796
797
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200798/*
799 * Delete all thread states except the one passed as argument.
800 * Note that, if there is a current thread state, it *must* be the one
801 * passed as argument. Also, this won't touch any other interpreters
802 * than the current one, since we don't know which thread state should
803 * be kept in those other interpreteres.
804 */
805void
806_PyThreadState_DeleteExcept(PyThreadState *tstate)
807{
808 PyInterpreterState *interp = tstate->interp;
809 PyThreadState *p, *next, *garbage;
810 HEAD_LOCK();
811 /* Remove all thread states, except tstate, from the linked list of
812 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200813 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200814 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200815 if (garbage == tstate)
816 garbage = tstate->next;
817 if (tstate->prev)
818 tstate->prev->next = tstate->next;
819 if (tstate->next)
820 tstate->next->prev = tstate->prev;
821 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200822 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200823 HEAD_UNLOCK();
824 /* Clear and deallocate all stale thread states. Even if this
825 executes Python code, we should be safe since it executes
826 in the current thread, not one of the stale threads. */
827 for (p = garbage; p; p = next) {
828 next = p->next;
829 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200830 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200831 }
832}
833
834
Guido van Rossuma027efa1997-05-05 20:56:21 +0000835PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100836_PyThreadState_UncheckedGet(void)
837{
Victor Stinner50b48572018-11-01 01:51:40 +0100838 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100839}
840
841
842PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000843PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000844{
Victor Stinner50b48572018-11-01 01:51:40 +0100845 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 if (tstate == NULL)
847 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000850}
851
852
853PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000854PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000855{
Victor Stinner50b48572018-11-01 01:51:40 +0100856 PyThreadState *oldts = _PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000857
Victor Stinner9204fb82018-10-30 15:13:17 +0100858 _PyThreadState_SET(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 /* It should not be possible for more than one thread state
860 to be used for a thread. Check this the best we can in debug
861 builds.
862 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200863#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (newts) {
865 /* This can be called from PyEval_RestoreThread(). Similar
866 to it, we need to ensure errno doesn't change.
867 */
868 int err = errno;
869 PyThreadState *check = PyGILState_GetThisThreadState();
870 if (check && check->interp == newts->interp && check != newts)
871 Py_FatalError("Invalid thread state for this thread");
872 errno = err;
873 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000874#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000876}
Guido van Rossumede04391998-04-10 20:18:25 +0000877
878/* An extension mechanism to store arbitrary additional per-thread state.
879 PyThreadState_GetDict() returns a dictionary that can be used to hold such
880 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000881 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
882 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000883
884PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000885PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000886{
Victor Stinner50b48572018-11-01 01:51:40 +0100887 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 if (tstate == NULL)
889 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000890
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 if (tstate->dict == NULL) {
892 PyObject *d;
893 tstate->dict = d = PyDict_New();
894 if (d == NULL)
895 PyErr_Clear();
896 }
897 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000898}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000899
900
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000901/* Asynchronously raise an exception in a thread.
902 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000903 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000904 to call this, or use ctypes. Must be called with the GIL held.
905 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
906 match any known thread id). Can be called with exc=NULL to clear an
907 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000908
909int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200910PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
911{
Victor Stinner9204fb82018-10-30 15:13:17 +0100912 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000914
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 /* Although the GIL is held, a few C API functions can be called
916 * without the GIL held, and in particular some that create and
917 * destroy thread and interpreter states. Those can mutate the
918 * list of thread states we're traversing, so to prevent that we lock
919 * head_mutex for the duration.
920 */
921 HEAD_LOCK();
922 for (p = interp->tstate_head; p != NULL; p = p->next) {
923 if (p->thread_id == id) {
924 /* Tricky: we need to decref the current value
925 * (if any) in p->async_exc, but that can in turn
926 * allow arbitrary Python code to run, including
927 * perhaps calls to this function. To prevent
928 * deadlock, we need to release head_mutex before
929 * the decref.
930 */
931 PyObject *old_exc = p->async_exc;
932 Py_XINCREF(exc);
933 p->async_exc = exc;
934 HEAD_UNLOCK();
935 Py_XDECREF(old_exc);
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100936 _PyEval_SignalAsyncExc();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 return 1;
938 }
939 }
940 HEAD_UNLOCK();
941 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000942}
943
944
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000945/* Routines for advanced debuggers, requested by David Beazley.
946 Don't use unless you know what you are doing! */
947
948PyInterpreterState *
949PyInterpreterState_Head(void)
950{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600951 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000952}
953
954PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700955PyInterpreterState_Main(void)
956{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600957 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700958}
959
960PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000961PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000963}
964
965PyThreadState *
966PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000968}
969
970PyThreadState *
971PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000973}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000974
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000975/* The implementation of sys._current_frames(). This is intended to be
976 called with the GIL held, as it will be when called via
977 sys._current_frames(). It's possible it would work fine even without
978 the GIL held, but haven't thought enough about that.
979*/
980PyObject *
981_PyThread_CurrentFrames(void)
982{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 PyObject *result;
984 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 result = PyDict_New();
987 if (result == NULL)
988 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 /* for i in all interpreters:
991 * for t in all of i's thread states:
992 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200993 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 * need to grab head_mutex for the duration.
995 */
996 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600997 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 PyThreadState *t;
999 for (t = i->tstate_head; t != NULL; t = t->next) {
1000 PyObject *id;
1001 int stat;
1002 struct _frame *frame = t->frame;
1003 if (frame == NULL)
1004 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001005 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 if (id == NULL)
1007 goto Fail;
1008 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1009 Py_DECREF(id);
1010 if (stat < 0)
1011 goto Fail;
1012 }
1013 }
1014 HEAD_UNLOCK();
1015 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001016
1017 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 HEAD_UNLOCK();
1019 Py_DECREF(result);
1020 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001021}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001022
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001023/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001024
1025/* Keep this as a static, as it is not reliable! It can only
1026 ever be compared to the state for the *current* thread.
1027 * If not equal, then it doesn't matter that the actual
1028 value may change immediately after comparison, as it can't
1029 possibly change to the current thread's state.
1030 * If equal, then the current thread holds the lock, so the value can't
1031 change until we yield the lock.
1032*/
1033static int
1034PyThreadState_IsCurrent(PyThreadState *tstate)
1035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 /* Must be the tstate for this thread */
1037 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinner50b48572018-11-01 01:51:40 +01001038 return tstate == _PyThreadState_GET();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001039}
1040
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001041/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001042 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001043*/
Tim Peters19717fa2004-10-09 17:38:29 +00001044void
1045_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001048 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1049 Py_FatalError("Could not allocate TSS entry");
1050 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001051 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001052 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001056}
1057
Victor Stinner861d9ab2016-03-16 22:45:24 +01001058PyInterpreterState *
1059_PyGILState_GetInterpreterStateUnsafe(void)
1060{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001061 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001062}
1063
Tim Peters19717fa2004-10-09 17:38:29 +00001064void
1065_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001066{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001067 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001068 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001069}
1070
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001071/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001072 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001073 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001074 */
1075void
1076_PyGILState_Reinit(void)
1077{
Victor Stinner5d926472018-03-06 14:31:37 +01001078 /* Force default allocator, since _PyRuntimeState_Fini() must
1079 use the same allocator than this function. */
1080 PyMemAllocatorEx old_alloc;
1081 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1082
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001083 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +01001084
1085 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1086
1087 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001088 Py_FatalError("Can't initialize threads for interpreter");
Victor Stinner5d926472018-03-06 14:31:37 +01001089 }
1090
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001091 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001092 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
1093 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1094 Py_FatalError("Could not allocate TSS entry");
1095 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001096
Charles-François Natalia233df82011-11-22 19:49:51 +01001097 /* If the thread had an associated auto thread state, reassociate it with
1098 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001099 if (tstate &&
1100 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
1101 {
1102 Py_FatalError("Couldn't create autoTSSkey mapping");
1103 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001104}
1105
Michael W. Hudson188d4362005-06-20 16:52:57 +00001106/* When a thread state is created for a thread by some mechanism other than
1107 PyGILState_Ensure, it's important that the GILState machinery knows about
1108 it so it doesn't try to create another thread state for the thread (this is
1109 a better fix for SF bug #1010677 than the first one attempted).
1110*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001111static void
Michael W. Hudson188d4362005-06-20 16:52:57 +00001112_PyGILState_NoteThreadState(PyThreadState* tstate)
1113{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001114 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001115 threadstate created in Py_Initialize(). Don't do anything for now
1116 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001117 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001119
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001120 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001121
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 The only situation where you can legitimately have more than one
1123 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001124 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001125
Victor Stinner590cebe2013-12-13 11:08:56 +01001126 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1127 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001128
Victor Stinner590cebe2013-12-13 11:08:56 +01001129 The first thread state created for that given OS level thread will
1130 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001132 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
1133 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1134 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001135 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001136 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001137 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001138 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 /* PyGILState_Release must not try to delete this thread state. */
1141 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001142}
1143
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001144/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001145PyThreadState *
1146PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001147{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001148 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001150 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001151}
1152
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001153int
1154PyGILState_Check(void)
1155{
Victor Stinner8a1be612016-03-14 22:07:55 +01001156 PyThreadState *tstate;
1157
1158 if (!_PyGILState_check_enabled)
1159 return 1;
1160
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001161 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001162 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001163 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001164
Victor Stinner50b48572018-11-01 01:51:40 +01001165 tstate = _PyThreadState_GET();
Victor Stinner8a1be612016-03-14 22:07:55 +01001166 if (tstate == NULL)
1167 return 0;
1168
1169 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001170}
1171
Tim Peters19717fa2004-10-09 17:38:29 +00001172PyGILState_STATE
1173PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 int current;
1176 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001177 int need_init_threads = 0;
1178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 /* Note that we do not auto-init Python here - apart from
1180 potential races with 2 threads auto-initializing, pep-311
1181 spells out other issues. Embedders are expected to have
1182 called Py_Initialize() and usually PyEval_InitThreads().
1183 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001184 /* Py_Initialize() hasn't been called! */
1185 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001186
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001187 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001189 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001192 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 if (tcur == NULL)
1194 Py_FatalError("Couldn't create thread-state for new thread");
1195 /* This is our thread state! We'll need to delete it in the
1196 matching call to PyGILState_Release(). */
1197 tcur->gilstate_counter = 0;
1198 current = 0; /* new thread state is never current */
1199 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001200 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001202 }
1203
1204 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001206 }
1207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 /* Update our counter in the thread-state - no need for locks:
1209 - tcur will remain valid as we hold the GIL.
1210 - the counter is safe as we are the only thread "allowed"
1211 to modify this value
1212 */
1213 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001214
1215 if (need_init_threads) {
1216 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1217 called from a new thread for the first time, we need the create the
1218 GIL. */
1219 PyEval_InitThreads();
1220 }
1221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001223}
1224
Tim Peters19717fa2004-10-09 17:38:29 +00001225void
1226PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001227{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001228 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1229 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 if (tcur == NULL)
1231 Py_FatalError("auto-releasing thread-state, "
1232 "but no thread-state for this thread");
1233 /* We must hold the GIL and have our thread state current */
1234 /* XXX - remove the check - the assert should be fine,
1235 but while this is very new (April 2003), the extra check
1236 by release-only users can't hurt.
1237 */
1238 if (! PyThreadState_IsCurrent(tcur))
1239 Py_FatalError("This thread state must be current when releasing");
1240 assert(PyThreadState_IsCurrent(tcur));
1241 --tcur->gilstate_counter;
1242 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 /* If we're going to destroy this thread-state, we must
1245 * clear it while the GIL is held, as destructors may run.
1246 */
1247 if (tcur->gilstate_counter == 0) {
1248 /* can't have been locked when we created it */
1249 assert(oldstate == PyGILState_UNLOCKED);
1250 PyThreadState_Clear(tcur);
1251 /* Delete the thread-state. Note this releases the GIL too!
1252 * It's vital that the GIL be held here, to avoid shutdown
1253 * races; see bugs 225673 and 1061968 (that nasty bug has a
1254 * habit of coming back).
1255 */
1256 PyThreadState_DeleteCurrent();
1257 }
1258 /* Release the lock if necessary */
1259 else if (oldstate == PyGILState_UNLOCKED)
1260 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001261}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001262
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001263
Eric Snow7f8bfc92018-01-29 18:23:44 -07001264/**************************/
1265/* cross-interpreter data */
1266/**************************/
1267
1268/* cross-interpreter data */
1269
1270crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1271
1272/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1273 to keep the registry code separate. */
1274static crossinterpdatafunc
1275_lookup_getdata(PyObject *obj)
1276{
1277 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1278 if (getdata == NULL && PyErr_Occurred() == 0)
1279 PyErr_Format(PyExc_ValueError,
1280 "%S does not support cross-interpreter data", obj);
1281 return getdata;
1282}
1283
1284int
1285_PyObject_CheckCrossInterpreterData(PyObject *obj)
1286{
1287 crossinterpdatafunc getdata = _lookup_getdata(obj);
1288 if (getdata == NULL) {
1289 return -1;
1290 }
1291 return 0;
1292}
1293
1294static int
1295_check_xidata(_PyCrossInterpreterData *data)
1296{
1297 // data->data can be anything, including NULL, so we don't check it.
1298
1299 // data->obj may be NULL, so we don't check it.
1300
1301 if (data->interp < 0) {
1302 PyErr_SetString(PyExc_SystemError, "missing interp");
1303 return -1;
1304 }
1305
1306 if (data->new_object == NULL) {
1307 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1308 return -1;
1309 }
1310
1311 // data->free may be NULL, so we don't check it.
1312
1313 return 0;
1314}
1315
1316int
1317_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1318{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001319 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001320 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001321 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001322
1323 // Reset data before re-populating.
1324 *data = (_PyCrossInterpreterData){0};
1325 data->free = PyMem_RawFree; // Set a default that may be overridden.
1326
1327 // Call the "getdata" func for the object.
1328 Py_INCREF(obj);
1329 crossinterpdatafunc getdata = _lookup_getdata(obj);
1330 if (getdata == NULL) {
1331 Py_DECREF(obj);
1332 return -1;
1333 }
1334 int res = getdata(obj, data);
1335 Py_DECREF(obj);
1336 if (res != 0) {
1337 return -1;
1338 }
1339
1340 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001341 data->interp = interp->id;
1342 if (_check_xidata(data) != 0) {
1343 _PyCrossInterpreterData_Release(data);
1344 return -1;
1345 }
1346
1347 return 0;
1348}
1349
Victor Stinner4d61e6e2019-03-04 14:21:28 +01001350static void
Eric Snow63799132018-06-01 18:45:20 -06001351_release_xidata(void *arg)
1352{
1353 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1354 if (data->free != NULL) {
1355 data->free(data->data);
1356 }
1357 Py_XDECREF(data->obj);
Victor Stinner4d61e6e2019-03-04 14:21:28 +01001358}
1359
1360static void
1361_call_in_interpreter(PyInterpreterState *interp,
1362 void (*func)(void *), void *arg)
1363{
1364 /* We would use Py_AddPendingCall() if it weren't specific to the
1365 * main interpreter (see bpo-33608). In the meantime we take a
1366 * naive approach.
1367 */
1368 PyThreadState *save_tstate = NULL;
1369 if (interp != _PyInterpreterState_Get()) {
1370 // XXX Using the "head" thread isn't strictly correct.
1371 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1372 // XXX Possible GILState issues?
1373 save_tstate = PyThreadState_Swap(tstate);
1374 }
1375
1376 func(arg);
1377
1378 // Switch back.
1379 if (save_tstate != NULL) {
1380 PyThreadState_Swap(save_tstate);
1381 }
Eric Snow63799132018-06-01 18:45:20 -06001382}
1383
Eric Snow7f8bfc92018-01-29 18:23:44 -07001384void
1385_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1386{
1387 if (data->data == NULL && data->obj == NULL) {
1388 // Nothing to release!
1389 return;
1390 }
1391
Victor Stinner4d61e6e2019-03-04 14:21:28 +01001392 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001393 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1394 if (interp == NULL) {
1395 // The intepreter was already destroyed.
1396 if (data->free != NULL) {
1397 // XXX Someone leaked some memory...
1398 }
1399 return;
1400 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001401
Eric Snow7f8bfc92018-01-29 18:23:44 -07001402 // "Release" the data and/or the object.
Victor Stinner4d61e6e2019-03-04 14:21:28 +01001403 _call_in_interpreter(interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001404}
1405
1406PyObject *
1407_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1408{
1409 return data->new_object(data);
1410}
1411
1412/* registry of {type -> crossinterpdatafunc} */
1413
1414/* For now we use a global registry of shareable classes. An
1415 alternative would be to add a tp_* slot for a class's
1416 crossinterpdatafunc. It would be simpler and more efficient. */
1417
1418static int
1419_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1420{
1421 // Note that we effectively replace already registered classes
1422 // rather than failing.
1423 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1424 if (newhead == NULL)
1425 return -1;
1426 newhead->cls = cls;
1427 newhead->getdata = getdata;
1428 newhead->next = _PyRuntime.xidregistry.head;
1429 _PyRuntime.xidregistry.head = newhead;
1430 return 0;
1431}
1432
1433static void _register_builtins_for_crossinterpreter_data(void);
1434
1435int
Eric Snowc11183c2019-03-15 16:35:46 -06001436_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001437 crossinterpdatafunc getdata)
1438{
1439 if (!PyType_Check(cls)) {
1440 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1441 return -1;
1442 }
1443 if (getdata == NULL) {
1444 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1445 return -1;
1446 }
1447
1448 // Make sure the class isn't ever deallocated.
1449 Py_INCREF((PyObject *)cls);
1450
1451 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1452 if (_PyRuntime.xidregistry.head == NULL) {
1453 _register_builtins_for_crossinterpreter_data();
1454 }
1455 int res = _register_xidata(cls, getdata);
1456 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1457 return res;
1458}
1459
Eric Snow6d2cd902018-05-16 15:04:57 -04001460/* Cross-interpreter objects are looked up by exact match on the class.
1461 We can reassess this policy when we move from a global registry to a
1462 tp_* slot. */
1463
Eric Snow7f8bfc92018-01-29 18:23:44 -07001464crossinterpdatafunc
1465_PyCrossInterpreterData_Lookup(PyObject *obj)
1466{
1467 PyObject *cls = PyObject_Type(obj);
1468 crossinterpdatafunc getdata = NULL;
1469 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1470 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1471 if (cur == NULL) {
1472 _register_builtins_for_crossinterpreter_data();
1473 cur = _PyRuntime.xidregistry.head;
1474 }
1475 for(; cur != NULL; cur = cur->next) {
1476 if (cur->cls == (PyTypeObject *)cls) {
1477 getdata = cur->getdata;
1478 break;
1479 }
1480 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001481 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001482 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1483 return getdata;
1484}
1485
1486/* cross-interpreter data for builtin types */
1487
Eric Snow6d2cd902018-05-16 15:04:57 -04001488struct _shared_bytes_data {
1489 char *bytes;
1490 Py_ssize_t len;
1491};
1492
Eric Snow7f8bfc92018-01-29 18:23:44 -07001493static PyObject *
1494_new_bytes_object(_PyCrossInterpreterData *data)
1495{
Eric Snow6d2cd902018-05-16 15:04:57 -04001496 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1497 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001498}
1499
1500static int
1501_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1502{
Eric Snow6d2cd902018-05-16 15:04:57 -04001503 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1504 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1505 return -1;
1506 }
1507 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001508 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001509 data->obj = obj; // Will be "released" (decref'ed) when data released.
1510 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001511 data->free = PyMem_Free;
1512 return 0;
1513}
1514
1515struct _shared_str_data {
1516 int kind;
1517 const void *buffer;
1518 Py_ssize_t len;
1519};
1520
1521static PyObject *
1522_new_str_object(_PyCrossInterpreterData *data)
1523{
1524 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1525 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1526}
1527
1528static int
1529_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1530{
1531 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1532 shared->kind = PyUnicode_KIND(obj);
1533 shared->buffer = PyUnicode_DATA(obj);
1534 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1535 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001536 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001537 data->obj = obj; // Will be "released" (decref'ed) when data released.
1538 data->new_object = _new_str_object;
1539 data->free = PyMem_Free;
1540 return 0;
1541}
1542
1543static PyObject *
1544_new_long_object(_PyCrossInterpreterData *data)
1545{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001546 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001547}
1548
1549static int
1550_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1551{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001552 /* Note that this means the size of shareable ints is bounded by
1553 * sys.maxsize. Hence on 32-bit architectures that is half the
1554 * size of maximum shareable ints on 64-bit.
1555 */
1556 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001557 if (value == -1 && PyErr_Occurred()) {
1558 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1559 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1560 }
1561 return -1;
1562 }
1563 data->data = (void *)value;
1564 data->obj = NULL;
1565 data->new_object = _new_long_object;
1566 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001567 return 0;
1568}
1569
1570static PyObject *
1571_new_none_object(_PyCrossInterpreterData *data)
1572{
1573 // XXX Singleton refcounts are problematic across interpreters...
1574 Py_INCREF(Py_None);
1575 return Py_None;
1576}
1577
1578static int
1579_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1580{
1581 data->data = NULL;
1582 // data->obj remains NULL
1583 data->new_object = _new_none_object;
1584 data->free = NULL; // There is nothing to free.
1585 return 0;
1586}
1587
1588static void
1589_register_builtins_for_crossinterpreter_data(void)
1590{
1591 // None
1592 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1593 Py_FatalError("could not register None for cross-interpreter sharing");
1594 }
1595
Eric Snow6d2cd902018-05-16 15:04:57 -04001596 // int
1597 if (_register_xidata(&PyLong_Type, _long_shared) != 0) {
1598 Py_FatalError("could not register int for cross-interpreter sharing");
1599 }
1600
Eric Snow7f8bfc92018-01-29 18:23:44 -07001601 // bytes
1602 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1603 Py_FatalError("could not register bytes for cross-interpreter sharing");
1604 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001605
1606 // str
1607 if (_register_xidata(&PyUnicode_Type, _str_shared) != 0) {
1608 Py_FatalError("could not register str for cross-interpreter sharing");
1609 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001610}
1611
1612
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001613#ifdef __cplusplus
1614}
1615#endif