blob: 6fe3dd1ff3fa2d55f0835648e7ead5e959820954 [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;
177 interp->config = _PyMainInterpreterConfig_INIT;
Victor Stinnerd4341102017-11-23 00:12:09 +0100178 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000179#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300180#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100181 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000182#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100183 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000184#endif
185#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000186
Victor Stinnerd4341102017-11-23 00:12:09 +0100187 HEAD_LOCK();
Victor Stinnerd4341102017-11-23 00:12:09 +0100188 if (_PyRuntime.interpreters.next_id < 0) {
189 /* overflow or Py_Initialize() not called! */
190 PyErr_SetString(PyExc_RuntimeError,
191 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100192 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100193 interp = NULL;
194 } else {
195 interp->id = _PyRuntime.interpreters.next_id;
196 _PyRuntime.interpreters.next_id += 1;
Pablo Galindo95d630e2018-08-31 22:49:29 +0100197 interp->next = _PyRuntime.interpreters.head;
198 if (_PyRuntime.interpreters.main == NULL) {
199 _PyRuntime.interpreters.main = interp;
200 }
201 _PyRuntime.interpreters.head = interp;
Victor Stinnerd4341102017-11-23 00:12:09 +0100202 }
203 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000204
Pablo Galindo95d630e2018-08-31 22:49:29 +0100205 if (interp == NULL) {
206 return NULL;
207 }
208
Yury Selivanovf23746a2018-01-22 19:11:18 -0500209 interp->tstate_next_unique_id = 0;
210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000212}
213
214
215void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000216PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 PyThreadState *p;
219 HEAD_LOCK();
220 for (p = interp->tstate_head; p != NULL; p = p->next)
221 PyThreadState_Clear(p);
222 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100223 _PyCoreConfig_Clear(&interp->core_config);
224 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 Py_CLEAR(interp->codec_search_path);
226 Py_CLEAR(interp->codec_search_cache);
227 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700228 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 Py_CLEAR(interp->sysdict);
231 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200232 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400233 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300234 Py_CLEAR(interp->import_func);
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600235 Py_CLEAR(interp->dict);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200236#ifdef HAVE_FORK
237 Py_CLEAR(interp->before_forkers);
238 Py_CLEAR(interp->after_forkers_parent);
239 Py_CLEAR(interp->after_forkers_child);
240#endif
Eric Snow5be45a62019-03-08 22:47:07 -0700241 // XXX Once we have one allocator per interpreter (i.e.
242 // per-interpreter GC) we must ensure that all of the interpreter's
243 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000244}
245
246
247static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000248zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 PyThreadState *p;
251 /* No need to lock the mutex here because this should only happen
252 when the threads are all really dead (XXX famous last words). */
253 while ((p = interp->tstate_head) != NULL) {
254 PyThreadState_Delete(p);
255 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000256}
257
258
259void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000260PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000261{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 PyInterpreterState **p;
263 zapthreads(interp);
264 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600265 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 if (*p == NULL)
267 Py_FatalError(
268 "PyInterpreterState_Delete: invalid interp");
269 if (*p == interp)
270 break;
271 }
272 if (interp->tstate_head != NULL)
273 Py_FatalError("PyInterpreterState_Delete: remaining threads");
274 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600275 if (_PyRuntime.interpreters.main == interp) {
276 _PyRuntime.interpreters.main = NULL;
277 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700278 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
279 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 HEAD_UNLOCK();
Eric Snow4c6955e2018-02-16 18:53:40 -0700281 if (interp->id_mutex != NULL) {
282 PyThread_free_lock(interp->id_mutex);
283 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200284 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000285}
286
287
Eric Snow59032962018-09-14 14:17:20 -0700288/*
289 * Delete all interpreter states except the main interpreter. If there
290 * is a current interpreter state, it *must* be the main interpreter.
291 */
292void
293_PyInterpreterState_DeleteExceptMain()
294{
295 PyThreadState *tstate = PyThreadState_Swap(NULL);
296 if (tstate != NULL && tstate->interp != _PyRuntime.interpreters.main) {
297 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
298 }
299
300 HEAD_LOCK();
301 PyInterpreterState *interp = _PyRuntime.interpreters.head;
302 _PyRuntime.interpreters.head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100303 while (interp != NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700304 if (interp == _PyRuntime.interpreters.main) {
305 _PyRuntime.interpreters.main->next = NULL;
306 _PyRuntime.interpreters.head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100307 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700308 continue;
309 }
310
311 PyInterpreterState_Clear(interp); // XXX must activate?
312 zapthreads(interp);
313 if (interp->id_mutex != NULL) {
314 PyThread_free_lock(interp->id_mutex);
315 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100316 PyInterpreterState *prev_interp = interp;
317 interp = interp->next;
318 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700319 }
320 HEAD_UNLOCK();
321
322 if (_PyRuntime.interpreters.head == NULL) {
323 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
324 }
325 PyThreadState_Swap(tstate);
326}
327
328
Victor Stinnercaba55b2018-08-03 15:33:52 +0200329PyInterpreterState *
330_PyInterpreterState_Get(void)
331{
Victor Stinner50b48572018-11-01 01:51:40 +0100332 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200333 if (tstate == NULL) {
334 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
335 }
336 PyInterpreterState *interp = tstate->interp;
337 if (interp == NULL) {
338 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
339 }
340 return interp;
341}
342
343
Eric Snowe3774162017-05-22 19:46:40 -0700344int64_t
345PyInterpreterState_GetID(PyInterpreterState *interp)
346{
347 if (interp == NULL) {
348 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
349 return -1;
350 }
351 return interp->id;
352}
353
354
Eric Snow5be45a62019-03-08 22:47:07 -0700355static PyInterpreterState *
356interp_look_up_id(PY_INT64_T requested_id)
Eric Snowb05b7112019-03-01 12:35:10 -0700357{
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100358 PyInterpreterState *interp = PyInterpreterState_Head();
359 while (interp != NULL) {
360 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snow5be45a62019-03-08 22:47:07 -0700361 if (id < 0) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100362 return NULL;
Eric Snow5be45a62019-03-08 22:47:07 -0700363 }
364 if (requested_id == id) {
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100365 return interp;
Eric Snow5be45a62019-03-08 22:47:07 -0700366 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100367 interp = PyInterpreterState_Next(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700368 }
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100369 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700370}
371
Eric Snow5be45a62019-03-08 22:47:07 -0700372PyInterpreterState *
373_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
374{
375 PyInterpreterState *interp = NULL;
376 if (requested_id >= 0) {
377 HEAD_LOCK();
378 interp = interp_look_up_id(requested_id);
379 HEAD_UNLOCK();
380 }
381 if (interp == NULL && !PyErr_Occurred()) {
382 PyErr_Format(PyExc_RuntimeError,
383 "unrecognized interpreter ID %lld", requested_id);
384 }
385 return interp;
386}
387
Eric Snow4c6955e2018-02-16 18:53:40 -0700388
389int
390_PyInterpreterState_IDInitref(PyInterpreterState *interp)
391{
392 if (interp->id_mutex != NULL) {
393 return 0;
394 }
395 interp->id_mutex = PyThread_allocate_lock();
396 if (interp->id_mutex == NULL) {
397 PyErr_SetString(PyExc_RuntimeError,
398 "failed to create init interpreter ID mutex");
399 return -1;
400 }
401 interp->id_refcount = 0;
402 return 0;
403}
404
405
406void
407_PyInterpreterState_IDIncref(PyInterpreterState *interp)
408{
409 if (interp->id_mutex == NULL) {
410 return;
411 }
412 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
413 interp->id_refcount += 1;
414 PyThread_release_lock(interp->id_mutex);
415}
416
417
418void
419_PyInterpreterState_IDDecref(PyInterpreterState *interp)
420{
421 if (interp->id_mutex == NULL) {
422 return;
423 }
424 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
425 assert(interp->id_refcount != 0);
426 interp->id_refcount -= 1;
427 int64_t refcount = interp->id_refcount;
428 PyThread_release_lock(interp->id_mutex);
429
Eric Snowc11183c2019-03-15 16:35:46 -0600430 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700431 // XXX Using the "head" thread isn't strictly correct.
432 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
433 // XXX Possible GILState issues?
434 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700435 Py_EndInterpreter(tstate);
436 PyThreadState_Swap(save_tstate);
437 }
438}
439
Eric Snowc11183c2019-03-15 16:35:46 -0600440int
441_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
442{
443 return interp->requires_idref;
444}
445
446void
447_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
448{
449 interp->requires_idref = required ? 1 : 0;
450}
451
Eric Snowbe3b2952019-02-23 11:35:52 -0700452_PyCoreConfig *
453_PyInterpreterState_GetCoreConfig(PyInterpreterState *interp)
454{
455 return &interp->core_config;
456}
457
458_PyMainInterpreterConfig *
459_PyInterpreterState_GetMainConfig(PyInterpreterState *interp)
460{
461 return &interp->config;
462}
Eric Snow4c6955e2018-02-16 18:53:40 -0700463
Eric Snowc11183c2019-03-15 16:35:46 -0600464PyObject *
465_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
466{
467 if (interp->modules == NULL) {
468 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
469 return NULL;
470 }
471 return PyMapping_GetItemString(interp->modules, "__main__");
472}
473
Eric Snowd2fdd1f2019-03-15 17:47:43 -0600474PyObject *
475PyInterpreterState_GetDict(PyInterpreterState *interp)
476{
477 if (interp->dict == NULL) {
478 interp->dict = PyDict_New();
479 if (interp->dict == NULL) {
480 PyErr_Clear();
481 }
482 }
483 /* Returning NULL means no per-interpreter dict is available. */
484 return interp->dict;
485}
486
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000487/* Default implementation for _PyThreadState_GetFrame */
488static struct _frame *
489threadstate_getframe(PyThreadState *self)
490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000492}
493
Victor Stinner45b9be52010-03-03 23:28:07 +0000494static PyThreadState *
495new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000496{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200497 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000498
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 if (_PyThreadState_GetFrame == NULL)
500 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 if (tstate != NULL) {
503 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 tstate->frame = NULL;
506 tstate->recursion_depth = 0;
507 tstate->overflowed = 0;
508 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700509 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 tstate->tracing = 0;
511 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 tstate->gilstate_counter = 0;
513 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 tstate->curexc_type = NULL;
519 tstate->curexc_value = NULL;
520 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000521
Mark Shannonae3087c2017-10-22 22:41:51 +0100522 tstate->exc_state.exc_type = NULL;
523 tstate->exc_state.exc_value = NULL;
524 tstate->exc_state.exc_traceback = NULL;
525 tstate->exc_state.previous_item = NULL;
526 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 tstate->c_profilefunc = NULL;
529 tstate->c_tracefunc = NULL;
530 tstate->c_profileobj = NULL;
531 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000532
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200533 tstate->trash_delete_nesting = 0;
534 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200535 tstate->on_delete = NULL;
536 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200537
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800538 tstate->coroutine_origin_tracking_depth = 0;
539
Yury Selivanov75445082015-05-11 22:57:16 -0400540 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400541 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400542
Yury Selivanoveb636452016-09-08 22:01:51 -0700543 tstate->async_gen_firstiter = NULL;
544 tstate->async_gen_finalizer = NULL;
545
Yury Selivanovf23746a2018-01-22 19:11:18 -0500546 tstate->context = NULL;
547 tstate->context_ver = 1;
548
549 tstate->id = ++interp->tstate_next_unique_id;
550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 if (init)
552 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000553
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200555 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200557 if (tstate->next)
558 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 interp->tstate_head = tstate;
560 HEAD_UNLOCK();
561 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000564}
565
Victor Stinner45b9be52010-03-03 23:28:07 +0000566PyThreadState *
567PyThreadState_New(PyInterpreterState *interp)
568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000570}
571
572PyThreadState *
573_PyThreadState_Prealloc(PyInterpreterState *interp)
574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000576}
577
578void
579_PyThreadState_Init(PyThreadState *tstate)
580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000582}
583
Martin v. Löwis1a214512008-06-11 05:26:20 +0000584PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200585PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000586{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200587 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100588 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000590 if (module->m_slots) {
591 return NULL;
592 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 if (index == 0)
594 return NULL;
595 if (state->modules_by_index == NULL)
596 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200597 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 return NULL;
599 res = PyList_GET_ITEM(state->modules_by_index, index);
600 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000601}
602
603int
604_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
605{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000606 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300607 if (!def) {
608 assert(PyErr_Occurred());
609 return -1;
610 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000611 if (def->m_slots) {
612 PyErr_SetString(PyExc_SystemError,
613 "PyState_AddModule called on module with slots");
614 return -1;
615 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100616 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (!state->modules_by_index) {
618 state->modules_by_index = PyList_New(0);
619 if (!state->modules_by_index)
620 return -1;
621 }
622 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
623 if (PyList_Append(state->modules_by_index, Py_None) < 0)
624 return -1;
625 Py_INCREF(module);
626 return PyList_SetItem(state->modules_by_index,
627 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000628}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000629
Martin v. Löwis7800f752012-06-22 12:20:55 +0200630int
631PyState_AddModule(PyObject* module, struct PyModuleDef* def)
632{
633 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100634 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200635 if (!def) {
636 Py_FatalError("PyState_AddModule: Module Definition is NULL");
637 return -1;
638 }
639 index = def->m_base.m_index;
640 if (state->modules_by_index) {
641 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
642 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
643 Py_FatalError("PyState_AddModule: Module already added!");
644 return -1;
645 }
646 }
647 }
648 return _PyState_AddModule(module, def);
649}
650
651int
652PyState_RemoveModule(struct PyModuleDef* def)
653{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000654 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200655 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000656 if (def->m_slots) {
657 PyErr_SetString(PyExc_SystemError,
658 "PyState_RemoveModule called on module with slots");
659 return -1;
660 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100661 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200662 if (index == 0) {
663 Py_FatalError("PyState_RemoveModule: Module index invalid.");
664 return -1;
665 }
666 if (state->modules_by_index == NULL) {
667 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
668 return -1;
669 }
670 if (index > PyList_GET_SIZE(state->modules_by_index)) {
671 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
672 return -1;
673 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700674 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200675 return PyList_SetItem(state->modules_by_index, index, Py_None);
676}
677
Antoine Pitrou40322e62013-08-11 00:30:09 +0200678/* used by import.c:PyImport_Cleanup */
679void
680_PyState_ClearModules(void)
681{
Victor Stinner9204fb82018-10-30 15:13:17 +0100682 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200683 if (state->modules_by_index) {
684 Py_ssize_t i;
685 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
686 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
687 if (PyModule_Check(m)) {
688 /* cleanup the saved copy of module dicts */
689 PyModuleDef *md = PyModule_GetDef(m);
690 if (md)
691 Py_CLEAR(md->m_base.m_copy);
692 }
693 }
694 /* Setting modules_by_index to NULL could be dangerous, so we
695 clear the list instead. */
696 if (PyList_SetSlice(state->modules_by_index,
697 0, PyList_GET_SIZE(state->modules_by_index),
698 NULL))
699 PyErr_WriteUnraisable(state->modules_by_index);
700 }
701}
702
Guido van Rossuma027efa1997-05-05 20:56:21 +0000703void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000704PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000705{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200706 int verbose = tstate->interp->core_config.verbose;
707
708 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 fprintf(stderr,
710 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 Py_CLEAR(tstate->dict);
715 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 Py_CLEAR(tstate->curexc_type);
718 Py_CLEAR(tstate->curexc_value);
719 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000720
Mark Shannonae3087c2017-10-22 22:41:51 +0100721 Py_CLEAR(tstate->exc_state.exc_type);
722 Py_CLEAR(tstate->exc_state.exc_value);
723 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300724
Mark Shannonae3087c2017-10-22 22:41:51 +0100725 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200726 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100727 fprintf(stderr,
728 "PyThreadState_Clear: warning: thread still has a generator\n");
729 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 tstate->c_profilefunc = NULL;
732 tstate->c_tracefunc = NULL;
733 Py_CLEAR(tstate->c_profileobj);
734 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400735
736 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700737 Py_CLEAR(tstate->async_gen_firstiter);
738 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500739
740 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000741}
742
743
Guido van Rossum29757862001-01-23 01:46:06 +0000744/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
745static void
746tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000747{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 if (tstate == NULL)
750 Py_FatalError("PyThreadState_Delete: NULL tstate");
751 interp = tstate->interp;
752 if (interp == NULL)
753 Py_FatalError("PyThreadState_Delete: NULL interp");
754 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200755 if (tstate->prev)
756 tstate->prev->next = tstate->next;
757 else
758 interp->tstate_head = tstate->next;
759 if (tstate->next)
760 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200762 if (tstate->on_delete != NULL) {
763 tstate->on_delete(tstate->on_delete_data);
764 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200765 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000766}
767
768
Guido van Rossum29757862001-01-23 01:46:06 +0000769void
770PyThreadState_Delete(PyThreadState *tstate)
771{
Victor Stinner50b48572018-11-01 01:51:40 +0100772 if (tstate == _PyThreadState_GET())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600774 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900775 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600776 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900777 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600778 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200779 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000780}
781
782
Guido van Rossum29757862001-01-23 01:46:06 +0000783void
784PyThreadState_DeleteCurrent()
785{
Victor Stinner50b48572018-11-01 01:51:40 +0100786 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 if (tstate == NULL)
788 Py_FatalError(
789 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100790 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600791 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900792 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600793 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900794 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600795 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100796 _PyThreadState_SET(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000798}
Guido van Rossum29757862001-01-23 01:46:06 +0000799
800
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200801/*
802 * Delete all thread states except the one passed as argument.
803 * Note that, if there is a current thread state, it *must* be the one
804 * passed as argument. Also, this won't touch any other interpreters
805 * than the current one, since we don't know which thread state should
806 * be kept in those other interpreteres.
807 */
808void
809_PyThreadState_DeleteExcept(PyThreadState *tstate)
810{
811 PyInterpreterState *interp = tstate->interp;
812 PyThreadState *p, *next, *garbage;
813 HEAD_LOCK();
814 /* Remove all thread states, except tstate, from the linked list of
815 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200816 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200817 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200818 if (garbage == tstate)
819 garbage = tstate->next;
820 if (tstate->prev)
821 tstate->prev->next = tstate->next;
822 if (tstate->next)
823 tstate->next->prev = tstate->prev;
824 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200825 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200826 HEAD_UNLOCK();
827 /* Clear and deallocate all stale thread states. Even if this
828 executes Python code, we should be safe since it executes
829 in the current thread, not one of the stale threads. */
830 for (p = garbage; p; p = next) {
831 next = p->next;
832 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200833 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200834 }
835}
836
837
Guido van Rossuma027efa1997-05-05 20:56:21 +0000838PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100839_PyThreadState_UncheckedGet(void)
840{
Victor Stinner50b48572018-11-01 01:51:40 +0100841 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100842}
843
844
845PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000846PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000847{
Victor Stinner50b48572018-11-01 01:51:40 +0100848 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 if (tstate == NULL)
850 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000851
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000852 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000853}
854
855
856PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000857PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000858{
Victor Stinner50b48572018-11-01 01:51:40 +0100859 PyThreadState *oldts = _PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000860
Victor Stinner9204fb82018-10-30 15:13:17 +0100861 _PyThreadState_SET(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 /* It should not be possible for more than one thread state
863 to be used for a thread. Check this the best we can in debug
864 builds.
865 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200866#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 if (newts) {
868 /* This can be called from PyEval_RestoreThread(). Similar
869 to it, we need to ensure errno doesn't change.
870 */
871 int err = errno;
872 PyThreadState *check = PyGILState_GetThisThreadState();
873 if (check && check->interp == newts->interp && check != newts)
874 Py_FatalError("Invalid thread state for this thread");
875 errno = err;
876 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000877#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000879}
Guido van Rossumede04391998-04-10 20:18:25 +0000880
881/* An extension mechanism to store arbitrary additional per-thread state.
882 PyThreadState_GetDict() returns a dictionary that can be used to hold such
883 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000884 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
885 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000886
887PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000888PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000889{
Victor Stinner50b48572018-11-01 01:51:40 +0100890 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 if (tstate == NULL)
892 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 if (tstate->dict == NULL) {
895 PyObject *d;
896 tstate->dict = d = PyDict_New();
897 if (d == NULL)
898 PyErr_Clear();
899 }
900 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000901}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000902
903
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000904/* Asynchronously raise an exception in a thread.
905 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000906 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000907 to call this, or use ctypes. Must be called with the GIL held.
908 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
909 match any known thread id). Can be called with exc=NULL to clear an
910 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000911
912int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200913PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
914{
Victor Stinner9204fb82018-10-30 15:13:17 +0100915 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 /* Although the GIL is held, a few C API functions can be called
919 * without the GIL held, and in particular some that create and
920 * destroy thread and interpreter states. Those can mutate the
921 * list of thread states we're traversing, so to prevent that we lock
922 * head_mutex for the duration.
923 */
924 HEAD_LOCK();
925 for (p = interp->tstate_head; p != NULL; p = p->next) {
926 if (p->thread_id == id) {
927 /* Tricky: we need to decref the current value
928 * (if any) in p->async_exc, but that can in turn
929 * allow arbitrary Python code to run, including
930 * perhaps calls to this function. To prevent
931 * deadlock, we need to release head_mutex before
932 * the decref.
933 */
934 PyObject *old_exc = p->async_exc;
935 Py_XINCREF(exc);
936 p->async_exc = exc;
937 HEAD_UNLOCK();
938 Py_XDECREF(old_exc);
Victor Stinner4d61e6e2019-03-04 14:21:28 +0100939 _PyEval_SignalAsyncExc();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 return 1;
941 }
942 }
943 HEAD_UNLOCK();
944 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000945}
946
947
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000948/* Routines for advanced debuggers, requested by David Beazley.
949 Don't use unless you know what you are doing! */
950
951PyInterpreterState *
952PyInterpreterState_Head(void)
953{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600954 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000955}
956
957PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700958PyInterpreterState_Main(void)
959{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600960 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700961}
962
963PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000964PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000966}
967
968PyThreadState *
969PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000971}
972
973PyThreadState *
974PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000976}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000977
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000978/* The implementation of sys._current_frames(). This is intended to be
979 called with the GIL held, as it will be when called via
980 sys._current_frames(). It's possible it would work fine even without
981 the GIL held, but haven't thought enough about that.
982*/
983PyObject *
984_PyThread_CurrentFrames(void)
985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 PyObject *result;
987 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 result = PyDict_New();
990 if (result == NULL)
991 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 /* for i in all interpreters:
994 * for t in all of i's thread states:
995 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200996 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 * need to grab head_mutex for the duration.
998 */
999 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001000 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 PyThreadState *t;
1002 for (t = i->tstate_head; t != NULL; t = t->next) {
1003 PyObject *id;
1004 int stat;
1005 struct _frame *frame = t->frame;
1006 if (frame == NULL)
1007 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02001008 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (id == NULL)
1010 goto Fail;
1011 stat = PyDict_SetItem(result, id, (PyObject *)frame);
1012 Py_DECREF(id);
1013 if (stat < 0)
1014 goto Fail;
1015 }
1016 }
1017 HEAD_UNLOCK();
1018 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001019
1020 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 HEAD_UNLOCK();
1022 Py_DECREF(result);
1023 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001024}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +00001025
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001026/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001027
1028/* Keep this as a static, as it is not reliable! It can only
1029 ever be compared to the state for the *current* thread.
1030 * If not equal, then it doesn't matter that the actual
1031 value may change immediately after comparison, as it can't
1032 possibly change to the current thread's state.
1033 * If equal, then the current thread holds the lock, so the value can't
1034 change until we yield the lock.
1035*/
1036static int
1037PyThreadState_IsCurrent(PyThreadState *tstate)
1038{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 /* Must be the tstate for this thread */
1040 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinner50b48572018-11-01 01:51:40 +01001041 return tstate == _PyThreadState_GET();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001042}
1043
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001044/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001045 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001046*/
Tim Peters19717fa2004-10-09 17:38:29 +00001047void
1048_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001049{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001051 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1052 Py_FatalError("Could not allocate TSS entry");
1053 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001054 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001055 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001059}
1060
Victor Stinner861d9ab2016-03-16 22:45:24 +01001061PyInterpreterState *
1062_PyGILState_GetInterpreterStateUnsafe(void)
1063{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001064 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001065}
1066
Tim Peters19717fa2004-10-09 17:38:29 +00001067void
1068_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001069{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001070 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001071 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001072}
1073
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001074/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001075 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001076 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001077 */
1078void
1079_PyGILState_Reinit(void)
1080{
Victor Stinner5d926472018-03-06 14:31:37 +01001081 /* Force default allocator, since _PyRuntimeState_Fini() must
1082 use the same allocator than this function. */
1083 PyMemAllocatorEx old_alloc;
1084 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1085
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001086 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +01001087
1088 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1089
1090 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001091 Py_FatalError("Can't initialize threads for interpreter");
Victor Stinner5d926472018-03-06 14:31:37 +01001092 }
1093
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001094 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001095 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
1096 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1097 Py_FatalError("Could not allocate TSS entry");
1098 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001099
Charles-François Natalia233df82011-11-22 19:49:51 +01001100 /* If the thread had an associated auto thread state, reassociate it with
1101 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001102 if (tstate &&
1103 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
1104 {
1105 Py_FatalError("Couldn't create autoTSSkey mapping");
1106 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001107}
1108
Michael W. Hudson188d4362005-06-20 16:52:57 +00001109/* When a thread state is created for a thread by some mechanism other than
1110 PyGILState_Ensure, it's important that the GILState machinery knows about
1111 it so it doesn't try to create another thread state for the thread (this is
1112 a better fix for SF bug #1010677 than the first one attempted).
1113*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001114static void
Michael W. Hudson188d4362005-06-20 16:52:57 +00001115_PyGILState_NoteThreadState(PyThreadState* tstate)
1116{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001117 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001118 threadstate created in Py_Initialize(). Don't do anything for now
1119 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001120 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001122
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001123 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 The only situation where you can legitimately have more than one
1126 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001127 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001128
Victor Stinner590cebe2013-12-13 11:08:56 +01001129 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1130 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001131
Victor Stinner590cebe2013-12-13 11:08:56 +01001132 The first thread state created for that given OS level thread will
1133 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001135 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
1136 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1137 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001138 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001139 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001140 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001141 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 /* PyGILState_Release must not try to delete this thread state. */
1144 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001145}
1146
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001147/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001148PyThreadState *
1149PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001150{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001151 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001153 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001154}
1155
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001156int
1157PyGILState_Check(void)
1158{
Victor Stinner8a1be612016-03-14 22:07:55 +01001159 PyThreadState *tstate;
1160
1161 if (!_PyGILState_check_enabled)
1162 return 1;
1163
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001164 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001165 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001166 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001167
Victor Stinner50b48572018-11-01 01:51:40 +01001168 tstate = _PyThreadState_GET();
Victor Stinner8a1be612016-03-14 22:07:55 +01001169 if (tstate == NULL)
1170 return 0;
1171
1172 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001173}
1174
Tim Peters19717fa2004-10-09 17:38:29 +00001175PyGILState_STATE
1176PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 int current;
1179 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001180 int need_init_threads = 0;
1181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 /* Note that we do not auto-init Python here - apart from
1183 potential races with 2 threads auto-initializing, pep-311
1184 spells out other issues. Embedders are expected to have
1185 called Py_Initialize() and usually PyEval_InitThreads().
1186 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001187 /* Py_Initialize() hasn't been called! */
1188 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001189
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001190 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001192 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001195 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (tcur == NULL)
1197 Py_FatalError("Couldn't create thread-state for new thread");
1198 /* This is our thread state! We'll need to delete it in the
1199 matching call to PyGILState_Release(). */
1200 tcur->gilstate_counter = 0;
1201 current = 0; /* new thread state is never current */
1202 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001203 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001205 }
1206
1207 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001209 }
1210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 /* Update our counter in the thread-state - no need for locks:
1212 - tcur will remain valid as we hold the GIL.
1213 - the counter is safe as we are the only thread "allowed"
1214 to modify this value
1215 */
1216 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001217
1218 if (need_init_threads) {
1219 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1220 called from a new thread for the first time, we need the create the
1221 GIL. */
1222 PyEval_InitThreads();
1223 }
1224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001226}
1227
Tim Peters19717fa2004-10-09 17:38:29 +00001228void
1229PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001230{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001231 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1232 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (tcur == NULL)
1234 Py_FatalError("auto-releasing thread-state, "
1235 "but no thread-state for this thread");
1236 /* We must hold the GIL and have our thread state current */
1237 /* XXX - remove the check - the assert should be fine,
1238 but while this is very new (April 2003), the extra check
1239 by release-only users can't hurt.
1240 */
1241 if (! PyThreadState_IsCurrent(tcur))
1242 Py_FatalError("This thread state must be current when releasing");
1243 assert(PyThreadState_IsCurrent(tcur));
1244 --tcur->gilstate_counter;
1245 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 /* If we're going to destroy this thread-state, we must
1248 * clear it while the GIL is held, as destructors may run.
1249 */
1250 if (tcur->gilstate_counter == 0) {
1251 /* can't have been locked when we created it */
1252 assert(oldstate == PyGILState_UNLOCKED);
1253 PyThreadState_Clear(tcur);
1254 /* Delete the thread-state. Note this releases the GIL too!
1255 * It's vital that the GIL be held here, to avoid shutdown
1256 * races; see bugs 225673 and 1061968 (that nasty bug has a
1257 * habit of coming back).
1258 */
1259 PyThreadState_DeleteCurrent();
1260 }
1261 /* Release the lock if necessary */
1262 else if (oldstate == PyGILState_UNLOCKED)
1263 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001264}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001265
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001266
Eric Snow7f8bfc92018-01-29 18:23:44 -07001267/**************************/
1268/* cross-interpreter data */
1269/**************************/
1270
1271/* cross-interpreter data */
1272
1273crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1274
1275/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1276 to keep the registry code separate. */
1277static crossinterpdatafunc
1278_lookup_getdata(PyObject *obj)
1279{
1280 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1281 if (getdata == NULL && PyErr_Occurred() == 0)
1282 PyErr_Format(PyExc_ValueError,
1283 "%S does not support cross-interpreter data", obj);
1284 return getdata;
1285}
1286
1287int
1288_PyObject_CheckCrossInterpreterData(PyObject *obj)
1289{
1290 crossinterpdatafunc getdata = _lookup_getdata(obj);
1291 if (getdata == NULL) {
1292 return -1;
1293 }
1294 return 0;
1295}
1296
1297static int
1298_check_xidata(_PyCrossInterpreterData *data)
1299{
1300 // data->data can be anything, including NULL, so we don't check it.
1301
1302 // data->obj may be NULL, so we don't check it.
1303
1304 if (data->interp < 0) {
1305 PyErr_SetString(PyExc_SystemError, "missing interp");
1306 return -1;
1307 }
1308
1309 if (data->new_object == NULL) {
1310 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1311 return -1;
1312 }
1313
1314 // data->free may be NULL, so we don't check it.
1315
1316 return 0;
1317}
1318
1319int
1320_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1321{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001322 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001323 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001324 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001325
1326 // Reset data before re-populating.
1327 *data = (_PyCrossInterpreterData){0};
1328 data->free = PyMem_RawFree; // Set a default that may be overridden.
1329
1330 // Call the "getdata" func for the object.
1331 Py_INCREF(obj);
1332 crossinterpdatafunc getdata = _lookup_getdata(obj);
1333 if (getdata == NULL) {
1334 Py_DECREF(obj);
1335 return -1;
1336 }
1337 int res = getdata(obj, data);
1338 Py_DECREF(obj);
1339 if (res != 0) {
1340 return -1;
1341 }
1342
1343 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001344 data->interp = interp->id;
1345 if (_check_xidata(data) != 0) {
1346 _PyCrossInterpreterData_Release(data);
1347 return -1;
1348 }
1349
1350 return 0;
1351}
1352
Victor Stinner4d61e6e2019-03-04 14:21:28 +01001353static void
Eric Snow63799132018-06-01 18:45:20 -06001354_release_xidata(void *arg)
1355{
1356 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1357 if (data->free != NULL) {
1358 data->free(data->data);
1359 }
1360 Py_XDECREF(data->obj);
Victor Stinner4d61e6e2019-03-04 14:21:28 +01001361}
1362
1363static void
1364_call_in_interpreter(PyInterpreterState *interp,
1365 void (*func)(void *), void *arg)
1366{
1367 /* We would use Py_AddPendingCall() if it weren't specific to the
1368 * main interpreter (see bpo-33608). In the meantime we take a
1369 * naive approach.
1370 */
1371 PyThreadState *save_tstate = NULL;
1372 if (interp != _PyInterpreterState_Get()) {
1373 // XXX Using the "head" thread isn't strictly correct.
1374 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1375 // XXX Possible GILState issues?
1376 save_tstate = PyThreadState_Swap(tstate);
1377 }
1378
1379 func(arg);
1380
1381 // Switch back.
1382 if (save_tstate != NULL) {
1383 PyThreadState_Swap(save_tstate);
1384 }
Eric Snow63799132018-06-01 18:45:20 -06001385}
1386
Eric Snow7f8bfc92018-01-29 18:23:44 -07001387void
1388_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1389{
1390 if (data->data == NULL && data->obj == NULL) {
1391 // Nothing to release!
1392 return;
1393 }
1394
Victor Stinner4d61e6e2019-03-04 14:21:28 +01001395 // Switch to the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001396 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1397 if (interp == NULL) {
1398 // The intepreter was already destroyed.
1399 if (data->free != NULL) {
1400 // XXX Someone leaked some memory...
1401 }
1402 return;
1403 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001404
Eric Snow7f8bfc92018-01-29 18:23:44 -07001405 // "Release" the data and/or the object.
Victor Stinner4d61e6e2019-03-04 14:21:28 +01001406 _call_in_interpreter(interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001407}
1408
1409PyObject *
1410_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1411{
1412 return data->new_object(data);
1413}
1414
1415/* registry of {type -> crossinterpdatafunc} */
1416
1417/* For now we use a global registry of shareable classes. An
1418 alternative would be to add a tp_* slot for a class's
1419 crossinterpdatafunc. It would be simpler and more efficient. */
1420
1421static int
1422_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1423{
1424 // Note that we effectively replace already registered classes
1425 // rather than failing.
1426 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1427 if (newhead == NULL)
1428 return -1;
1429 newhead->cls = cls;
1430 newhead->getdata = getdata;
1431 newhead->next = _PyRuntime.xidregistry.head;
1432 _PyRuntime.xidregistry.head = newhead;
1433 return 0;
1434}
1435
1436static void _register_builtins_for_crossinterpreter_data(void);
1437
1438int
Eric Snowc11183c2019-03-15 16:35:46 -06001439_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001440 crossinterpdatafunc getdata)
1441{
1442 if (!PyType_Check(cls)) {
1443 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1444 return -1;
1445 }
1446 if (getdata == NULL) {
1447 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1448 return -1;
1449 }
1450
1451 // Make sure the class isn't ever deallocated.
1452 Py_INCREF((PyObject *)cls);
1453
1454 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1455 if (_PyRuntime.xidregistry.head == NULL) {
1456 _register_builtins_for_crossinterpreter_data();
1457 }
1458 int res = _register_xidata(cls, getdata);
1459 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1460 return res;
1461}
1462
Eric Snow6d2cd902018-05-16 15:04:57 -04001463/* Cross-interpreter objects are looked up by exact match on the class.
1464 We can reassess this policy when we move from a global registry to a
1465 tp_* slot. */
1466
Eric Snow7f8bfc92018-01-29 18:23:44 -07001467crossinterpdatafunc
1468_PyCrossInterpreterData_Lookup(PyObject *obj)
1469{
1470 PyObject *cls = PyObject_Type(obj);
1471 crossinterpdatafunc getdata = NULL;
1472 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1473 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1474 if (cur == NULL) {
1475 _register_builtins_for_crossinterpreter_data();
1476 cur = _PyRuntime.xidregistry.head;
1477 }
1478 for(; cur != NULL; cur = cur->next) {
1479 if (cur->cls == (PyTypeObject *)cls) {
1480 getdata = cur->getdata;
1481 break;
1482 }
1483 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001484 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001485 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1486 return getdata;
1487}
1488
1489/* cross-interpreter data for builtin types */
1490
Eric Snow6d2cd902018-05-16 15:04:57 -04001491struct _shared_bytes_data {
1492 char *bytes;
1493 Py_ssize_t len;
1494};
1495
Eric Snow7f8bfc92018-01-29 18:23:44 -07001496static PyObject *
1497_new_bytes_object(_PyCrossInterpreterData *data)
1498{
Eric Snow6d2cd902018-05-16 15:04:57 -04001499 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1500 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001501}
1502
1503static int
1504_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1505{
Eric Snow6d2cd902018-05-16 15:04:57 -04001506 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1507 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1508 return -1;
1509 }
1510 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001511 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001512 data->obj = obj; // Will be "released" (decref'ed) when data released.
1513 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001514 data->free = PyMem_Free;
1515 return 0;
1516}
1517
1518struct _shared_str_data {
1519 int kind;
1520 const void *buffer;
1521 Py_ssize_t len;
1522};
1523
1524static PyObject *
1525_new_str_object(_PyCrossInterpreterData *data)
1526{
1527 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1528 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1529}
1530
1531static int
1532_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1533{
1534 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1535 shared->kind = PyUnicode_KIND(obj);
1536 shared->buffer = PyUnicode_DATA(obj);
1537 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1538 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001539 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001540 data->obj = obj; // Will be "released" (decref'ed) when data released.
1541 data->new_object = _new_str_object;
1542 data->free = PyMem_Free;
1543 return 0;
1544}
1545
1546static PyObject *
1547_new_long_object(_PyCrossInterpreterData *data)
1548{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001549 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001550}
1551
1552static int
1553_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1554{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001555 /* Note that this means the size of shareable ints is bounded by
1556 * sys.maxsize. Hence on 32-bit architectures that is half the
1557 * size of maximum shareable ints on 64-bit.
1558 */
1559 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001560 if (value == -1 && PyErr_Occurred()) {
1561 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1562 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1563 }
1564 return -1;
1565 }
1566 data->data = (void *)value;
1567 data->obj = NULL;
1568 data->new_object = _new_long_object;
1569 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001570 return 0;
1571}
1572
1573static PyObject *
1574_new_none_object(_PyCrossInterpreterData *data)
1575{
1576 // XXX Singleton refcounts are problematic across interpreters...
1577 Py_INCREF(Py_None);
1578 return Py_None;
1579}
1580
1581static int
1582_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1583{
1584 data->data = NULL;
1585 // data->obj remains NULL
1586 data->new_object = _new_none_object;
1587 data->free = NULL; // There is nothing to free.
1588 return 0;
1589}
1590
1591static void
1592_register_builtins_for_crossinterpreter_data(void)
1593{
1594 // None
1595 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1596 Py_FatalError("could not register None for cross-interpreter sharing");
1597 }
1598
Eric Snow6d2cd902018-05-16 15:04:57 -04001599 // int
1600 if (_register_xidata(&PyLong_Type, _long_shared) != 0) {
1601 Py_FatalError("could not register int for cross-interpreter sharing");
1602 }
1603
Eric Snow7f8bfc92018-01-29 18:23:44 -07001604 // bytes
1605 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1606 Py_FatalError("could not register bytes for cross-interpreter sharing");
1607 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001608
1609 // str
1610 if (_register_xidata(&PyUnicode_Type, _str_shared) != 0) {
1611 Py_FatalError("could not register str for cross-interpreter sharing");
1612 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001613}
1614
1615
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001616#ifdef __cplusplus
1617}
1618#endif