blob: 3978baa7af89d8afce7d9f5764a7c99540d771a6 [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
95 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060096}
97
Eric Snow8479a342019-03-08 23:44:33 -070098/* This function is called from PyOS_AfterFork_Child to ensure that
99 * newly created child processes do not share locks with the parent.
100 */
101
102void
103_PyRuntimeState_ReInitThreads(void)
104{
105 // This was initially set in _PyRuntimeState_Init().
106 _PyRuntime.main_thread = PyThread_get_thread_ident();
107
108 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
109 if (_PyRuntime.interpreters.mutex == NULL) {
110 Py_FatalError("Can't initialize lock for runtime interpreters");
111 }
112
113 _PyRuntime.interpreters.main->id_mutex = PyThread_allocate_lock();
114 if (_PyRuntime.interpreters.main->id_mutex == NULL) {
115 Py_FatalError("Can't initialize ID lock for main interpreter");
116 }
117
118 _PyRuntime.xidregistry.mutex = PyThread_allocate_lock();
119 if (_PyRuntime.xidregistry.mutex == NULL) {
120 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
121 }
122}
123
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600124#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
125 WAIT_LOCK)
126#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700127
Michael W. Hudson188d4362005-06-20 16:52:57 +0000128static void _PyGILState_NoteThreadState(PyThreadState* tstate);
129
Victor Stinnera7368ac2017-11-15 18:11:45 -0800130_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600131_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700132{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600133 runtime->interpreters.next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100134
135 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
136 Create a new mutex if needed. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600137 if (runtime->interpreters.mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100138 /* Force default allocator, since _PyRuntimeState_Fini() must
139 use the same allocator than this function. */
140 PyMemAllocatorEx old_alloc;
141 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
142
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600143 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100144
145 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
146
Victor Stinnera7368ac2017-11-15 18:11:45 -0800147 if (runtime->interpreters.mutex == NULL) {
148 return _Py_INIT_ERR("Can't initialize threads for interpreter");
149 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600150 }
Victor Stinner5d926472018-03-06 14:31:37 +0100151
Victor Stinnera7368ac2017-11-15 18:11:45 -0800152 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700153}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000154
155PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000156PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200159 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000160
Victor Stinnerd4341102017-11-23 00:12:09 +0100161 if (interp == NULL) {
162 return NULL;
163 }
164
Eric Snow5be45a62019-03-08 22:47:07 -0700165 memset(interp, 0, sizeof(*interp));
Eric Snow4c6955e2018-02-16 18:53:40 -0700166 interp->id_refcount = -1;
Victor Stinnerd4341102017-11-23 00:12:09 +0100167 interp->check_interval = 100;
Victor Stinnerd4341102017-11-23 00:12:09 +0100168 interp->core_config = _PyCoreConfig_INIT;
169 interp->config = _PyMainInterpreterConfig_INIT;
Victor Stinnerd4341102017-11-23 00:12:09 +0100170 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000171#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300172#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100173 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000174#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100175 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000176#endif
177#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000178
Victor Stinnerd4341102017-11-23 00:12:09 +0100179 HEAD_LOCK();
Victor Stinnerd4341102017-11-23 00:12:09 +0100180 if (_PyRuntime.interpreters.next_id < 0) {
181 /* overflow or Py_Initialize() not called! */
182 PyErr_SetString(PyExc_RuntimeError,
183 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100184 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100185 interp = NULL;
186 } else {
187 interp->id = _PyRuntime.interpreters.next_id;
188 _PyRuntime.interpreters.next_id += 1;
Pablo Galindo95d630e2018-08-31 22:49:29 +0100189 interp->next = _PyRuntime.interpreters.head;
190 if (_PyRuntime.interpreters.main == NULL) {
191 _PyRuntime.interpreters.main = interp;
192 }
193 _PyRuntime.interpreters.head = interp;
Victor Stinnerd4341102017-11-23 00:12:09 +0100194 }
195 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000196
Pablo Galindo95d630e2018-08-31 22:49:29 +0100197 if (interp == NULL) {
198 return NULL;
199 }
200
Yury Selivanovf23746a2018-01-22 19:11:18 -0500201 interp->tstate_next_unique_id = 0;
202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000204}
205
206
207void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000208PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000209{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 PyThreadState *p;
211 HEAD_LOCK();
212 for (p = interp->tstate_head; p != NULL; p = p->next)
213 PyThreadState_Clear(p);
214 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100215 _PyCoreConfig_Clear(&interp->core_config);
216 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 Py_CLEAR(interp->codec_search_path);
218 Py_CLEAR(interp->codec_search_cache);
219 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700220 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 Py_CLEAR(interp->sysdict);
223 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200224 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400225 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300226 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200227#ifdef HAVE_FORK
228 Py_CLEAR(interp->before_forkers);
229 Py_CLEAR(interp->after_forkers_parent);
230 Py_CLEAR(interp->after_forkers_child);
231#endif
Eric Snow5be45a62019-03-08 22:47:07 -0700232 // XXX Once we have one allocator per interpreter (i.e.
233 // per-interpreter GC) we must ensure that all of the interpreter's
234 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000235}
236
237
238static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000239zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 PyThreadState *p;
242 /* No need to lock the mutex here because this should only happen
243 when the threads are all really dead (XXX famous last words). */
244 while ((p = interp->tstate_head) != NULL) {
245 PyThreadState_Delete(p);
246 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000247}
248
249
250void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000251PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000252{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 PyInterpreterState **p;
254 zapthreads(interp);
255 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600256 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000257 if (*p == NULL)
258 Py_FatalError(
259 "PyInterpreterState_Delete: invalid interp");
260 if (*p == interp)
261 break;
262 }
263 if (interp->tstate_head != NULL)
264 Py_FatalError("PyInterpreterState_Delete: remaining threads");
265 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600266 if (_PyRuntime.interpreters.main == interp) {
267 _PyRuntime.interpreters.main = NULL;
268 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700269 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
270 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 HEAD_UNLOCK();
Eric Snow4c6955e2018-02-16 18:53:40 -0700272 if (interp->id_mutex != NULL) {
273 PyThread_free_lock(interp->id_mutex);
274 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200275 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000276}
277
278
Eric Snow59032962018-09-14 14:17:20 -0700279/*
280 * Delete all interpreter states except the main interpreter. If there
281 * is a current interpreter state, it *must* be the main interpreter.
282 */
283void
284_PyInterpreterState_DeleteExceptMain()
285{
286 PyThreadState *tstate = PyThreadState_Swap(NULL);
287 if (tstate != NULL && tstate->interp != _PyRuntime.interpreters.main) {
288 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
289 }
290
291 HEAD_LOCK();
292 PyInterpreterState *interp = _PyRuntime.interpreters.head;
293 _PyRuntime.interpreters.head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100294 while (interp != NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700295 if (interp == _PyRuntime.interpreters.main) {
296 _PyRuntime.interpreters.main->next = NULL;
297 _PyRuntime.interpreters.head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100298 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700299 continue;
300 }
301
302 PyInterpreterState_Clear(interp); // XXX must activate?
303 zapthreads(interp);
304 if (interp->id_mutex != NULL) {
305 PyThread_free_lock(interp->id_mutex);
306 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100307 PyInterpreterState *prev_interp = interp;
308 interp = interp->next;
309 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700310 }
311 HEAD_UNLOCK();
312
313 if (_PyRuntime.interpreters.head == NULL) {
314 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
315 }
316 PyThreadState_Swap(tstate);
317}
318
319
Victor Stinnercaba55b2018-08-03 15:33:52 +0200320PyInterpreterState *
321_PyInterpreterState_Get(void)
322{
Victor Stinner50b48572018-11-01 01:51:40 +0100323 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200324 if (tstate == NULL) {
325 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
326 }
327 PyInterpreterState *interp = tstate->interp;
328 if (interp == NULL) {
329 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
330 }
331 return interp;
332}
333
334
Eric Snowe3774162017-05-22 19:46:40 -0700335int64_t
336PyInterpreterState_GetID(PyInterpreterState *interp)
337{
338 if (interp == NULL) {
339 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
340 return -1;
341 }
342 return interp->id;
343}
344
345
Eric Snow5be45a62019-03-08 22:47:07 -0700346static PyInterpreterState *
347interp_look_up_id(PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700348{
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100349 PyInterpreterState *interp = PyInterpreterState_Head();
350 while (interp != NULL) {
351 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700352 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100353 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700354 }
355 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100356 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700357 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100358 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700359 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100360 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700361}
362
Eric Snow5be45a62019-03-08 22:47:07 -0700363PyInterpreterState *
364_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
365{
366 PyInterpreterState *interp = NULL;
367 if (requested_id >= 0) {
368 HEAD_LOCK();
369 interp = interp_look_up_id(requested_id);
370 HEAD_UNLOCK();
371 }
372 if (interp == NULL && !PyErr_Occurred()) {
373 PyErr_Format(PyExc_RuntimeError,
374 "unrecognized interpreter ID %lld", requested_id);
375 }
376 return interp;
377}
378
Eric Snow4c6955e2018-02-16 18:53:40 -0700379
380int
381_PyInterpreterState_IDInitref(PyInterpreterState *interp)
382{
383 if (interp->id_mutex != NULL) {
384 return 0;
385 }
386 interp->id_mutex = PyThread_allocate_lock();
387 if (interp->id_mutex == NULL) {
388 PyErr_SetString(PyExc_RuntimeError,
389 "failed to create init interpreter ID mutex");
390 return -1;
391 }
392 interp->id_refcount = 0;
393 return 0;
394}
395
396
397void
398_PyInterpreterState_IDIncref(PyInterpreterState *interp)
399{
400 if (interp->id_mutex == NULL) {
401 return;
402 }
403 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
404 interp->id_refcount += 1;
405 PyThread_release_lock(interp->id_mutex);
406}
407
408
409void
410_PyInterpreterState_IDDecref(PyInterpreterState *interp)
411{
412 if (interp->id_mutex == NULL) {
413 return;
414 }
415 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
416 assert(interp->id_refcount != 0);
417 interp->id_refcount -= 1;
418 int64_t refcount = interp->id_refcount;
419 PyThread_release_lock(interp->id_mutex);
420
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100421 if (refcount == 0) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700422 // XXX Using the "head" thread isn't strictly correct.
423 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
424 // XXX Possible GILState issues?
425 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700426 Py_EndInterpreter(tstate);
427 PyThreadState_Swap(save_tstate);
428 }
429}
430
Eric Snowbe3b2952019-02-23 11:35:52 -0700431_PyCoreConfig *
432_PyInterpreterState_GetCoreConfig(PyInterpreterState *interp)
433{
434 return &interp->core_config;
435}
436
437_PyMainInterpreterConfig *
438_PyInterpreterState_GetMainConfig(PyInterpreterState *interp)
439{
440 return &interp->config;
441}
Eric Snow4c6955e2018-02-16 18:53:40 -0700442
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000443/* Default implementation for _PyThreadState_GetFrame */
444static struct _frame *
445threadstate_getframe(PyThreadState *self)
446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000448}
449
Victor Stinner45b9be52010-03-03 23:28:07 +0000450static PyThreadState *
451new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000452{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200453 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 if (_PyThreadState_GetFrame == NULL)
456 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 if (tstate != NULL) {
459 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 tstate->frame = NULL;
462 tstate->recursion_depth = 0;
463 tstate->overflowed = 0;
464 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700465 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 tstate->tracing = 0;
467 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 tstate->gilstate_counter = 0;
469 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 tstate->curexc_type = NULL;
475 tstate->curexc_value = NULL;
476 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000477
Mark Shannonae3087c2017-10-22 22:41:51 +0100478 tstate->exc_state.exc_type = NULL;
479 tstate->exc_state.exc_value = NULL;
480 tstate->exc_state.exc_traceback = NULL;
481 tstate->exc_state.previous_item = NULL;
482 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 tstate->c_profilefunc = NULL;
485 tstate->c_tracefunc = NULL;
486 tstate->c_profileobj = NULL;
487 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000488
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200489 tstate->trash_delete_nesting = 0;
490 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200491 tstate->on_delete = NULL;
492 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200493
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800494 tstate->coroutine_origin_tracking_depth = 0;
495
Yury Selivanov75445082015-05-11 22:57:16 -0400496 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400497 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400498
Yury Selivanoveb636452016-09-08 22:01:51 -0700499 tstate->async_gen_firstiter = NULL;
500 tstate->async_gen_finalizer = NULL;
501
Yury Selivanovf23746a2018-01-22 19:11:18 -0500502 tstate->context = NULL;
503 tstate->context_ver = 1;
504
505 tstate->id = ++interp->tstate_next_unique_id;
506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 if (init)
508 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200511 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200513 if (tstate->next)
514 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 interp->tstate_head = tstate;
516 HEAD_UNLOCK();
517 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000520}
521
Victor Stinner45b9be52010-03-03 23:28:07 +0000522PyThreadState *
523PyThreadState_New(PyInterpreterState *interp)
524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000526}
527
528PyThreadState *
529_PyThreadState_Prealloc(PyInterpreterState *interp)
530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000532}
533
534void
535_PyThreadState_Init(PyThreadState *tstate)
536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000538}
539
Martin v. Löwis1a214512008-06-11 05:26:20 +0000540PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200541PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000542{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200543 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100544 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000546 if (module->m_slots) {
547 return NULL;
548 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 if (index == 0)
550 return NULL;
551 if (state->modules_by_index == NULL)
552 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200553 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 return NULL;
555 res = PyList_GET_ITEM(state->modules_by_index, index);
556 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000557}
558
559int
560_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
561{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000562 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300563 if (!def) {
564 assert(PyErr_Occurred());
565 return -1;
566 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000567 if (def->m_slots) {
568 PyErr_SetString(PyExc_SystemError,
569 "PyState_AddModule called on module with slots");
570 return -1;
571 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100572 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 if (!state->modules_by_index) {
574 state->modules_by_index = PyList_New(0);
575 if (!state->modules_by_index)
576 return -1;
577 }
578 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
579 if (PyList_Append(state->modules_by_index, Py_None) < 0)
580 return -1;
581 Py_INCREF(module);
582 return PyList_SetItem(state->modules_by_index,
583 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000584}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000585
Martin v. Löwis7800f752012-06-22 12:20:55 +0200586int
587PyState_AddModule(PyObject* module, struct PyModuleDef* def)
588{
589 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100590 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200591 if (!def) {
592 Py_FatalError("PyState_AddModule: Module Definition is NULL");
593 return -1;
594 }
595 index = def->m_base.m_index;
596 if (state->modules_by_index) {
597 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
598 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
599 Py_FatalError("PyState_AddModule: Module already added!");
600 return -1;
601 }
602 }
603 }
604 return _PyState_AddModule(module, def);
605}
606
607int
608PyState_RemoveModule(struct PyModuleDef* def)
609{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000610 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200611 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000612 if (def->m_slots) {
613 PyErr_SetString(PyExc_SystemError,
614 "PyState_RemoveModule called on module with slots");
615 return -1;
616 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100617 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200618 if (index == 0) {
619 Py_FatalError("PyState_RemoveModule: Module index invalid.");
620 return -1;
621 }
622 if (state->modules_by_index == NULL) {
623 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
624 return -1;
625 }
626 if (index > PyList_GET_SIZE(state->modules_by_index)) {
627 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
628 return -1;
629 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700630 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200631 return PyList_SetItem(state->modules_by_index, index, Py_None);
632}
633
Antoine Pitrou40322e62013-08-11 00:30:09 +0200634/* used by import.c:PyImport_Cleanup */
635void
636_PyState_ClearModules(void)
637{
Victor Stinner9204fb82018-10-30 15:13:17 +0100638 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200639 if (state->modules_by_index) {
640 Py_ssize_t i;
641 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
642 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
643 if (PyModule_Check(m)) {
644 /* cleanup the saved copy of module dicts */
645 PyModuleDef *md = PyModule_GetDef(m);
646 if (md)
647 Py_CLEAR(md->m_base.m_copy);
648 }
649 }
650 /* Setting modules_by_index to NULL could be dangerous, so we
651 clear the list instead. */
652 if (PyList_SetSlice(state->modules_by_index,
653 0, PyList_GET_SIZE(state->modules_by_index),
654 NULL))
655 PyErr_WriteUnraisable(state->modules_by_index);
656 }
657}
658
Guido van Rossuma027efa1997-05-05 20:56:21 +0000659void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000660PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000661{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200662 int verbose = tstate->interp->core_config.verbose;
663
664 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 fprintf(stderr,
666 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 Py_CLEAR(tstate->dict);
671 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 Py_CLEAR(tstate->curexc_type);
674 Py_CLEAR(tstate->curexc_value);
675 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000676
Mark Shannonae3087c2017-10-22 22:41:51 +0100677 Py_CLEAR(tstate->exc_state.exc_type);
678 Py_CLEAR(tstate->exc_state.exc_value);
679 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300680
Mark Shannonae3087c2017-10-22 22:41:51 +0100681 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200682 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100683 fprintf(stderr,
684 "PyThreadState_Clear: warning: thread still has a generator\n");
685 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 tstate->c_profilefunc = NULL;
688 tstate->c_tracefunc = NULL;
689 Py_CLEAR(tstate->c_profileobj);
690 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400691
692 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700693 Py_CLEAR(tstate->async_gen_firstiter);
694 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500695
696 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000697}
698
699
Guido van Rossum29757862001-01-23 01:46:06 +0000700/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
701static void
702tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 if (tstate == NULL)
706 Py_FatalError("PyThreadState_Delete: NULL tstate");
707 interp = tstate->interp;
708 if (interp == NULL)
709 Py_FatalError("PyThreadState_Delete: NULL interp");
710 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200711 if (tstate->prev)
712 tstate->prev->next = tstate->next;
713 else
714 interp->tstate_head = tstate->next;
715 if (tstate->next)
716 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200718 if (tstate->on_delete != NULL) {
719 tstate->on_delete(tstate->on_delete_data);
720 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200721 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000722}
723
724
Guido van Rossum29757862001-01-23 01:46:06 +0000725void
726PyThreadState_Delete(PyThreadState *tstate)
727{
Victor Stinner50b48572018-11-01 01:51:40 +0100728 if (tstate == _PyThreadState_GET())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600730 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900731 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600732 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900733 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600734 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200735 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000736}
737
738
Guido van Rossum29757862001-01-23 01:46:06 +0000739void
740PyThreadState_DeleteCurrent()
741{
Victor Stinner50b48572018-11-01 01:51:40 +0100742 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 if (tstate == NULL)
744 Py_FatalError(
745 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100746 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600747 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900748 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600749 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900750 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600751 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100752 _PyThreadState_SET(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000754}
Guido van Rossum29757862001-01-23 01:46:06 +0000755
756
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200757/*
758 * Delete all thread states except the one passed as argument.
759 * Note that, if there is a current thread state, it *must* be the one
760 * passed as argument. Also, this won't touch any other interpreters
761 * than the current one, since we don't know which thread state should
762 * be kept in those other interpreteres.
763 */
764void
765_PyThreadState_DeleteExcept(PyThreadState *tstate)
766{
767 PyInterpreterState *interp = tstate->interp;
768 PyThreadState *p, *next, *garbage;
769 HEAD_LOCK();
770 /* Remove all thread states, except tstate, from the linked list of
771 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200772 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200773 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200774 if (garbage == tstate)
775 garbage = tstate->next;
776 if (tstate->prev)
777 tstate->prev->next = tstate->next;
778 if (tstate->next)
779 tstate->next->prev = tstate->prev;
780 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200781 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200782 HEAD_UNLOCK();
783 /* Clear and deallocate all stale thread states. Even if this
784 executes Python code, we should be safe since it executes
785 in the current thread, not one of the stale threads. */
786 for (p = garbage; p; p = next) {
787 next = p->next;
788 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200789 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200790 }
791}
792
793
Guido van Rossuma027efa1997-05-05 20:56:21 +0000794PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100795_PyThreadState_UncheckedGet(void)
796{
Victor Stinner50b48572018-11-01 01:51:40 +0100797 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100798}
799
800
801PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000802PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000803{
Victor Stinner50b48572018-11-01 01:51:40 +0100804 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 if (tstate == NULL)
806 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000809}
810
811
812PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000813PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000814{
Victor Stinner50b48572018-11-01 01:51:40 +0100815 PyThreadState *oldts = _PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000816
Victor Stinner9204fb82018-10-30 15:13:17 +0100817 _PyThreadState_SET(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 /* It should not be possible for more than one thread state
819 to be used for a thread. Check this the best we can in debug
820 builds.
821 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200822#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 if (newts) {
824 /* This can be called from PyEval_RestoreThread(). Similar
825 to it, we need to ensure errno doesn't change.
826 */
827 int err = errno;
828 PyThreadState *check = PyGILState_GetThisThreadState();
829 if (check && check->interp == newts->interp && check != newts)
830 Py_FatalError("Invalid thread state for this thread");
831 errno = err;
832 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000833#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000835}
Guido van Rossumede04391998-04-10 20:18:25 +0000836
837/* An extension mechanism to store arbitrary additional per-thread state.
838 PyThreadState_GetDict() returns a dictionary that can be used to hold such
839 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000840 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
841 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000842
843PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000844PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000845{
Victor Stinner50b48572018-11-01 01:51:40 +0100846 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 if (tstate == NULL)
848 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 if (tstate->dict == NULL) {
851 PyObject *d;
852 tstate->dict = d = PyDict_New();
853 if (d == NULL)
854 PyErr_Clear();
855 }
856 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000857}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000858
859
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000860/* Asynchronously raise an exception in a thread.
861 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000862 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000863 to call this, or use ctypes. Must be called with the GIL held.
864 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
865 match any known thread id). Can be called with exc=NULL to clear an
866 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000867
868int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200869PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
870{
Victor Stinner9204fb82018-10-30 15:13:17 +0100871 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000873
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 /* Although the GIL is held, a few C API functions can be called
875 * without the GIL held, and in particular some that create and
876 * destroy thread and interpreter states. Those can mutate the
877 * list of thread states we're traversing, so to prevent that we lock
878 * head_mutex for the duration.
879 */
880 HEAD_LOCK();
881 for (p = interp->tstate_head; p != NULL; p = p->next) {
882 if (p->thread_id == id) {
883 /* Tricky: we need to decref the current value
884 * (if any) in p->async_exc, but that can in turn
885 * allow arbitrary Python code to run, including
886 * perhaps calls to this function. To prevent
887 * deadlock, we need to release head_mutex before
888 * the decref.
889 */
890 PyObject *old_exc = p->async_exc;
891 Py_XINCREF(exc);
892 p->async_exc = exc;
893 HEAD_UNLOCK();
894 Py_XDECREF(old_exc);
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100895 _PyEval_SignalAsyncExc();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 return 1;
897 }
898 }
899 HEAD_UNLOCK();
900 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000901}
902
903
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000904/* Routines for advanced debuggers, requested by David Beazley.
905 Don't use unless you know what you are doing! */
906
907PyInterpreterState *
908PyInterpreterState_Head(void)
909{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600910 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000911}
912
913PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700914PyInterpreterState_Main(void)
915{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600916 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700917}
918
919PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000920PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000922}
923
924PyThreadState *
925PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000927}
928
929PyThreadState *
930PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000932}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000933
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000934/* The implementation of sys._current_frames(). This is intended to be
935 called with the GIL held, as it will be when called via
936 sys._current_frames(). It's possible it would work fine even without
937 the GIL held, but haven't thought enough about that.
938*/
939PyObject *
940_PyThread_CurrentFrames(void)
941{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 PyObject *result;
943 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 result = PyDict_New();
946 if (result == NULL)
947 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 /* for i in all interpreters:
950 * for t in all of i's thread states:
951 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200952 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 * need to grab head_mutex for the duration.
954 */
955 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600956 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 PyThreadState *t;
958 for (t = i->tstate_head; t != NULL; t = t->next) {
959 PyObject *id;
960 int stat;
961 struct _frame *frame = t->frame;
962 if (frame == NULL)
963 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200964 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 if (id == NULL)
966 goto Fail;
967 stat = PyDict_SetItem(result, id, (PyObject *)frame);
968 Py_DECREF(id);
969 if (stat < 0)
970 goto Fail;
971 }
972 }
973 HEAD_UNLOCK();
974 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000975
976 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 HEAD_UNLOCK();
978 Py_DECREF(result);
979 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000980}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000981
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000982/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000983
984/* Keep this as a static, as it is not reliable! It can only
985 ever be compared to the state for the *current* thread.
986 * If not equal, then it doesn't matter that the actual
987 value may change immediately after comparison, as it can't
988 possibly change to the current thread's state.
989 * If equal, then the current thread holds the lock, so the value can't
990 change until we yield the lock.
991*/
992static int
993PyThreadState_IsCurrent(PyThreadState *tstate)
994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 /* Must be the tstate for this thread */
996 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinner50b48572018-11-01 01:51:40 +0100997 return tstate == _PyThreadState_GET();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000998}
999
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001000/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001001 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001002*/
Tim Peters19717fa2004-10-09 17:38:29 +00001003void
1004_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001007 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1008 Py_FatalError("Could not allocate TSS entry");
1009 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001010 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001011 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001015}
1016
Victor Stinner861d9ab2016-03-16 22:45:24 +01001017PyInterpreterState *
1018_PyGILState_GetInterpreterStateUnsafe(void)
1019{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001020 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001021}
1022
Tim Peters19717fa2004-10-09 17:38:29 +00001023void
1024_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001025{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001026 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001027 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001028}
1029
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001030/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001031 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001032 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001033 */
1034void
1035_PyGILState_Reinit(void)
1036{
Victor Stinner5d926472018-03-06 14:31:37 +01001037 /* Force default allocator, since _PyRuntimeState_Fini() must
1038 use the same allocator than this function. */
1039 PyMemAllocatorEx old_alloc;
1040 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1041
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001042 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +01001043
1044 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1045
1046 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001047 Py_FatalError("Can't initialize threads for interpreter");
Victor Stinner5d926472018-03-06 14:31:37 +01001048 }
1049
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001050 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001051 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
1052 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1053 Py_FatalError("Could not allocate TSS entry");
1054 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001055
Charles-François Natalia233df82011-11-22 19:49:51 +01001056 /* If the thread had an associated auto thread state, reassociate it with
1057 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001058 if (tstate &&
1059 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
1060 {
1061 Py_FatalError("Couldn't create autoTSSkey mapping");
1062 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001063}
1064
Michael W. Hudson188d4362005-06-20 16:52:57 +00001065/* When a thread state is created for a thread by some mechanism other than
1066 PyGILState_Ensure, it's important that the GILState machinery knows about
1067 it so it doesn't try to create another thread state for the thread (this is
1068 a better fix for SF bug #1010677 than the first one attempted).
1069*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001070static void
Michael W. Hudson188d4362005-06-20 16:52:57 +00001071_PyGILState_NoteThreadState(PyThreadState* tstate)
1072{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001073 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001074 threadstate created in Py_Initialize(). Don't do anything for now
1075 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001076 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001078
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001079 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 The only situation where you can legitimately have more than one
1082 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001083 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001084
Victor Stinner590cebe2013-12-13 11:08:56 +01001085 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1086 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001087
Victor Stinner590cebe2013-12-13 11:08:56 +01001088 The first thread state created for that given OS level thread will
1089 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001091 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
1092 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1093 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001094 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001095 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001096 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001097 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 /* PyGILState_Release must not try to delete this thread state. */
1100 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001101}
1102
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001103/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001104PyThreadState *
1105PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001106{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001107 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001109 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001110}
1111
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001112int
1113PyGILState_Check(void)
1114{
Victor Stinner8a1be612016-03-14 22:07:55 +01001115 PyThreadState *tstate;
1116
1117 if (!_PyGILState_check_enabled)
1118 return 1;
1119
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001120 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001121 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001122 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001123
Victor Stinner50b48572018-11-01 01:51:40 +01001124 tstate = _PyThreadState_GET();
Victor Stinner8a1be612016-03-14 22:07:55 +01001125 if (tstate == NULL)
1126 return 0;
1127
1128 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001129}
1130
Tim Peters19717fa2004-10-09 17:38:29 +00001131PyGILState_STATE
1132PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 int current;
1135 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001136 int need_init_threads = 0;
1137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 /* Note that we do not auto-init Python here - apart from
1139 potential races with 2 threads auto-initializing, pep-311
1140 spells out other issues. Embedders are expected to have
1141 called Py_Initialize() and usually PyEval_InitThreads().
1142 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001143 /* Py_Initialize() hasn't been called! */
1144 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001145
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001146 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001148 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001151 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 if (tcur == NULL)
1153 Py_FatalError("Couldn't create thread-state for new thread");
1154 /* This is our thread state! We'll need to delete it in the
1155 matching call to PyGILState_Release(). */
1156 tcur->gilstate_counter = 0;
1157 current = 0; /* new thread state is never current */
1158 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001159 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001160 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001161 }
1162
1163 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001165 }
1166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 /* Update our counter in the thread-state - no need for locks:
1168 - tcur will remain valid as we hold the GIL.
1169 - the counter is safe as we are the only thread "allowed"
1170 to modify this value
1171 */
1172 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001173
1174 if (need_init_threads) {
1175 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1176 called from a new thread for the first time, we need the create the
1177 GIL. */
1178 PyEval_InitThreads();
1179 }
1180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001182}
1183
Tim Peters19717fa2004-10-09 17:38:29 +00001184void
1185PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001186{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001187 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1188 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 if (tcur == NULL)
1190 Py_FatalError("auto-releasing thread-state, "
1191 "but no thread-state for this thread");
1192 /* We must hold the GIL and have our thread state current */
1193 /* XXX - remove the check - the assert should be fine,
1194 but while this is very new (April 2003), the extra check
1195 by release-only users can't hurt.
1196 */
1197 if (! PyThreadState_IsCurrent(tcur))
1198 Py_FatalError("This thread state must be current when releasing");
1199 assert(PyThreadState_IsCurrent(tcur));
1200 --tcur->gilstate_counter;
1201 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 /* If we're going to destroy this thread-state, we must
1204 * clear it while the GIL is held, as destructors may run.
1205 */
1206 if (tcur->gilstate_counter == 0) {
1207 /* can't have been locked when we created it */
1208 assert(oldstate == PyGILState_UNLOCKED);
1209 PyThreadState_Clear(tcur);
1210 /* Delete the thread-state. Note this releases the GIL too!
1211 * It's vital that the GIL be held here, to avoid shutdown
1212 * races; see bugs 225673 and 1061968 (that nasty bug has a
1213 * habit of coming back).
1214 */
1215 PyThreadState_DeleteCurrent();
1216 }
1217 /* Release the lock if necessary */
1218 else if (oldstate == PyGILState_UNLOCKED)
1219 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001220}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001221
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001222
Eric Snow7f8bfc92018-01-29 18:23:44 -07001223/**************************/
1224/* cross-interpreter data */
1225/**************************/
1226
1227/* cross-interpreter data */
1228
1229crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1230
1231/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1232 to keep the registry code separate. */
1233static crossinterpdatafunc
1234_lookup_getdata(PyObject *obj)
1235{
1236 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1237 if (getdata == NULL && PyErr_Occurred() == 0)
1238 PyErr_Format(PyExc_ValueError,
1239 "%S does not support cross-interpreter data", obj);
1240 return getdata;
1241}
1242
1243int
1244_PyObject_CheckCrossInterpreterData(PyObject *obj)
1245{
1246 crossinterpdatafunc getdata = _lookup_getdata(obj);
1247 if (getdata == NULL) {
1248 return -1;
1249 }
1250 return 0;
1251}
1252
1253static int
1254_check_xidata(_PyCrossInterpreterData *data)
1255{
1256 // data->data can be anything, including NULL, so we don't check it.
1257
1258 // data->obj may be NULL, so we don't check it.
1259
1260 if (data->interp < 0) {
1261 PyErr_SetString(PyExc_SystemError, "missing interp");
1262 return -1;
1263 }
1264
1265 if (data->new_object == NULL) {
1266 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1267 return -1;
1268 }
1269
1270 // data->free may be NULL, so we don't check it.
1271
1272 return 0;
1273}
1274
1275int
1276_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1277{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001278 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001279 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001280 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001281
1282 // Reset data before re-populating.
1283 *data = (_PyCrossInterpreterData){0};
1284 data->free = PyMem_RawFree; // Set a default that may be overridden.
1285
1286 // Call the "getdata" func for the object.
1287 Py_INCREF(obj);
1288 crossinterpdatafunc getdata = _lookup_getdata(obj);
1289 if (getdata == NULL) {
1290 Py_DECREF(obj);
1291 return -1;
1292 }
1293 int res = getdata(obj, data);
1294 Py_DECREF(obj);
1295 if (res != 0) {
1296 return -1;
1297 }
1298
1299 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001300 data->interp = interp->id;
1301 if (_check_xidata(data) != 0) {
1302 _PyCrossInterpreterData_Release(data);
1303 return -1;
1304 }
1305
1306 return 0;
1307}
1308
Victor Stinner4d61e6e2019-03-04 14:21:28 +01001309static void
Eric Snow63799132018-06-01 18:45:20 -06001310_release_xidata(void *arg)
1311{
1312 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1313 if (data->free != NULL) {
1314 data->free(data->data);
1315 }
1316 Py_XDECREF(data->obj);
Victor Stinner4d61e6e2019-03-04 14:21:28 +01001317}
1318
1319static void
1320_call_in_interpreter(PyInterpreterState *interp,
1321 void (*func)(void *), void *arg)
1322{
1323 /* We would use Py_AddPendingCall() if it weren't specific to the
1324 * main interpreter (see bpo-33608). In the meantime we take a
1325 * naive approach.
1326 */
1327 PyThreadState *save_tstate = NULL;
1328 if (interp != _PyInterpreterState_Get()) {
1329 // XXX Using the "head" thread isn't strictly correct.
1330 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1331 // XXX Possible GILState issues?
1332 save_tstate = PyThreadState_Swap(tstate);
1333 }
1334
1335 func(arg);
1336
1337 // Switch back.
1338 if (save_tstate != NULL) {
1339 PyThreadState_Swap(save_tstate);
1340 }
Eric Snow63799132018-06-01 18:45:20 -06001341}
1342
Eric Snow7f8bfc92018-01-29 18:23:44 -07001343void
1344_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1345{
1346 if (data->data == NULL && data->obj == NULL) {
1347 // Nothing to release!
1348 return;
1349 }
1350
Victor Stinner4d61e6e2019-03-04 14:21:28 +01001351 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001352 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1353 if (interp == NULL) {
1354 // The intepreter was already destroyed.
1355 if (data->free != NULL) {
1356 // XXX Someone leaked some memory...
1357 }
1358 return;
1359 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001360
Eric Snow7f8bfc92018-01-29 18:23:44 -07001361 // "Release" the data and/or the object.
Victor Stinner4d61e6e2019-03-04 14:21:28 +01001362 _call_in_interpreter(interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001363}
1364
1365PyObject *
1366_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1367{
1368 return data->new_object(data);
1369}
1370
1371/* registry of {type -> crossinterpdatafunc} */
1372
1373/* For now we use a global registry of shareable classes. An
1374 alternative would be to add a tp_* slot for a class's
1375 crossinterpdatafunc. It would be simpler and more efficient. */
1376
1377static int
1378_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1379{
1380 // Note that we effectively replace already registered classes
1381 // rather than failing.
1382 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1383 if (newhead == NULL)
1384 return -1;
1385 newhead->cls = cls;
1386 newhead->getdata = getdata;
1387 newhead->next = _PyRuntime.xidregistry.head;
1388 _PyRuntime.xidregistry.head = newhead;
1389 return 0;
1390}
1391
1392static void _register_builtins_for_crossinterpreter_data(void);
1393
1394int
Victor Stinner4d61e6e2019-03-04 14:21:28 +01001395_PyCrossInterpreterData_Register_Class(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001396 crossinterpdatafunc getdata)
1397{
1398 if (!PyType_Check(cls)) {
1399 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1400 return -1;
1401 }
1402 if (getdata == NULL) {
1403 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1404 return -1;
1405 }
1406
1407 // Make sure the class isn't ever deallocated.
1408 Py_INCREF((PyObject *)cls);
1409
1410 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1411 if (_PyRuntime.xidregistry.head == NULL) {
1412 _register_builtins_for_crossinterpreter_data();
1413 }
1414 int res = _register_xidata(cls, getdata);
1415 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1416 return res;
1417}
1418
Eric Snow6d2cd902018-05-16 15:04:57 -04001419/* Cross-interpreter objects are looked up by exact match on the class.
1420 We can reassess this policy when we move from a global registry to a
1421 tp_* slot. */
1422
Eric Snow7f8bfc92018-01-29 18:23:44 -07001423crossinterpdatafunc
1424_PyCrossInterpreterData_Lookup(PyObject *obj)
1425{
1426 PyObject *cls = PyObject_Type(obj);
1427 crossinterpdatafunc getdata = NULL;
1428 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1429 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1430 if (cur == NULL) {
1431 _register_builtins_for_crossinterpreter_data();
1432 cur = _PyRuntime.xidregistry.head;
1433 }
1434 for(; cur != NULL; cur = cur->next) {
1435 if (cur->cls == (PyTypeObject *)cls) {
1436 getdata = cur->getdata;
1437 break;
1438 }
1439 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001440 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001441 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1442 return getdata;
1443}
1444
1445/* cross-interpreter data for builtin types */
1446
Eric Snow6d2cd902018-05-16 15:04:57 -04001447struct _shared_bytes_data {
1448 char *bytes;
1449 Py_ssize_t len;
1450};
1451
Eric Snow7f8bfc92018-01-29 18:23:44 -07001452static PyObject *
1453_new_bytes_object(_PyCrossInterpreterData *data)
1454{
Eric Snow6d2cd902018-05-16 15:04:57 -04001455 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1456 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001457}
1458
1459static int
1460_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1461{
Eric Snow6d2cd902018-05-16 15:04:57 -04001462 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1463 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1464 return -1;
1465 }
1466 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001467 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001468 data->obj = obj; // Will be "released" (decref'ed) when data released.
1469 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001470 data->free = PyMem_Free;
1471 return 0;
1472}
1473
1474struct _shared_str_data {
1475 int kind;
1476 const void *buffer;
1477 Py_ssize_t len;
1478};
1479
1480static PyObject *
1481_new_str_object(_PyCrossInterpreterData *data)
1482{
1483 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1484 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1485}
1486
1487static int
1488_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1489{
1490 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1491 shared->kind = PyUnicode_KIND(obj);
1492 shared->buffer = PyUnicode_DATA(obj);
1493 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1494 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001495 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001496 data->obj = obj; // Will be "released" (decref'ed) when data released.
1497 data->new_object = _new_str_object;
1498 data->free = PyMem_Free;
1499 return 0;
1500}
1501
1502static PyObject *
1503_new_long_object(_PyCrossInterpreterData *data)
1504{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001505 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001506}
1507
1508static int
1509_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1510{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001511 /* Note that this means the size of shareable ints is bounded by
1512 * sys.maxsize. Hence on 32-bit architectures that is half the
1513 * size of maximum shareable ints on 64-bit.
1514 */
1515 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001516 if (value == -1 && PyErr_Occurred()) {
1517 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1518 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1519 }
1520 return -1;
1521 }
1522 data->data = (void *)value;
1523 data->obj = NULL;
1524 data->new_object = _new_long_object;
1525 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001526 return 0;
1527}
1528
1529static PyObject *
1530_new_none_object(_PyCrossInterpreterData *data)
1531{
1532 // XXX Singleton refcounts are problematic across interpreters...
1533 Py_INCREF(Py_None);
1534 return Py_None;
1535}
1536
1537static int
1538_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1539{
1540 data->data = NULL;
1541 // data->obj remains NULL
1542 data->new_object = _new_none_object;
1543 data->free = NULL; // There is nothing to free.
1544 return 0;
1545}
1546
1547static void
1548_register_builtins_for_crossinterpreter_data(void)
1549{
1550 // None
1551 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1552 Py_FatalError("could not register None for cross-interpreter sharing");
1553 }
1554
Eric Snow6d2cd902018-05-16 15:04:57 -04001555 // int
1556 if (_register_xidata(&PyLong_Type, _long_shared) != 0) {
1557 Py_FatalError("could not register int for cross-interpreter sharing");
1558 }
1559
Eric Snow7f8bfc92018-01-29 18:23:44 -07001560 // bytes
1561 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1562 Py_FatalError("could not register bytes for cross-interpreter sharing");
1563 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001564
1565 // str
1566 if (_register_xidata(&PyUnicode_Type, _str_shared) != 0) {
1567 Py_FatalError("could not register str for cross-interpreter sharing");
1568 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001569}
1570
1571
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001572#ifdef __cplusplus
1573}
1574#endif