blob: a2464b6cf5518f317bee22a8a5be3bc52fd23301 [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);
Victor Stinner6d5ee972019-03-23 12:05:43 +010044 runtime->preconfig = _PyPreConfig_INIT;
Michael W. Hudson188d4362005-06-20 16:52:57 +000045
Eric Snow2ebc5ce2017-09-07 23:51:28 -060046 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080047
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090048 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
49 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080050 Py_tss_t initial = Py_tss_NEEDS_INIT;
51 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000052
Eric Snow2ebc5ce2017-09-07 23:51:28 -060053 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080054 if (runtime->interpreters.mutex == NULL) {
55 return _Py_INIT_ERR("Can't initialize threads for interpreter");
56 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060057 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070058
59 runtime->xidregistry.mutex = PyThread_allocate_lock();
60 if (runtime->xidregistry.mutex == NULL) {
61 return _Py_INIT_ERR("Can't initialize threads for cross-interpreter data registry");
62 }
63
Eric Snow8479a342019-03-08 23:44:33 -070064 // Set it to the ID of the main thread of the main interpreter.
65 runtime->main_thread = PyThread_get_thread_ident();
Eric Snow5be45a62019-03-08 22:47:07 -070066
Victor Stinnerf7e5b562017-11-15 15:48:08 -080067 return _Py_INIT_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060068}
Eric Snow05351c12017-09-05 21:43:08 -070069
Victor Stinner5d39e042017-11-29 17:20:38 +010070_PyInitError
71_PyRuntimeState_Init(_PyRuntimeState *runtime)
72{
73 /* Force default allocator, since _PyRuntimeState_Fini() must
74 use the same allocator than this function. */
75 PyMemAllocatorEx old_alloc;
76 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
77
78 _PyInitError err = _PyRuntimeState_Init_impl(runtime);
79
80 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
81 return err;
82}
83
Eric Snow2ebc5ce2017-09-07 23:51:28 -060084void
85_PyRuntimeState_Fini(_PyRuntimeState *runtime)
86{
Victor Stinner5d39e042017-11-29 17:20:38 +010087 /* Force the allocator used by _PyRuntimeState_Init(). */
88 PyMemAllocatorEx old_alloc;
89 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -080090
Eric Snow2ebc5ce2017-09-07 23:51:28 -060091 if (runtime->interpreters.mutex != NULL) {
92 PyThread_free_lock(runtime->interpreters.mutex);
93 runtime->interpreters.mutex = NULL;
94 }
Victor Stinnerccb04422017-11-16 03:20:31 -080095
Stéphane Wirtel943395f2019-03-19 11:51:32 +010096 if (runtime->xidregistry.mutex != NULL) {
97 PyThread_free_lock(runtime->xidregistry.mutex);
98 runtime->xidregistry.mutex = NULL;
99 }
100
Victor Stinner6d5ee972019-03-23 12:05:43 +0100101 _PyPreConfig_Clear(&runtime->preconfig);
102
Victor Stinnerccb04422017-11-16 03:20:31 -0800103 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600104}
105
Eric Snow8479a342019-03-08 23:44:33 -0700106/* This function is called from PyOS_AfterFork_Child to ensure that
107 * newly created child processes do not share locks with the parent.
108 */
109
110void
111_PyRuntimeState_ReInitThreads(void)
112{
113 // This was initially set in _PyRuntimeState_Init().
114 _PyRuntime.main_thread = PyThread_get_thread_ident();
115
116 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
117 if (_PyRuntime.interpreters.mutex == NULL) {
118 Py_FatalError("Can't initialize lock for runtime interpreters");
119 }
120
121 _PyRuntime.interpreters.main->id_mutex = PyThread_allocate_lock();
122 if (_PyRuntime.interpreters.main->id_mutex == NULL) {
123 Py_FatalError("Can't initialize ID lock for main interpreter");
124 }
125
126 _PyRuntime.xidregistry.mutex = PyThread_allocate_lock();
127 if (_PyRuntime.xidregistry.mutex == NULL) {
128 Py_FatalError("Can't initialize lock for cross-interpreter data registry");
129 }
130}
131
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600132#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
133 WAIT_LOCK)
134#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -0700135
Michael W. Hudson188d4362005-06-20 16:52:57 +0000136static void _PyGILState_NoteThreadState(PyThreadState* tstate);
137
Victor Stinnera7368ac2017-11-15 18:11:45 -0800138_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600139_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700140{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600141 runtime->interpreters.next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100142
143 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
144 Create a new mutex if needed. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600145 if (runtime->interpreters.mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100146 /* Force default allocator, since _PyRuntimeState_Fini() must
147 use the same allocator than this function. */
148 PyMemAllocatorEx old_alloc;
149 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
150
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600151 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100152
153 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
154
Victor Stinnera7368ac2017-11-15 18:11:45 -0800155 if (runtime->interpreters.mutex == NULL) {
156 return _Py_INIT_ERR("Can't initialize threads for interpreter");
157 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600158 }
Victor Stinner5d926472018-03-06 14:31:37 +0100159
Victor Stinnera7368ac2017-11-15 18:11:45 -0800160 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700161}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000162
163PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000164PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000166 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200167 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000168
Victor Stinnerd4341102017-11-23 00:12:09 +0100169 if (interp == NULL) {
170 return NULL;
171 }
172
Eric Snow5be45a62019-03-08 22:47:07 -0700173 memset(interp, 0, sizeof(*interp));
Eric Snow4c6955e2018-02-16 18:53:40 -0700174 interp->id_refcount = -1;
Victor Stinnerd4341102017-11-23 00:12:09 +0100175 interp->check_interval = 100;
Victor Stinnerd4341102017-11-23 00:12:09 +0100176 interp->core_config = _PyCoreConfig_INIT;
Victor Stinnerd4341102017-11-23 00:12:09 +0100177 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000178#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300179#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100180 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000181#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100182 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000183#endif
184#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000185
Victor Stinnerd4341102017-11-23 00:12:09 +0100186 HEAD_LOCK();
Victor Stinnerd4341102017-11-23 00:12:09 +0100187 if (_PyRuntime.interpreters.next_id < 0) {
188 /* overflow or Py_Initialize() not called! */
189 PyErr_SetString(PyExc_RuntimeError,
190 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100191 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100192 interp = NULL;
193 } else {
194 interp->id = _PyRuntime.interpreters.next_id;
195 _PyRuntime.interpreters.next_id += 1;
Pablo Galindo95d630e2018-08-31 22:49:29 +0100196 interp->next = _PyRuntime.interpreters.head;
197 if (_PyRuntime.interpreters.main == NULL) {
198 _PyRuntime.interpreters.main = interp;
199 }
200 _PyRuntime.interpreters.head = interp;
Victor Stinnerd4341102017-11-23 00:12:09 +0100201 }
202 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000203
Pablo Galindo95d630e2018-08-31 22:49:29 +0100204 if (interp == NULL) {
205 return NULL;
206 }
207
Yury Selivanovf23746a2018-01-22 19:11:18 -0500208 interp->tstate_next_unique_id = 0;
209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000211}
212
213
214void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000215PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 PyThreadState *p;
218 HEAD_LOCK();
219 for (p = interp->tstate_head; p != NULL; p = p->next)
220 PyThreadState_Clear(p);
221 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100222 _PyCoreConfig_Clear(&interp->core_config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 Py_CLEAR(interp->codec_search_path);
224 Py_CLEAR(interp->codec_search_cache);
225 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700226 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000228 Py_CLEAR(interp->sysdict);
229 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200230 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400231 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300232 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600233 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200234#ifdef HAVE_FORK
235 Py_CLEAR(interp->before_forkers);
236 Py_CLEAR(interp->after_forkers_parent);
237 Py_CLEAR(interp->after_forkers_child);
238#endif
Eric Snow5be45a62019-03-08 22:47:07 -0700239 // XXX Once we have one allocator per interpreter (i.e.
240 // per-interpreter GC) we must ensure that all of the interpreter's
241 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000242}
243
244
245static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000246zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 PyThreadState *p;
249 /* No need to lock the mutex here because this should only happen
250 when the threads are all really dead (XXX famous last words). */
251 while ((p = interp->tstate_head) != NULL) {
252 PyThreadState_Delete(p);
253 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000254}
255
256
257void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000258PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 PyInterpreterState **p;
261 zapthreads(interp);
262 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600263 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 if (*p == NULL)
265 Py_FatalError(
266 "PyInterpreterState_Delete: invalid interp");
267 if (*p == interp)
268 break;
269 }
270 if (interp->tstate_head != NULL)
271 Py_FatalError("PyInterpreterState_Delete: remaining threads");
272 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600273 if (_PyRuntime.interpreters.main == interp) {
274 _PyRuntime.interpreters.main = NULL;
275 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700276 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
277 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 HEAD_UNLOCK();
Eric Snow4c6955e2018-02-16 18:53:40 -0700279 if (interp->id_mutex != NULL) {
280 PyThread_free_lock(interp->id_mutex);
281 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200282 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000283}
284
285
Eric Snow59032962018-09-14 14:17:20 -0700286/*
287 * Delete all interpreter states except the main interpreter. If there
288 * is a current interpreter state, it *must* be the main interpreter.
289 */
290void
291_PyInterpreterState_DeleteExceptMain()
292{
293 PyThreadState *tstate = PyThreadState_Swap(NULL);
294 if (tstate != NULL && tstate->interp != _PyRuntime.interpreters.main) {
295 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
296 }
297
298 HEAD_LOCK();
299 PyInterpreterState *interp = _PyRuntime.interpreters.head;
300 _PyRuntime.interpreters.head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100301 while (interp != NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700302 if (interp == _PyRuntime.interpreters.main) {
303 _PyRuntime.interpreters.main->next = NULL;
304 _PyRuntime.interpreters.head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100305 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700306 continue;
307 }
308
309 PyInterpreterState_Clear(interp); // XXX must activate?
310 zapthreads(interp);
311 if (interp->id_mutex != NULL) {
312 PyThread_free_lock(interp->id_mutex);
313 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100314 PyInterpreterState *prev_interp = interp;
315 interp = interp->next;
316 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700317 }
318 HEAD_UNLOCK();
319
320 if (_PyRuntime.interpreters.head == NULL) {
321 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
322 }
323 PyThreadState_Swap(tstate);
324}
325
326
Victor Stinnercaba55b2018-08-03 15:33:52 +0200327PyInterpreterState *
328_PyInterpreterState_Get(void)
329{
Victor Stinner50b48572018-11-01 01:51:40 +0100330 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200331 if (tstate == NULL) {
332 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
333 }
334 PyInterpreterState *interp = tstate->interp;
335 if (interp == NULL) {
336 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
337 }
338 return interp;
339}
340
341
Eric Snowe3774162017-05-22 19:46:40 -0700342int64_t
343PyInterpreterState_GetID(PyInterpreterState *interp)
344{
345 if (interp == NULL) {
346 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
347 return -1;
348 }
349 return interp->id;
350}
351
352
Eric Snow5be45a62019-03-08 22:47:07 -0700353static PyInterpreterState *
354interp_look_up_id(PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700355{
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100356 PyInterpreterState *interp = PyInterpreterState_Head();
357 while (interp != NULL) {
358 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700359 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100360 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700361 }
362 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100363 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700364 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100365 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700366 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100367 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700368}
369
Eric Snow5be45a62019-03-08 22:47:07 -0700370PyInterpreterState *
371_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
372{
373 PyInterpreterState *interp = NULL;
374 if (requested_id >= 0) {
375 HEAD_LOCK();
376 interp = interp_look_up_id(requested_id);
377 HEAD_UNLOCK();
378 }
379 if (interp == NULL && !PyErr_Occurred()) {
380 PyErr_Format(PyExc_RuntimeError,
381 "unrecognized interpreter ID %lld", requested_id);
382 }
383 return interp;
384}
385
Eric Snow4c6955e2018-02-16 18:53:40 -0700386
387int
388_PyInterpreterState_IDInitref(PyInterpreterState *interp)
389{
390 if (interp->id_mutex != NULL) {
391 return 0;
392 }
393 interp->id_mutex = PyThread_allocate_lock();
394 if (interp->id_mutex == NULL) {
395 PyErr_SetString(PyExc_RuntimeError,
396 "failed to create init interpreter ID mutex");
397 return -1;
398 }
399 interp->id_refcount = 0;
400 return 0;
401}
402
403
404void
405_PyInterpreterState_IDIncref(PyInterpreterState *interp)
406{
407 if (interp->id_mutex == NULL) {
408 return;
409 }
410 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
411 interp->id_refcount += 1;
412 PyThread_release_lock(interp->id_mutex);
413}
414
415
416void
417_PyInterpreterState_IDDecref(PyInterpreterState *interp)
418{
419 if (interp->id_mutex == NULL) {
420 return;
421 }
422 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
423 assert(interp->id_refcount != 0);
424 interp->id_refcount -= 1;
425 int64_t refcount = interp->id_refcount;
426 PyThread_release_lock(interp->id_mutex);
427
Eric Snowc11183c2019-03-15 16:35:46 -0600428 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700429 // XXX Using the "head" thread isn't strictly correct.
430 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
431 // XXX Possible GILState issues?
432 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700433 Py_EndInterpreter(tstate);
434 PyThreadState_Swap(save_tstate);
435 }
436}
437
Eric Snowc11183c2019-03-15 16:35:46 -0600438int
439_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
440{
441 return interp->requires_idref;
442}
443
444void
445_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
446{
447 interp->requires_idref = required ? 1 : 0;
448}
449
Eric Snowbe3b2952019-02-23 11:35:52 -0700450_PyCoreConfig *
451_PyInterpreterState_GetCoreConfig(PyInterpreterState *interp)
452{
453 return &interp->core_config;
454}
455
Eric Snowc11183c2019-03-15 16:35:46 -0600456PyObject *
457_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
458{
459 if (interp->modules == NULL) {
460 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
461 return NULL;
462 }
463 return PyMapping_GetItemString(interp->modules, "__main__");
464}
465
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600466PyObject *
467PyInterpreterState_GetDict(PyInterpreterState *interp)
468{
469 if (interp->dict == NULL) {
470 interp->dict = PyDict_New();
471 if (interp->dict == NULL) {
472 PyErr_Clear();
473 }
474 }
475 /* Returning NULL means no per-interpreter dict is available. */
476 return interp->dict;
477}
478
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000479/* Default implementation for _PyThreadState_GetFrame */
480static struct _frame *
481threadstate_getframe(PyThreadState *self)
482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000484}
485
Victor Stinner45b9be52010-03-03 23:28:07 +0000486static PyThreadState *
487new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000488{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200489 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 if (_PyThreadState_GetFrame == NULL)
492 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (tstate != NULL) {
495 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 tstate->frame = NULL;
498 tstate->recursion_depth = 0;
499 tstate->overflowed = 0;
500 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700501 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 tstate->tracing = 0;
503 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 tstate->gilstate_counter = 0;
505 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 tstate->curexc_type = NULL;
511 tstate->curexc_value = NULL;
512 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000513
Mark Shannonae3087c2017-10-22 22:41:51 +0100514 tstate->exc_state.exc_type = NULL;
515 tstate->exc_state.exc_value = NULL;
516 tstate->exc_state.exc_traceback = NULL;
517 tstate->exc_state.previous_item = NULL;
518 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 tstate->c_profilefunc = NULL;
521 tstate->c_tracefunc = NULL;
522 tstate->c_profileobj = NULL;
523 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000524
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200525 tstate->trash_delete_nesting = 0;
526 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200527 tstate->on_delete = NULL;
528 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200529
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800530 tstate->coroutine_origin_tracking_depth = 0;
531
Yury Selivanov75445082015-05-11 22:57:16 -0400532 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400533 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400534
Yury Selivanoveb636452016-09-08 22:01:51 -0700535 tstate->async_gen_firstiter = NULL;
536 tstate->async_gen_finalizer = NULL;
537
Yury Selivanovf23746a2018-01-22 19:11:18 -0500538 tstate->context = NULL;
539 tstate->context_ver = 1;
540
541 tstate->id = ++interp->tstate_next_unique_id;
542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 if (init)
544 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200547 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200549 if (tstate->next)
550 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 interp->tstate_head = tstate;
552 HEAD_UNLOCK();
553 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000556}
557
Victor Stinner45b9be52010-03-03 23:28:07 +0000558PyThreadState *
559PyThreadState_New(PyInterpreterState *interp)
560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000562}
563
564PyThreadState *
565_PyThreadState_Prealloc(PyInterpreterState *interp)
566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000568}
569
570void
571_PyThreadState_Init(PyThreadState *tstate)
572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000574}
575
Martin v. Löwis1a214512008-06-11 05:26:20 +0000576PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200577PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000578{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200579 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100580 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000582 if (module->m_slots) {
583 return NULL;
584 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 if (index == 0)
586 return NULL;
587 if (state->modules_by_index == NULL)
588 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200589 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 return NULL;
591 res = PyList_GET_ITEM(state->modules_by_index, index);
592 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000593}
594
595int
596_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
597{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000598 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300599 if (!def) {
600 assert(PyErr_Occurred());
601 return -1;
602 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000603 if (def->m_slots) {
604 PyErr_SetString(PyExc_SystemError,
605 "PyState_AddModule called on module with slots");
606 return -1;
607 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100608 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (!state->modules_by_index) {
610 state->modules_by_index = PyList_New(0);
611 if (!state->modules_by_index)
612 return -1;
613 }
614 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
615 if (PyList_Append(state->modules_by_index, Py_None) < 0)
616 return -1;
617 Py_INCREF(module);
618 return PyList_SetItem(state->modules_by_index,
619 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000620}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000621
Martin v. Löwis7800f752012-06-22 12:20:55 +0200622int
623PyState_AddModule(PyObject* module, struct PyModuleDef* def)
624{
625 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100626 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200627 if (!def) {
628 Py_FatalError("PyState_AddModule: Module Definition is NULL");
629 return -1;
630 }
631 index = def->m_base.m_index;
632 if (state->modules_by_index) {
633 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
634 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
635 Py_FatalError("PyState_AddModule: Module already added!");
636 return -1;
637 }
638 }
639 }
640 return _PyState_AddModule(module, def);
641}
642
643int
644PyState_RemoveModule(struct PyModuleDef* def)
645{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000646 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200647 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000648 if (def->m_slots) {
649 PyErr_SetString(PyExc_SystemError,
650 "PyState_RemoveModule called on module with slots");
651 return -1;
652 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100653 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200654 if (index == 0) {
655 Py_FatalError("PyState_RemoveModule: Module index invalid.");
656 return -1;
657 }
658 if (state->modules_by_index == NULL) {
659 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
660 return -1;
661 }
662 if (index > PyList_GET_SIZE(state->modules_by_index)) {
663 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
664 return -1;
665 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700666 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200667 return PyList_SetItem(state->modules_by_index, index, Py_None);
668}
669
Antoine Pitrou40322e62013-08-11 00:30:09 +0200670/* used by import.c:PyImport_Cleanup */
671void
672_PyState_ClearModules(void)
673{
Victor Stinner9204fb82018-10-30 15:13:17 +0100674 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200675 if (state->modules_by_index) {
676 Py_ssize_t i;
677 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
678 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
679 if (PyModule_Check(m)) {
680 /* cleanup the saved copy of module dicts */
681 PyModuleDef *md = PyModule_GetDef(m);
682 if (md)
683 Py_CLEAR(md->m_base.m_copy);
684 }
685 }
686 /* Setting modules_by_index to NULL could be dangerous, so we
687 clear the list instead. */
688 if (PyList_SetSlice(state->modules_by_index,
689 0, PyList_GET_SIZE(state->modules_by_index),
690 NULL))
691 PyErr_WriteUnraisable(state->modules_by_index);
692 }
693}
694
Guido van Rossuma027efa1997-05-05 20:56:21 +0000695void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000696PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000697{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200698 int verbose = tstate->interp->core_config.verbose;
699
700 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 fprintf(stderr,
702 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 Py_CLEAR(tstate->dict);
707 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 Py_CLEAR(tstate->curexc_type);
710 Py_CLEAR(tstate->curexc_value);
711 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000712
Mark Shannonae3087c2017-10-22 22:41:51 +0100713 Py_CLEAR(tstate->exc_state.exc_type);
714 Py_CLEAR(tstate->exc_state.exc_value);
715 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300716
Mark Shannonae3087c2017-10-22 22:41:51 +0100717 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200718 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100719 fprintf(stderr,
720 "PyThreadState_Clear: warning: thread still has a generator\n");
721 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 tstate->c_profilefunc = NULL;
724 tstate->c_tracefunc = NULL;
725 Py_CLEAR(tstate->c_profileobj);
726 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400727
728 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700729 Py_CLEAR(tstate->async_gen_firstiter);
730 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500731
732 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000733}
734
735
Guido van Rossum29757862001-01-23 01:46:06 +0000736/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
737static void
738tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 if (tstate == NULL)
742 Py_FatalError("PyThreadState_Delete: NULL tstate");
743 interp = tstate->interp;
744 if (interp == NULL)
745 Py_FatalError("PyThreadState_Delete: NULL interp");
746 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200747 if (tstate->prev)
748 tstate->prev->next = tstate->next;
749 else
750 interp->tstate_head = tstate->next;
751 if (tstate->next)
752 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200754 if (tstate->on_delete != NULL) {
755 tstate->on_delete(tstate->on_delete_data);
756 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200757 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000758}
759
760
Guido van Rossum29757862001-01-23 01:46:06 +0000761void
762PyThreadState_Delete(PyThreadState *tstate)
763{
Victor Stinner50b48572018-11-01 01:51:40 +0100764 if (tstate == _PyThreadState_GET())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600766 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900767 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600768 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900769 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600770 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200771 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000772}
773
774
Guido van Rossum29757862001-01-23 01:46:06 +0000775void
776PyThreadState_DeleteCurrent()
777{
Victor Stinner50b48572018-11-01 01:51:40 +0100778 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if (tstate == NULL)
780 Py_FatalError(
781 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100782 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600783 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900784 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600785 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900786 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600787 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100788 _PyThreadState_SET(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000790}
Guido van Rossum29757862001-01-23 01:46:06 +0000791
792
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200793/*
794 * Delete all thread states except the one passed as argument.
795 * Note that, if there is a current thread state, it *must* be the one
796 * passed as argument. Also, this won't touch any other interpreters
797 * than the current one, since we don't know which thread state should
798 * be kept in those other interpreteres.
799 */
800void
801_PyThreadState_DeleteExcept(PyThreadState *tstate)
802{
803 PyInterpreterState *interp = tstate->interp;
804 PyThreadState *p, *next, *garbage;
805 HEAD_LOCK();
806 /* Remove all thread states, except tstate, from the linked list of
807 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200808 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200809 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200810 if (garbage == tstate)
811 garbage = tstate->next;
812 if (tstate->prev)
813 tstate->prev->next = tstate->next;
814 if (tstate->next)
815 tstate->next->prev = tstate->prev;
816 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200817 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200818 HEAD_UNLOCK();
819 /* Clear and deallocate all stale thread states. Even if this
820 executes Python code, we should be safe since it executes
821 in the current thread, not one of the stale threads. */
822 for (p = garbage; p; p = next) {
823 next = p->next;
824 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200825 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200826 }
827}
828
829
Guido van Rossuma027efa1997-05-05 20:56:21 +0000830PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100831_PyThreadState_UncheckedGet(void)
832{
Victor Stinner50b48572018-11-01 01:51:40 +0100833 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100834}
835
836
837PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000838PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000839{
Victor Stinner50b48572018-11-01 01:51:40 +0100840 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 if (tstate == NULL)
842 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000845}
846
847
848PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000849PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000850{
Victor Stinner50b48572018-11-01 01:51:40 +0100851 PyThreadState *oldts = _PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000852
Victor Stinner9204fb82018-10-30 15:13:17 +0100853 _PyThreadState_SET(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 /* It should not be possible for more than one thread state
855 to be used for a thread. Check this the best we can in debug
856 builds.
857 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200858#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 if (newts) {
860 /* This can be called from PyEval_RestoreThread(). Similar
861 to it, we need to ensure errno doesn't change.
862 */
863 int err = errno;
864 PyThreadState *check = PyGILState_GetThisThreadState();
865 if (check && check->interp == newts->interp && check != newts)
866 Py_FatalError("Invalid thread state for this thread");
867 errno = err;
868 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000869#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000871}
Guido van Rossumede04391998-04-10 20:18:25 +0000872
873/* An extension mechanism to store arbitrary additional per-thread state.
874 PyThreadState_GetDict() returns a dictionary that can be used to hold such
875 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000876 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
877 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000878
879PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000880PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000881{
Victor Stinner50b48572018-11-01 01:51:40 +0100882 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 if (tstate == NULL)
884 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 if (tstate->dict == NULL) {
887 PyObject *d;
888 tstate->dict = d = PyDict_New();
889 if (d == NULL)
890 PyErr_Clear();
891 }
892 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000893}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000894
895
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000896/* Asynchronously raise an exception in a thread.
897 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000898 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000899 to call this, or use ctypes. Must be called with the GIL held.
900 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
901 match any known thread id). Can be called with exc=NULL to clear an
902 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000903
904int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200905PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
906{
Victor Stinner9204fb82018-10-30 15:13:17 +0100907 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000909
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 /* Although the GIL is held, a few C API functions can be called
911 * without the GIL held, and in particular some that create and
912 * destroy thread and interpreter states. Those can mutate the
913 * list of thread states we're traversing, so to prevent that we lock
914 * head_mutex for the duration.
915 */
916 HEAD_LOCK();
917 for (p = interp->tstate_head; p != NULL; p = p->next) {
918 if (p->thread_id == id) {
919 /* Tricky: we need to decref the current value
920 * (if any) in p->async_exc, but that can in turn
921 * allow arbitrary Python code to run, including
922 * perhaps calls to this function. To prevent
923 * deadlock, we need to release head_mutex before
924 * the decref.
925 */
926 PyObject *old_exc = p->async_exc;
927 Py_XINCREF(exc);
928 p->async_exc = exc;
929 HEAD_UNLOCK();
930 Py_XDECREF(old_exc);
Eric Snowb75b1a352019-04-12 10:20:10 -0600931 _PyEval_SignalAsyncExc();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 return 1;
933 }
934 }
935 HEAD_UNLOCK();
936 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000937}
938
939
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000940/* Routines for advanced debuggers, requested by David Beazley.
941 Don't use unless you know what you are doing! */
942
943PyInterpreterState *
944PyInterpreterState_Head(void)
945{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600946 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000947}
948
949PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700950PyInterpreterState_Main(void)
951{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600952 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700953}
954
955PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000956PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000957 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000958}
959
960PyThreadState *
961PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000963}
964
965PyThreadState *
966PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000968}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000969
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000970/* The implementation of sys._current_frames(). This is intended to be
971 called with the GIL held, as it will be when called via
972 sys._current_frames(). It's possible it would work fine even without
973 the GIL held, but haven't thought enough about that.
974*/
975PyObject *
976_PyThread_CurrentFrames(void)
977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 PyObject *result;
979 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 result = PyDict_New();
982 if (result == NULL)
983 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 /* for i in all interpreters:
986 * for t in all of i's thread states:
987 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200988 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 * need to grab head_mutex for the duration.
990 */
991 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600992 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 PyThreadState *t;
994 for (t = i->tstate_head; t != NULL; t = t->next) {
995 PyObject *id;
996 int stat;
997 struct _frame *frame = t->frame;
998 if (frame == NULL)
999 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001000 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 if (id == NULL)
1002 goto Fail;
1003 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1004 Py_DECREF(id);
1005 if (stat < 0)
1006 goto Fail;
1007 }
1008 }
1009 HEAD_UNLOCK();
1010 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001011
1012 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 HEAD_UNLOCK();
1014 Py_DECREF(result);
1015 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001016}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001017
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001018/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001019
1020/* Keep this as a static, as it is not reliable! It can only
1021 ever be compared to the state for the *current* thread.
1022 * If not equal, then it doesn't matter that the actual
1023 value may change immediately after comparison, as it can't
1024 possibly change to the current thread's state.
1025 * If equal, then the current thread holds the lock, so the value can't
1026 change until we yield the lock.
1027*/
1028static int
1029PyThreadState_IsCurrent(PyThreadState *tstate)
1030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 /* Must be the tstate for this thread */
1032 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinner50b48572018-11-01 01:51:40 +01001033 return tstate == _PyThreadState_GET();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001034}
1035
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001036/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001037 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001038*/
Tim Peters19717fa2004-10-09 17:38:29 +00001039void
1040_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001043 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1044 Py_FatalError("Could not allocate TSS entry");
1045 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001046 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001047 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001051}
1052
Victor Stinner861d9ab2016-03-16 22:45:24 +01001053PyInterpreterState *
1054_PyGILState_GetInterpreterStateUnsafe(void)
1055{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001056 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001057}
1058
Tim Peters19717fa2004-10-09 17:38:29 +00001059void
1060_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001061{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001062 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001063 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001064}
1065
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001066/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001067 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001068 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001069 */
1070void
1071_PyGILState_Reinit(void)
1072{
Victor Stinner5d926472018-03-06 14:31:37 +01001073 /* Force default allocator, since _PyRuntimeState_Fini() must
1074 use the same allocator than this function. */
1075 PyMemAllocatorEx old_alloc;
1076 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1077
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001078 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +01001079
1080 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1081
1082 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001083 Py_FatalError("Can't initialize threads for interpreter");
Victor Stinner5d926472018-03-06 14:31:37 +01001084 }
1085
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001086 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001087 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
1088 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1089 Py_FatalError("Could not allocate TSS entry");
1090 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001091
Charles-François Natalia233df82011-11-22 19:49:51 +01001092 /* If the thread had an associated auto thread state, reassociate it with
1093 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001094 if (tstate &&
1095 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
1096 {
1097 Py_FatalError("Couldn't create autoTSSkey mapping");
1098 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001099}
1100
Michael W. Hudson188d4362005-06-20 16:52:57 +00001101/* When a thread state is created for a thread by some mechanism other than
1102 PyGILState_Ensure, it's important that the GILState machinery knows about
1103 it so it doesn't try to create another thread state for the thread (this is
1104 a better fix for SF bug #1010677 than the first one attempted).
1105*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001106static void
Michael W. Hudson188d4362005-06-20 16:52:57 +00001107_PyGILState_NoteThreadState(PyThreadState* tstate)
1108{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001109 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001110 threadstate created in Py_Initialize(). Don't do anything for now
1111 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001112 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001114
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001115 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 The only situation where you can legitimately have more than one
1118 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001119 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001120
Victor Stinner590cebe2013-12-13 11:08:56 +01001121 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1122 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001123
Victor Stinner590cebe2013-12-13 11:08:56 +01001124 The first thread state created for that given OS level thread will
1125 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001127 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
1128 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1129 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001130 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001131 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001132 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001133 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 /* PyGILState_Release must not try to delete this thread state. */
1136 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001137}
1138
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001139/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001140PyThreadState *
1141PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001142{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001143 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001145 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001146}
1147
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001148int
1149PyGILState_Check(void)
1150{
Victor Stinner8a1be612016-03-14 22:07:55 +01001151 PyThreadState *tstate;
1152
1153 if (!_PyGILState_check_enabled)
1154 return 1;
1155
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001156 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001157 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001158 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001159
Victor Stinner50b48572018-11-01 01:51:40 +01001160 tstate = _PyThreadState_GET();
Victor Stinner8a1be612016-03-14 22:07:55 +01001161 if (tstate == NULL)
1162 return 0;
1163
1164 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001165}
1166
Tim Peters19717fa2004-10-09 17:38:29 +00001167PyGILState_STATE
1168PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 int current;
1171 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001172 int need_init_threads = 0;
1173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 /* Note that we do not auto-init Python here - apart from
1175 potential races with 2 threads auto-initializing, pep-311
1176 spells out other issues. Embedders are expected to have
1177 called Py_Initialize() and usually PyEval_InitThreads().
1178 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001179 /* Py_Initialize() hasn't been called! */
1180 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001181
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001182 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001184 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001185
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001187 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 if (tcur == NULL)
1189 Py_FatalError("Couldn't create thread-state for new thread");
1190 /* This is our thread state! We'll need to delete it in the
1191 matching call to PyGILState_Release(). */
1192 tcur->gilstate_counter = 0;
1193 current = 0; /* new thread state is never current */
1194 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001195 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001197 }
1198
1199 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001201 }
1202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 /* Update our counter in the thread-state - no need for locks:
1204 - tcur will remain valid as we hold the GIL.
1205 - the counter is safe as we are the only thread "allowed"
1206 to modify this value
1207 */
1208 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001209
1210 if (need_init_threads) {
1211 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1212 called from a new thread for the first time, we need the create the
1213 GIL. */
1214 PyEval_InitThreads();
1215 }
1216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001218}
1219
Tim Peters19717fa2004-10-09 17:38:29 +00001220void
1221PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001222{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001223 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1224 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 if (tcur == NULL)
1226 Py_FatalError("auto-releasing thread-state, "
1227 "but no thread-state for this thread");
1228 /* We must hold the GIL and have our thread state current */
1229 /* XXX - remove the check - the assert should be fine,
1230 but while this is very new (April 2003), the extra check
1231 by release-only users can't hurt.
1232 */
1233 if (! PyThreadState_IsCurrent(tcur))
1234 Py_FatalError("This thread state must be current when releasing");
1235 assert(PyThreadState_IsCurrent(tcur));
1236 --tcur->gilstate_counter;
1237 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 /* If we're going to destroy this thread-state, we must
1240 * clear it while the GIL is held, as destructors may run.
1241 */
1242 if (tcur->gilstate_counter == 0) {
1243 /* can't have been locked when we created it */
1244 assert(oldstate == PyGILState_UNLOCKED);
1245 PyThreadState_Clear(tcur);
1246 /* Delete the thread-state. Note this releases the GIL too!
1247 * It's vital that the GIL be held here, to avoid shutdown
1248 * races; see bugs 225673 and 1061968 (that nasty bug has a
1249 * habit of coming back).
1250 */
1251 PyThreadState_DeleteCurrent();
1252 }
1253 /* Release the lock if necessary */
1254 else if (oldstate == PyGILState_UNLOCKED)
1255 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001256}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001257
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001258
Eric Snow7f8bfc92018-01-29 18:23:44 -07001259/**************************/
1260/* cross-interpreter data */
1261/**************************/
1262
1263/* cross-interpreter data */
1264
1265crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1266
1267/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1268 to keep the registry code separate. */
1269static crossinterpdatafunc
1270_lookup_getdata(PyObject *obj)
1271{
1272 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1273 if (getdata == NULL && PyErr_Occurred() == 0)
1274 PyErr_Format(PyExc_ValueError,
1275 "%S does not support cross-interpreter data", obj);
1276 return getdata;
1277}
1278
1279int
1280_PyObject_CheckCrossInterpreterData(PyObject *obj)
1281{
1282 crossinterpdatafunc getdata = _lookup_getdata(obj);
1283 if (getdata == NULL) {
1284 return -1;
1285 }
1286 return 0;
1287}
1288
1289static int
1290_check_xidata(_PyCrossInterpreterData *data)
1291{
1292 // data->data can be anything, including NULL, so we don't check it.
1293
1294 // data->obj may be NULL, so we don't check it.
1295
1296 if (data->interp < 0) {
1297 PyErr_SetString(PyExc_SystemError, "missing interp");
1298 return -1;
1299 }
1300
1301 if (data->new_object == NULL) {
1302 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1303 return -1;
1304 }
1305
1306 // data->free may be NULL, so we don't check it.
1307
1308 return 0;
1309}
1310
1311int
1312_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1313{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001314 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001315 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001316 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001317
1318 // Reset data before re-populating.
1319 *data = (_PyCrossInterpreterData){0};
1320 data->free = PyMem_RawFree; // Set a default that may be overridden.
1321
1322 // Call the "getdata" func for the object.
1323 Py_INCREF(obj);
1324 crossinterpdatafunc getdata = _lookup_getdata(obj);
1325 if (getdata == NULL) {
1326 Py_DECREF(obj);
1327 return -1;
1328 }
1329 int res = getdata(obj, data);
1330 Py_DECREF(obj);
1331 if (res != 0) {
1332 return -1;
1333 }
1334
1335 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001336 data->interp = interp->id;
1337 if (_check_xidata(data) != 0) {
1338 _PyCrossInterpreterData_Release(data);
1339 return -1;
1340 }
1341
1342 return 0;
1343}
1344
Eric Snowb75b1a352019-04-12 10:20:10 -06001345static void
Eric Snow63799132018-06-01 18:45:20 -06001346_release_xidata(void *arg)
1347{
1348 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1349 if (data->free != NULL) {
1350 data->free(data->data);
1351 }
1352 Py_XDECREF(data->obj);
Eric Snowb75b1a352019-04-12 10:20:10 -06001353}
1354
1355static void
1356_call_in_interpreter(PyInterpreterState *interp,
1357 void (*func)(void *), void *arg)
1358{
1359 /* We would use Py_AddPendingCall() if it weren't specific to the
1360 * main interpreter (see bpo-33608). In the meantime we take a
1361 * naive approach.
1362 */
1363 PyThreadState *save_tstate = NULL;
1364 if (interp != _PyInterpreterState_Get()) {
1365 // XXX Using the "head" thread isn't strictly correct.
1366 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1367 // XXX Possible GILState issues?
1368 save_tstate = PyThreadState_Swap(tstate);
1369 }
1370
1371 func(arg);
1372
1373 // Switch back.
1374 if (save_tstate != NULL) {
1375 PyThreadState_Swap(save_tstate);
1376 }
Eric Snow63799132018-06-01 18:45:20 -06001377}
1378
Eric Snow7f8bfc92018-01-29 18:23:44 -07001379void
1380_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1381{
1382 if (data->data == NULL && data->obj == NULL) {
1383 // Nothing to release!
1384 return;
1385 }
1386
Eric Snowb75b1a352019-04-12 10:20:10 -06001387 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001388 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1389 if (interp == NULL) {
1390 // The intepreter was already destroyed.
1391 if (data->free != NULL) {
1392 // XXX Someone leaked some memory...
1393 }
1394 return;
1395 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001396
Eric Snow7f8bfc92018-01-29 18:23:44 -07001397 // "Release" the data and/or the object.
Eric Snowb75b1a352019-04-12 10:20:10 -06001398 _call_in_interpreter(interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001399}
1400
1401PyObject *
1402_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1403{
1404 return data->new_object(data);
1405}
1406
1407/* registry of {type -> crossinterpdatafunc} */
1408
1409/* For now we use a global registry of shareable classes. An
1410 alternative would be to add a tp_* slot for a class's
1411 crossinterpdatafunc. It would be simpler and more efficient. */
1412
1413static int
1414_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1415{
1416 // Note that we effectively replace already registered classes
1417 // rather than failing.
1418 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1419 if (newhead == NULL)
1420 return -1;
1421 newhead->cls = cls;
1422 newhead->getdata = getdata;
1423 newhead->next = _PyRuntime.xidregistry.head;
1424 _PyRuntime.xidregistry.head = newhead;
1425 return 0;
1426}
1427
1428static void _register_builtins_for_crossinterpreter_data(void);
1429
1430int
Eric Snowc11183c2019-03-15 16:35:46 -06001431_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001432 crossinterpdatafunc getdata)
1433{
1434 if (!PyType_Check(cls)) {
1435 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1436 return -1;
1437 }
1438 if (getdata == NULL) {
1439 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1440 return -1;
1441 }
1442
1443 // Make sure the class isn't ever deallocated.
1444 Py_INCREF((PyObject *)cls);
1445
1446 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1447 if (_PyRuntime.xidregistry.head == NULL) {
1448 _register_builtins_for_crossinterpreter_data();
1449 }
1450 int res = _register_xidata(cls, getdata);
1451 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1452 return res;
1453}
1454
Eric Snow6d2cd902018-05-16 15:04:57 -04001455/* Cross-interpreter objects are looked up by exact match on the class.
1456 We can reassess this policy when we move from a global registry to a
1457 tp_* slot. */
1458
Eric Snow7f8bfc92018-01-29 18:23:44 -07001459crossinterpdatafunc
1460_PyCrossInterpreterData_Lookup(PyObject *obj)
1461{
1462 PyObject *cls = PyObject_Type(obj);
1463 crossinterpdatafunc getdata = NULL;
1464 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1465 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1466 if (cur == NULL) {
1467 _register_builtins_for_crossinterpreter_data();
1468 cur = _PyRuntime.xidregistry.head;
1469 }
1470 for(; cur != NULL; cur = cur->next) {
1471 if (cur->cls == (PyTypeObject *)cls) {
1472 getdata = cur->getdata;
1473 break;
1474 }
1475 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001476 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001477 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1478 return getdata;
1479}
1480
1481/* cross-interpreter data for builtin types */
1482
Eric Snow6d2cd902018-05-16 15:04:57 -04001483struct _shared_bytes_data {
1484 char *bytes;
1485 Py_ssize_t len;
1486};
1487
Eric Snow7f8bfc92018-01-29 18:23:44 -07001488static PyObject *
1489_new_bytes_object(_PyCrossInterpreterData *data)
1490{
Eric Snow6d2cd902018-05-16 15:04:57 -04001491 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1492 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001493}
1494
1495static int
1496_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1497{
Eric Snow6d2cd902018-05-16 15:04:57 -04001498 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1499 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1500 return -1;
1501 }
1502 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001503 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001504 data->obj = obj; // Will be "released" (decref'ed) when data released.
1505 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001506 data->free = PyMem_Free;
1507 return 0;
1508}
1509
1510struct _shared_str_data {
1511 int kind;
1512 const void *buffer;
1513 Py_ssize_t len;
1514};
1515
1516static PyObject *
1517_new_str_object(_PyCrossInterpreterData *data)
1518{
1519 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1520 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1521}
1522
1523static int
1524_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1525{
1526 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1527 shared->kind = PyUnicode_KIND(obj);
1528 shared->buffer = PyUnicode_DATA(obj);
1529 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1530 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001531 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001532 data->obj = obj; // Will be "released" (decref'ed) when data released.
1533 data->new_object = _new_str_object;
1534 data->free = PyMem_Free;
1535 return 0;
1536}
1537
1538static PyObject *
1539_new_long_object(_PyCrossInterpreterData *data)
1540{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001541 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001542}
1543
1544static int
1545_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1546{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001547 /* Note that this means the size of shareable ints is bounded by
1548 * sys.maxsize. Hence on 32-bit architectures that is half the
1549 * size of maximum shareable ints on 64-bit.
1550 */
1551 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001552 if (value == -1 && PyErr_Occurred()) {
1553 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1554 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1555 }
1556 return -1;
1557 }
1558 data->data = (void *)value;
1559 data->obj = NULL;
1560 data->new_object = _new_long_object;
1561 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001562 return 0;
1563}
1564
1565static PyObject *
1566_new_none_object(_PyCrossInterpreterData *data)
1567{
1568 // XXX Singleton refcounts are problematic across interpreters...
1569 Py_INCREF(Py_None);
1570 return Py_None;
1571}
1572
1573static int
1574_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1575{
1576 data->data = NULL;
1577 // data->obj remains NULL
1578 data->new_object = _new_none_object;
1579 data->free = NULL; // There is nothing to free.
1580 return 0;
1581}
1582
1583static void
1584_register_builtins_for_crossinterpreter_data(void)
1585{
1586 // None
1587 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1588 Py_FatalError("could not register None for cross-interpreter sharing");
1589 }
1590
Eric Snow6d2cd902018-05-16 15:04:57 -04001591 // int
1592 if (_register_xidata(&PyLong_Type, _long_shared) != 0) {
1593 Py_FatalError("could not register int for cross-interpreter sharing");
1594 }
1595
Eric Snow7f8bfc92018-01-29 18:23:44 -07001596 // bytes
1597 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1598 Py_FatalError("could not register bytes for cross-interpreter sharing");
1599 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001600
1601 // str
1602 if (_register_xidata(&PyUnicode_Type, _str_shared) != 0) {
1603 Py_FatalError("could not register str for cross-interpreter sharing");
1604 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001605}
1606
1607
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001608#ifdef __cplusplus
1609}
1610#endif