blob: 99a01efa6c72ed70d91145ee5c9da24ac0a5bbf8 [file] [log] [blame]
Guido van Rossuma027efa1997-05-05 20:56:21 +00001
2/* Thread and interpreter state structures and their interfaces */
3
4#include "Python.h"
Victor Stinnerf684d832019-03-01 03:44:13 +01005#include "pycore_coreconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +01006#include "pycore_pymem.h"
7#include "pycore_pystate.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +00008
Victor Stinner9204fb82018-10-30 15:13:17 +01009#define _PyThreadState_SET(value) \
10 _Py_atomic_store_relaxed(&_PyRuntime.gilstate.tstate_current, \
11 (uintptr_t)(value))
Victor Stinnerb02ef712016-01-22 14:09:55 +010012
Victor Stinnerbfd316e2016-01-20 11:12:38 +010013
Tim Peters84705582004-10-10 02:47:33 +000014/* --------------------------------------------------------------------------
15CAUTION
16
Victor Stinner1a7425f2013-07-07 16:25:15 +020017Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
18number of these functions are advertised as safe to call when the GIL isn't
19held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
20debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
21to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000022-------------------------------------------------------------------------- */
23
Martin v. Löwisf0473d52001-07-18 16:17:16 +000024#ifdef HAVE_DLOPEN
25#ifdef HAVE_DLFCN_H
26#include <dlfcn.h>
27#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030028#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000029#define RTLD_LAZY 1
30#endif
31#endif
32
Benjamin Peterson43162b82012-04-13 11:58:27 -040033#ifdef __cplusplus
34extern "C" {
35#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000036
Victor Stinner5d39e042017-11-29 17:20:38 +010037static _PyInitError
38_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060039{
40 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010041
Eric Snow2ebc5ce2017-09-07 23:51:28 -060042 _PyGC_Initialize(&runtime->gc);
43 _PyEval_Initialize(&runtime->ceval);
Michael W. Hudson188d4362005-06-20 16:52:57 +000044
Eric Snow2ebc5ce2017-09-07 23:51:28 -060045 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080046
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090047 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
48 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080049 Py_tss_t initial = Py_tss_NEEDS_INIT;
50 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000051
Eric Snow2ebc5ce2017-09-07 23:51:28 -060052 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080053 if (runtime->interpreters.mutex == NULL) {
54 return _Py_INIT_ERR("Can't initialize threads for interpreter");
55 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060056 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070057
58 runtime->xidregistry.mutex = PyThread_allocate_lock();
59 if (runtime->xidregistry.mutex == NULL) {
60 return _Py_INIT_ERR("Can't initialize threads for cross-interpreter data registry");
61 }
62
Victor Stinnerf7e5b562017-11-15 15:48:08 -080063 return _Py_INIT_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060064}
Eric Snow05351c12017-09-05 21:43:08 -070065
Victor Stinner5d39e042017-11-29 17:20:38 +010066_PyInitError
67_PyRuntimeState_Init(_PyRuntimeState *runtime)
68{
69 /* Force default allocator, since _PyRuntimeState_Fini() must
70 use the same allocator than this function. */
71 PyMemAllocatorEx old_alloc;
72 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
73
74 _PyInitError err = _PyRuntimeState_Init_impl(runtime);
75
76 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
77 return err;
78}
79
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080void
81_PyRuntimeState_Fini(_PyRuntimeState *runtime)
82{
Victor Stinner5d39e042017-11-29 17:20:38 +010083 /* Force the allocator used by _PyRuntimeState_Init(). */
84 PyMemAllocatorEx old_alloc;
85 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -080086
Eric Snow2ebc5ce2017-09-07 23:51:28 -060087 if (runtime->interpreters.mutex != NULL) {
88 PyThread_free_lock(runtime->interpreters.mutex);
89 runtime->interpreters.mutex = NULL;
90 }
Victor Stinnerccb04422017-11-16 03:20:31 -080091
92 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060093}
94
95#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
96 WAIT_LOCK)
97#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -070098
Michael W. Hudson188d4362005-06-20 16:52:57 +000099static void _PyGILState_NoteThreadState(PyThreadState* tstate);
100
Victor Stinnera7368ac2017-11-15 18:11:45 -0800101_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600102_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700103{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600104 runtime->interpreters.next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100105
106 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
107 Create a new mutex if needed. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600108 if (runtime->interpreters.mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100109 /* Force default allocator, since _PyRuntimeState_Fini() must
110 use the same allocator than this function. */
111 PyMemAllocatorEx old_alloc;
112 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
113
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600114 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100115
116 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
117
Victor Stinnera7368ac2017-11-15 18:11:45 -0800118 if (runtime->interpreters.mutex == NULL) {
119 return _Py_INIT_ERR("Can't initialize threads for interpreter");
120 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600121 }
Victor Stinner5d926472018-03-06 14:31:37 +0100122
Victor Stinnera7368ac2017-11-15 18:11:45 -0800123 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700124}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000125
126PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000127PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200130 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000131
Victor Stinnerd4341102017-11-23 00:12:09 +0100132 if (interp == NULL) {
133 return NULL;
134 }
135
Eric Snowef4ac962019-02-24 15:40:47 -0800136 memset(interp, 0, sizeof(*interp));
Eric Snow4c6955e2018-02-16 18:53:40 -0700137 interp->id_refcount = -1;
Victor Stinnerd4341102017-11-23 00:12:09 +0100138 interp->check_interval = 100;
Eric Snowef4ac962019-02-24 15:40:47 -0800139
140 interp->ceval.pending.lock = PyThread_allocate_lock();
141 if (interp->ceval.pending.lock == NULL) {
142 PyErr_SetString(PyExc_RuntimeError,
143 "failed to create interpreter ceval pending mutex");
144 return NULL;
145 }
Victor Stinnerd4341102017-11-23 00:12:09 +0100146 interp->core_config = _PyCoreConfig_INIT;
147 interp->config = _PyMainInterpreterConfig_INIT;
Victor Stinnerd4341102017-11-23 00:12:09 +0100148 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000149#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300150#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100151 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000152#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100153 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000154#endif
155#endif
Eric Snowef4ac962019-02-24 15:40:47 -0800156
157 if (_PyRuntime.main_thread == 0) {
158 _PyRuntime.main_thread = PyThread_get_thread_ident();
159 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000160
Victor Stinnerd4341102017-11-23 00:12:09 +0100161 HEAD_LOCK();
Victor Stinnerd4341102017-11-23 00:12:09 +0100162 if (_PyRuntime.interpreters.next_id < 0) {
163 /* overflow or Py_Initialize() not called! */
164 PyErr_SetString(PyExc_RuntimeError,
165 "failed to get an interpreter ID");
Pablo Galindo95d630e2018-08-31 22:49:29 +0100166 PyMem_RawFree(interp);
Victor Stinnerd4341102017-11-23 00:12:09 +0100167 interp = NULL;
168 } else {
169 interp->id = _PyRuntime.interpreters.next_id;
170 _PyRuntime.interpreters.next_id += 1;
Pablo Galindo95d630e2018-08-31 22:49:29 +0100171 interp->next = _PyRuntime.interpreters.head;
172 if (_PyRuntime.interpreters.main == NULL) {
173 _PyRuntime.interpreters.main = interp;
174 }
175 _PyRuntime.interpreters.head = interp;
Victor Stinnerd4341102017-11-23 00:12:09 +0100176 }
177 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000178
Pablo Galindo95d630e2018-08-31 22:49:29 +0100179 if (interp == NULL) {
180 return NULL;
181 }
182
Yury Selivanovf23746a2018-01-22 19:11:18 -0500183 interp->tstate_next_unique_id = 0;
184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000186}
187
188
189void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000190PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 PyThreadState *p;
193 HEAD_LOCK();
194 for (p = interp->tstate_head; p != NULL; p = p->next)
195 PyThreadState_Clear(p);
196 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100197 _PyCoreConfig_Clear(&interp->core_config);
198 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 Py_CLEAR(interp->codec_search_path);
200 Py_CLEAR(interp->codec_search_cache);
201 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700202 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 Py_CLEAR(interp->sysdict);
205 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200206 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400207 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300208 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200209#ifdef HAVE_FORK
210 Py_CLEAR(interp->before_forkers);
211 Py_CLEAR(interp->after_forkers_parent);
212 Py_CLEAR(interp->after_forkers_child);
213#endif
Eric Snowef4ac962019-02-24 15:40:47 -0800214 // XXX Once we have one allocator per interpreter (i.e.
215 // per-interpreter GC) we must ensure that all of the interpreter's
216 // objects have been cleaned up at the point.
Guido van Rossum25ce5661997-08-02 03:10:38 +0000217}
218
219
220static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000221zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 PyThreadState *p;
224 /* No need to lock the mutex here because this should only happen
225 when the threads are all really dead (XXX famous last words). */
226 while ((p = interp->tstate_head) != NULL) {
227 PyThreadState_Delete(p);
228 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000229}
230
231
232void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000233PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 PyInterpreterState **p;
236 zapthreads(interp);
237 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600238 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 if (*p == NULL)
240 Py_FatalError(
241 "PyInterpreterState_Delete: invalid interp");
242 if (*p == interp)
243 break;
244 }
245 if (interp->tstate_head != NULL)
246 Py_FatalError("PyInterpreterState_Delete: remaining threads");
247 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600248 if (_PyRuntime.interpreters.main == interp) {
249 _PyRuntime.interpreters.main = NULL;
250 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700251 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
252 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 HEAD_UNLOCK();
Eric Snow4c6955e2018-02-16 18:53:40 -0700254 if (interp->id_mutex != NULL) {
255 PyThread_free_lock(interp->id_mutex);
256 }
Eric Snowef4ac962019-02-24 15:40:47 -0800257 if (interp->ceval.pending.lock != NULL) {
258 PyThread_free_lock(interp->ceval.pending.lock);
259 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200260 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000261}
262
263
Eric Snow59032962018-09-14 14:17:20 -0700264/*
265 * Delete all interpreter states except the main interpreter. If there
266 * is a current interpreter state, it *must* be the main interpreter.
267 */
268void
269_PyInterpreterState_DeleteExceptMain()
270{
271 PyThreadState *tstate = PyThreadState_Swap(NULL);
272 if (tstate != NULL && tstate->interp != _PyRuntime.interpreters.main) {
273 Py_FatalError("PyInterpreterState_DeleteExceptMain: not main interpreter");
274 }
275
276 HEAD_LOCK();
277 PyInterpreterState *interp = _PyRuntime.interpreters.head;
278 _PyRuntime.interpreters.head = NULL;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100279 while (interp != NULL) {
Eric Snow59032962018-09-14 14:17:20 -0700280 if (interp == _PyRuntime.interpreters.main) {
281 _PyRuntime.interpreters.main->next = NULL;
282 _PyRuntime.interpreters.head = interp;
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100283 interp = interp->next;
Eric Snow59032962018-09-14 14:17:20 -0700284 continue;
285 }
286
287 PyInterpreterState_Clear(interp); // XXX must activate?
288 zapthreads(interp);
289 if (interp->id_mutex != NULL) {
290 PyThread_free_lock(interp->id_mutex);
291 }
Stéphane Wirtelb5409da2019-02-20 15:27:22 +0100292 PyInterpreterState *prev_interp = interp;
293 interp = interp->next;
294 PyMem_RawFree(prev_interp);
Eric Snow59032962018-09-14 14:17:20 -0700295 }
296 HEAD_UNLOCK();
297
298 if (_PyRuntime.interpreters.head == NULL) {
299 Py_FatalError("PyInterpreterState_DeleteExceptMain: missing main");
300 }
301 PyThreadState_Swap(tstate);
302}
303
304
Victor Stinnercaba55b2018-08-03 15:33:52 +0200305PyInterpreterState *
306_PyInterpreterState_Get(void)
307{
Victor Stinner50b48572018-11-01 01:51:40 +0100308 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinnercaba55b2018-08-03 15:33:52 +0200309 if (tstate == NULL) {
310 Py_FatalError("_PyInterpreterState_Get(): no current thread state");
311 }
312 PyInterpreterState *interp = tstate->interp;
313 if (interp == NULL) {
314 Py_FatalError("_PyInterpreterState_Get(): no current interpreter");
315 }
316 return interp;
317}
318
319
Eric Snowe3774162017-05-22 19:46:40 -0700320int64_t
321PyInterpreterState_GetID(PyInterpreterState *interp)
322{
323 if (interp == NULL) {
324 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
325 return -1;
326 }
327 return interp->id;
328}
329
330
Eric Snowb05b7112019-03-01 12:35:10 -0700331static PyInterpreterState *
332interp_look_up_id(PY_INT64_T requested_id)
Eric Snow7f8bfc92018-01-29 18:23:44 -0700333{
Eric Snow7f8bfc92018-01-29 18:23:44 -0700334 PyInterpreterState *interp = PyInterpreterState_Head();
335 while (interp != NULL) {
336 PY_INT64_T id = PyInterpreterState_GetID(interp);
Eric Snowb05b7112019-03-01 12:35:10 -0700337 if (id < 0) {
Eric Snow7f8bfc92018-01-29 18:23:44 -0700338 return NULL;
Eric Snowb05b7112019-03-01 12:35:10 -0700339 }
340 if (requested_id == id) {
Eric Snow7f8bfc92018-01-29 18:23:44 -0700341 return interp;
Eric Snowb05b7112019-03-01 12:35:10 -0700342 }
Eric Snow7f8bfc92018-01-29 18:23:44 -0700343 interp = PyInterpreterState_Next(interp);
344 }
Eric Snow7f8bfc92018-01-29 18:23:44 -0700345 return NULL;
346}
347
Eric Snowb05b7112019-03-01 12:35:10 -0700348PyInterpreterState *
349_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
350{
351 PyInterpreterState *interp = NULL;
352 if (requested_id >= 0) {
353 HEAD_UNLOCK();
354 interp = interp_look_up_id(requested_id);
355 HEAD_UNLOCK();
356 }
357 if (interp == NULL && !PyErr_Occurred()) {
358 PyErr_Format(PyExc_RuntimeError,
359 "unrecognized interpreter ID %lld", requested_id);
360 }
361 return interp;
362}
363
Eric Snow4c6955e2018-02-16 18:53:40 -0700364
365int
366_PyInterpreterState_IDInitref(PyInterpreterState *interp)
367{
368 if (interp->id_mutex != NULL) {
369 return 0;
370 }
371 interp->id_mutex = PyThread_allocate_lock();
372 if (interp->id_mutex == NULL) {
373 PyErr_SetString(PyExc_RuntimeError,
374 "failed to create init interpreter ID mutex");
375 return -1;
376 }
377 interp->id_refcount = 0;
378 return 0;
379}
380
381
382void
383_PyInterpreterState_IDIncref(PyInterpreterState *interp)
384{
385 if (interp->id_mutex == NULL) {
386 return;
387 }
388 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
389 interp->id_refcount += 1;
390 PyThread_release_lock(interp->id_mutex);
391}
392
393
394void
395_PyInterpreterState_IDDecref(PyInterpreterState *interp)
396{
397 if (interp->id_mutex == NULL) {
398 return;
399 }
400 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
401 assert(interp->id_refcount != 0);
402 interp->id_refcount -= 1;
403 int64_t refcount = interp->id_refcount;
404 PyThread_release_lock(interp->id_mutex);
405
Eric Snowbcfa4502019-03-01 16:50:31 -0700406 if (refcount == 0 && interp->requires_idref) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700407 // XXX Using the "head" thread isn't strictly correct.
408 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
409 // XXX Possible GILState issues?
410 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700411 Py_EndInterpreter(tstate);
412 PyThreadState_Swap(save_tstate);
413 }
414}
415
Eric Snowbcfa4502019-03-01 16:50:31 -0700416int
417_PyInterpreterState_RequiresIDRef(PyInterpreterState *interp)
418{
419 return interp->requires_idref;
420}
421
422void
423_PyInterpreterState_RequireIDRef(PyInterpreterState *interp, int required)
424{
425 interp->requires_idref = required ? 1 : 0;
426}
427
Eric Snowbe3b2952019-02-23 11:35:52 -0700428_PyCoreConfig *
429_PyInterpreterState_GetCoreConfig(PyInterpreterState *interp)
430{
431 return &interp->core_config;
432}
433
434_PyMainInterpreterConfig *
435_PyInterpreterState_GetMainConfig(PyInterpreterState *interp)
436{
437 return &interp->config;
438}
Eric Snow4c6955e2018-02-16 18:53:40 -0700439
Eric Snowbcfa4502019-03-01 16:50:31 -0700440PyObject *
441_PyInterpreterState_GetMainModule(PyInterpreterState *interp)
442{
443 if (interp->modules == NULL) {
444 PyErr_SetString(PyExc_RuntimeError, "interpreter not initialized");
445 return NULL;
446 }
447 return PyMapping_GetItemString(interp->modules, "__main__");
448}
449
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000450/* Default implementation for _PyThreadState_GetFrame */
451static struct _frame *
452threadstate_getframe(PyThreadState *self)
453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000455}
456
Victor Stinner45b9be52010-03-03 23:28:07 +0000457static PyThreadState *
458new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000459{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200460 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 if (_PyThreadState_GetFrame == NULL)
463 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 if (tstate != NULL) {
466 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 tstate->frame = NULL;
469 tstate->recursion_depth = 0;
470 tstate->overflowed = 0;
471 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700472 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 tstate->tracing = 0;
474 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 tstate->gilstate_counter = 0;
476 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 tstate->curexc_type = NULL;
482 tstate->curexc_value = NULL;
483 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000484
Mark Shannonae3087c2017-10-22 22:41:51 +0100485 tstate->exc_state.exc_type = NULL;
486 tstate->exc_state.exc_value = NULL;
487 tstate->exc_state.exc_traceback = NULL;
488 tstate->exc_state.previous_item = NULL;
489 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000490
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 tstate->c_profilefunc = NULL;
492 tstate->c_tracefunc = NULL;
493 tstate->c_profileobj = NULL;
494 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000495
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200496 tstate->trash_delete_nesting = 0;
497 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200498 tstate->on_delete = NULL;
499 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200500
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800501 tstate->coroutine_origin_tracking_depth = 0;
502
Yury Selivanov75445082015-05-11 22:57:16 -0400503 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400504 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400505
Yury Selivanoveb636452016-09-08 22:01:51 -0700506 tstate->async_gen_firstiter = NULL;
507 tstate->async_gen_finalizer = NULL;
508
Yury Selivanovf23746a2018-01-22 19:11:18 -0500509 tstate->context = NULL;
510 tstate->context_ver = 1;
511
512 tstate->id = ++interp->tstate_next_unique_id;
513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 if (init)
515 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200518 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200520 if (tstate->next)
521 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 interp->tstate_head = tstate;
523 HEAD_UNLOCK();
524 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000527}
528
Victor Stinner45b9be52010-03-03 23:28:07 +0000529PyThreadState *
530PyThreadState_New(PyInterpreterState *interp)
531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000533}
534
535PyThreadState *
536_PyThreadState_Prealloc(PyInterpreterState *interp)
537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000539}
540
541void
542_PyThreadState_Init(PyThreadState *tstate)
543{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000545}
546
Martin v. Löwis1a214512008-06-11 05:26:20 +0000547PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200548PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000549{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200550 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100551 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000553 if (module->m_slots) {
554 return NULL;
555 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 if (index == 0)
557 return NULL;
558 if (state->modules_by_index == NULL)
559 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200560 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 return NULL;
562 res = PyList_GET_ITEM(state->modules_by_index, index);
563 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000564}
565
566int
567_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
568{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000569 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300570 if (!def) {
571 assert(PyErr_Occurred());
572 return -1;
573 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000574 if (def->m_slots) {
575 PyErr_SetString(PyExc_SystemError,
576 "PyState_AddModule called on module with slots");
577 return -1;
578 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100579 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 if (!state->modules_by_index) {
581 state->modules_by_index = PyList_New(0);
582 if (!state->modules_by_index)
583 return -1;
584 }
585 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
586 if (PyList_Append(state->modules_by_index, Py_None) < 0)
587 return -1;
588 Py_INCREF(module);
589 return PyList_SetItem(state->modules_by_index,
590 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000591}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000592
Martin v. Löwis7800f752012-06-22 12:20:55 +0200593int
594PyState_AddModule(PyObject* module, struct PyModuleDef* def)
595{
596 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100597 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200598 if (!def) {
599 Py_FatalError("PyState_AddModule: Module Definition is NULL");
600 return -1;
601 }
602 index = def->m_base.m_index;
603 if (state->modules_by_index) {
604 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
605 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
606 Py_FatalError("PyState_AddModule: Module already added!");
607 return -1;
608 }
609 }
610 }
611 return _PyState_AddModule(module, def);
612}
613
614int
615PyState_RemoveModule(struct PyModuleDef* def)
616{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000617 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200618 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000619 if (def->m_slots) {
620 PyErr_SetString(PyExc_SystemError,
621 "PyState_RemoveModule called on module with slots");
622 return -1;
623 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100624 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200625 if (index == 0) {
626 Py_FatalError("PyState_RemoveModule: Module index invalid.");
627 return -1;
628 }
629 if (state->modules_by_index == NULL) {
630 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
631 return -1;
632 }
633 if (index > PyList_GET_SIZE(state->modules_by_index)) {
634 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
635 return -1;
636 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700637 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200638 return PyList_SetItem(state->modules_by_index, index, Py_None);
639}
640
Antoine Pitrou40322e62013-08-11 00:30:09 +0200641/* used by import.c:PyImport_Cleanup */
642void
643_PyState_ClearModules(void)
644{
Victor Stinner9204fb82018-10-30 15:13:17 +0100645 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200646 if (state->modules_by_index) {
647 Py_ssize_t i;
648 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
649 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
650 if (PyModule_Check(m)) {
651 /* cleanup the saved copy of module dicts */
652 PyModuleDef *md = PyModule_GetDef(m);
653 if (md)
654 Py_CLEAR(md->m_base.m_copy);
655 }
656 }
657 /* Setting modules_by_index to NULL could be dangerous, so we
658 clear the list instead. */
659 if (PyList_SetSlice(state->modules_by_index,
660 0, PyList_GET_SIZE(state->modules_by_index),
661 NULL))
662 PyErr_WriteUnraisable(state->modules_by_index);
663 }
664}
665
Guido van Rossuma027efa1997-05-05 20:56:21 +0000666void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000667PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000668{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200669 int verbose = tstate->interp->core_config.verbose;
670
671 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 fprintf(stderr,
673 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 Py_CLEAR(tstate->dict);
678 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000680 Py_CLEAR(tstate->curexc_type);
681 Py_CLEAR(tstate->curexc_value);
682 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000683
Mark Shannonae3087c2017-10-22 22:41:51 +0100684 Py_CLEAR(tstate->exc_state.exc_type);
685 Py_CLEAR(tstate->exc_state.exc_value);
686 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300687
Mark Shannonae3087c2017-10-22 22:41:51 +0100688 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200689 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100690 fprintf(stderr,
691 "PyThreadState_Clear: warning: thread still has a generator\n");
692 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 tstate->c_profilefunc = NULL;
695 tstate->c_tracefunc = NULL;
696 Py_CLEAR(tstate->c_profileobj);
697 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400698
699 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700700 Py_CLEAR(tstate->async_gen_firstiter);
701 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500702
703 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000704}
705
706
Guido van Rossum29757862001-01-23 01:46:06 +0000707/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
708static void
709tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 if (tstate == NULL)
713 Py_FatalError("PyThreadState_Delete: NULL tstate");
714 interp = tstate->interp;
715 if (interp == NULL)
716 Py_FatalError("PyThreadState_Delete: NULL interp");
717 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200718 if (tstate->prev)
719 tstate->prev->next = tstate->next;
720 else
721 interp->tstate_head = tstate->next;
722 if (tstate->next)
723 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200725 if (tstate->on_delete != NULL) {
726 tstate->on_delete(tstate->on_delete_data);
727 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200728 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000729}
730
731
Guido van Rossum29757862001-01-23 01:46:06 +0000732void
733PyThreadState_Delete(PyThreadState *tstate)
734{
Victor Stinner50b48572018-11-01 01:51:40 +0100735 if (tstate == _PyThreadState_GET())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600737 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900738 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600739 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900740 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600741 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200742 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000743}
744
745
Guido van Rossum29757862001-01-23 01:46:06 +0000746void
747PyThreadState_DeleteCurrent()
748{
Victor Stinner50b48572018-11-01 01:51:40 +0100749 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000750 if (tstate == NULL)
751 Py_FatalError(
752 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100753 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600754 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900755 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600756 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900757 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600758 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100759 _PyThreadState_SET(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000761}
Guido van Rossum29757862001-01-23 01:46:06 +0000762
763
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200764/*
765 * Delete all thread states except the one passed as argument.
766 * Note that, if there is a current thread state, it *must* be the one
767 * passed as argument. Also, this won't touch any other interpreters
768 * than the current one, since we don't know which thread state should
769 * be kept in those other interpreteres.
770 */
771void
772_PyThreadState_DeleteExcept(PyThreadState *tstate)
773{
774 PyInterpreterState *interp = tstate->interp;
775 PyThreadState *p, *next, *garbage;
776 HEAD_LOCK();
777 /* Remove all thread states, except tstate, from the linked list of
778 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200779 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200780 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200781 if (garbage == tstate)
782 garbage = tstate->next;
783 if (tstate->prev)
784 tstate->prev->next = tstate->next;
785 if (tstate->next)
786 tstate->next->prev = tstate->prev;
787 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200788 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200789 HEAD_UNLOCK();
790 /* Clear and deallocate all stale thread states. Even if this
791 executes Python code, we should be safe since it executes
792 in the current thread, not one of the stale threads. */
793 for (p = garbage; p; p = next) {
794 next = p->next;
795 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200796 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200797 }
798}
799
800
Guido van Rossuma027efa1997-05-05 20:56:21 +0000801PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100802_PyThreadState_UncheckedGet(void)
803{
Victor Stinner50b48572018-11-01 01:51:40 +0100804 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100805}
806
807
808PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000809PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000810{
Victor Stinner50b48572018-11-01 01:51:40 +0100811 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 if (tstate == NULL)
813 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000816}
817
818
819PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000820PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000821{
Victor Stinner50b48572018-11-01 01:51:40 +0100822 PyThreadState *oldts = _PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000823
Victor Stinner9204fb82018-10-30 15:13:17 +0100824 _PyThreadState_SET(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000825 /* It should not be possible for more than one thread state
826 to be used for a thread. Check this the best we can in debug
827 builds.
828 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200829#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (newts) {
831 /* This can be called from PyEval_RestoreThread(). Similar
832 to it, we need to ensure errno doesn't change.
833 */
834 int err = errno;
835 PyThreadState *check = PyGILState_GetThisThreadState();
836 if (check && check->interp == newts->interp && check != newts)
837 Py_FatalError("Invalid thread state for this thread");
838 errno = err;
839 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000840#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000842}
Guido van Rossumede04391998-04-10 20:18:25 +0000843
844/* An extension mechanism to store arbitrary additional per-thread state.
845 PyThreadState_GetDict() returns a dictionary that can be used to hold such
846 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000847 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
848 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000849
850PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000851PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000852{
Victor Stinner50b48572018-11-01 01:51:40 +0100853 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 if (tstate == NULL)
855 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 if (tstate->dict == NULL) {
858 PyObject *d;
859 tstate->dict = d = PyDict_New();
860 if (d == NULL)
861 PyErr_Clear();
862 }
863 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000864}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000865
866
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000867/* Asynchronously raise an exception in a thread.
868 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000869 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000870 to call this, or use ctypes. Must be called with the GIL held.
871 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
872 match any known thread id). Can be called with exc=NULL to clear an
873 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000874
875int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200876PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
877{
Victor Stinner9204fb82018-10-30 15:13:17 +0100878 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 /* Although the GIL is held, a few C API functions can be called
882 * without the GIL held, and in particular some that create and
883 * destroy thread and interpreter states. Those can mutate the
884 * list of thread states we're traversing, so to prevent that we lock
885 * head_mutex for the duration.
886 */
887 HEAD_LOCK();
888 for (p = interp->tstate_head; p != NULL; p = p->next) {
889 if (p->thread_id == id) {
890 /* Tricky: we need to decref the current value
891 * (if any) in p->async_exc, but that can in turn
892 * allow arbitrary Python code to run, including
893 * perhaps calls to this function. To prevent
894 * deadlock, we need to release head_mutex before
895 * the decref.
896 */
897 PyObject *old_exc = p->async_exc;
898 Py_XINCREF(exc);
899 p->async_exc = exc;
900 HEAD_UNLOCK();
901 Py_XDECREF(old_exc);
Eric Snowef4ac962019-02-24 15:40:47 -0800902 _PyEval_SignalAsyncExc(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 return 1;
904 }
905 }
906 HEAD_UNLOCK();
907 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000908}
909
910
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000911/* Routines for advanced debuggers, requested by David Beazley.
912 Don't use unless you know what you are doing! */
913
914PyInterpreterState *
915PyInterpreterState_Head(void)
916{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600917 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000918}
919
920PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700921PyInterpreterState_Main(void)
922{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600923 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700924}
925
926PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000927PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000929}
930
931PyThreadState *
932PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000934}
935
936PyThreadState *
937PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000939}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000940
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000941/* The implementation of sys._current_frames(). This is intended to be
942 called with the GIL held, as it will be when called via
943 sys._current_frames(). It's possible it would work fine even without
944 the GIL held, but haven't thought enough about that.
945*/
946PyObject *
947_PyThread_CurrentFrames(void)
948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 PyObject *result;
950 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000951
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 result = PyDict_New();
953 if (result == NULL)
954 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000956 /* for i in all interpreters:
957 * for t in all of i's thread states:
958 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200959 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 * need to grab head_mutex for the duration.
961 */
962 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600963 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 PyThreadState *t;
965 for (t = i->tstate_head; t != NULL; t = t->next) {
966 PyObject *id;
967 int stat;
968 struct _frame *frame = t->frame;
969 if (frame == NULL)
970 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200971 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000972 if (id == NULL)
973 goto Fail;
974 stat = PyDict_SetItem(result, id, (PyObject *)frame);
975 Py_DECREF(id);
976 if (stat < 0)
977 goto Fail;
978 }
979 }
980 HEAD_UNLOCK();
981 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000982
983 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 HEAD_UNLOCK();
985 Py_DECREF(result);
986 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000987}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000988
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000989/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000990
991/* Keep this as a static, as it is not reliable! It can only
992 ever be compared to the state for the *current* thread.
993 * If not equal, then it doesn't matter that the actual
994 value may change immediately after comparison, as it can't
995 possibly change to the current thread's state.
996 * If equal, then the current thread holds the lock, so the value can't
997 change until we yield the lock.
998*/
999static int
1000PyThreadState_IsCurrent(PyThreadState *tstate)
1001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 /* Must be the tstate for this thread */
1003 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinner50b48572018-11-01 01:51:40 +01001004 return tstate == _PyThreadState_GET();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001005}
1006
Tim Peters4c1f5ec2004-10-09 17:25:05 +00001007/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001008 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001009*/
Tim Peters19717fa2004-10-09 17:38:29 +00001010void
1011_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001014 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1015 Py_FatalError("Could not allocate TSS entry");
1016 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001017 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001018 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +00001020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001022}
1023
Victor Stinner861d9ab2016-03-16 22:45:24 +01001024PyInterpreterState *
1025_PyGILState_GetInterpreterStateUnsafe(void)
1026{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001027 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +01001028}
1029
Tim Peters19717fa2004-10-09 17:38:29 +00001030void
1031_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001032{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001033 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001034 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001035}
1036
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001037/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001038 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001039 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001040 */
1041void
1042_PyGILState_Reinit(void)
1043{
Victor Stinner5d926472018-03-06 14:31:37 +01001044 /* Force default allocator, since _PyRuntimeState_Fini() must
1045 use the same allocator than this function. */
1046 PyMemAllocatorEx old_alloc;
1047 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1048
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001049 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +01001050
1051 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1052
1053 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001054 Py_FatalError("Can't initialize threads for interpreter");
Victor Stinner5d926472018-03-06 14:31:37 +01001055 }
1056
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001057 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001058 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
1059 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1060 Py_FatalError("Could not allocate TSS entry");
1061 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001062
Charles-François Natalia233df82011-11-22 19:49:51 +01001063 /* If the thread had an associated auto thread state, reassociate it with
1064 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001065 if (tstate &&
1066 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
1067 {
1068 Py_FatalError("Couldn't create autoTSSkey mapping");
1069 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001070}
1071
Michael W. Hudson188d4362005-06-20 16:52:57 +00001072/* When a thread state is created for a thread by some mechanism other than
1073 PyGILState_Ensure, it's important that the GILState machinery knows about
1074 it so it doesn't try to create another thread state for the thread (this is
1075 a better fix for SF bug #1010677 than the first one attempted).
1076*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001077static void
Michael W. Hudson188d4362005-06-20 16:52:57 +00001078_PyGILState_NoteThreadState(PyThreadState* tstate)
1079{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001080 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001081 threadstate created in Py_Initialize(). Don't do anything for now
1082 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001083 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001085
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001086 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 The only situation where you can legitimately have more than one
1089 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001090 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001091
Victor Stinner590cebe2013-12-13 11:08:56 +01001092 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1093 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001094
Victor Stinner590cebe2013-12-13 11:08:56 +01001095 The first thread state created for that given OS level thread will
1096 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001098 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
1099 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1100 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001101 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001102 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001103 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001104 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 /* PyGILState_Release must not try to delete this thread state. */
1107 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001108}
1109
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001110/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001111PyThreadState *
1112PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001113{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001114 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001116 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001117}
1118
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001119int
1120PyGILState_Check(void)
1121{
Victor Stinner8a1be612016-03-14 22:07:55 +01001122 PyThreadState *tstate;
1123
1124 if (!_PyGILState_check_enabled)
1125 return 1;
1126
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001127 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001128 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001129 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001130
Victor Stinner50b48572018-11-01 01:51:40 +01001131 tstate = _PyThreadState_GET();
Victor Stinner8a1be612016-03-14 22:07:55 +01001132 if (tstate == NULL)
1133 return 0;
1134
1135 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001136}
1137
Tim Peters19717fa2004-10-09 17:38:29 +00001138PyGILState_STATE
1139PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 int current;
1142 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001143 int need_init_threads = 0;
1144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 /* Note that we do not auto-init Python here - apart from
1146 potential races with 2 threads auto-initializing, pep-311
1147 spells out other issues. Embedders are expected to have
1148 called Py_Initialize() and usually PyEval_InitThreads().
1149 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001150 /* Py_Initialize() hasn't been called! */
1151 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001152
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001153 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001155 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001158 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 if (tcur == NULL)
1160 Py_FatalError("Couldn't create thread-state for new thread");
1161 /* This is our thread state! We'll need to delete it in the
1162 matching call to PyGILState_Release(). */
1163 tcur->gilstate_counter = 0;
1164 current = 0; /* new thread state is never current */
1165 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001166 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001168 }
1169
1170 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001172 }
1173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 /* Update our counter in the thread-state - no need for locks:
1175 - tcur will remain valid as we hold the GIL.
1176 - the counter is safe as we are the only thread "allowed"
1177 to modify this value
1178 */
1179 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001180
1181 if (need_init_threads) {
1182 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1183 called from a new thread for the first time, we need the create the
1184 GIL. */
1185 PyEval_InitThreads();
1186 }
1187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001189}
1190
Tim Peters19717fa2004-10-09 17:38:29 +00001191void
1192PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001193{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001194 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1195 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001196 if (tcur == NULL)
1197 Py_FatalError("auto-releasing thread-state, "
1198 "but no thread-state for this thread");
1199 /* We must hold the GIL and have our thread state current */
1200 /* XXX - remove the check - the assert should be fine,
1201 but while this is very new (April 2003), the extra check
1202 by release-only users can't hurt.
1203 */
1204 if (! PyThreadState_IsCurrent(tcur))
1205 Py_FatalError("This thread state must be current when releasing");
1206 assert(PyThreadState_IsCurrent(tcur));
1207 --tcur->gilstate_counter;
1208 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 /* If we're going to destroy this thread-state, we must
1211 * clear it while the GIL is held, as destructors may run.
1212 */
1213 if (tcur->gilstate_counter == 0) {
1214 /* can't have been locked when we created it */
1215 assert(oldstate == PyGILState_UNLOCKED);
1216 PyThreadState_Clear(tcur);
1217 /* Delete the thread-state. Note this releases the GIL too!
1218 * It's vital that the GIL be held here, to avoid shutdown
1219 * races; see bugs 225673 and 1061968 (that nasty bug has a
1220 * habit of coming back).
1221 */
1222 PyThreadState_DeleteCurrent();
1223 }
1224 /* Release the lock if necessary */
1225 else if (oldstate == PyGILState_UNLOCKED)
1226 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001227}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001228
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001229
Eric Snow7f8bfc92018-01-29 18:23:44 -07001230/**************************/
1231/* cross-interpreter data */
1232/**************************/
1233
1234/* cross-interpreter data */
1235
1236crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1237
1238/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1239 to keep the registry code separate. */
1240static crossinterpdatafunc
1241_lookup_getdata(PyObject *obj)
1242{
1243 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1244 if (getdata == NULL && PyErr_Occurred() == 0)
1245 PyErr_Format(PyExc_ValueError,
1246 "%S does not support cross-interpreter data", obj);
1247 return getdata;
1248}
1249
1250int
1251_PyObject_CheckCrossInterpreterData(PyObject *obj)
1252{
1253 crossinterpdatafunc getdata = _lookup_getdata(obj);
1254 if (getdata == NULL) {
1255 return -1;
1256 }
1257 return 0;
1258}
1259
1260static int
1261_check_xidata(_PyCrossInterpreterData *data)
1262{
1263 // data->data can be anything, including NULL, so we don't check it.
1264
1265 // data->obj may be NULL, so we don't check it.
1266
1267 if (data->interp < 0) {
1268 PyErr_SetString(PyExc_SystemError, "missing interp");
1269 return -1;
1270 }
1271
1272 if (data->new_object == NULL) {
1273 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1274 return -1;
1275 }
1276
1277 // data->free may be NULL, so we don't check it.
1278
1279 return 0;
1280}
1281
1282int
1283_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1284{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001285 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001286 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001287 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001288
1289 // Reset data before re-populating.
1290 *data = (_PyCrossInterpreterData){0};
1291 data->free = PyMem_RawFree; // Set a default that may be overridden.
1292
1293 // Call the "getdata" func for the object.
1294 Py_INCREF(obj);
1295 crossinterpdatafunc getdata = _lookup_getdata(obj);
1296 if (getdata == NULL) {
1297 Py_DECREF(obj);
1298 return -1;
1299 }
1300 int res = getdata(obj, data);
1301 Py_DECREF(obj);
1302 if (res != 0) {
1303 return -1;
1304 }
1305
1306 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001307 data->interp = interp->id;
1308 if (_check_xidata(data) != 0) {
1309 _PyCrossInterpreterData_Release(data);
1310 return -1;
1311 }
1312
1313 return 0;
1314}
1315
Eric Snowb05b7112019-03-01 12:35:10 -07001316static int
Eric Snow63799132018-06-01 18:45:20 -06001317_release_xidata(void *arg)
1318{
1319 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1320 if (data->free != NULL) {
1321 data->free(data->data);
1322 }
1323 Py_XDECREF(data->obj);
Eric Snowb05b7112019-03-01 12:35:10 -07001324 PyMem_Free(data);
1325 return 0;
Eric Snow63799132018-06-01 18:45:20 -06001326}
1327
Eric Snow7f8bfc92018-01-29 18:23:44 -07001328void
1329_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1330{
1331 if (data->data == NULL && data->obj == NULL) {
1332 // Nothing to release!
1333 return;
1334 }
1335
Eric Snowb05b7112019-03-01 12:35:10 -07001336 // Get the original interpreter.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001337 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1338 if (interp == NULL) {
1339 // The intepreter was already destroyed.
1340 if (data->free != NULL) {
1341 // XXX Someone leaked some memory...
1342 }
1343 return;
1344 }
Eric Snowb05b7112019-03-01 12:35:10 -07001345 // XXX There's an ever-so-slight race here...
1346 if (interp->finalizing) {
1347 // XXX Someone leaked some memory...
1348 return;
1349 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001350
Eric Snow7f8bfc92018-01-29 18:23:44 -07001351 // "Release" the data and/or the object.
Eric Snowb05b7112019-03-01 12:35:10 -07001352 _PyCrossInterpreterData *copied = PyMem_Malloc(sizeof(_PyCrossInterpreterData));
1353 if (copied == NULL) {
1354 PyErr_SetString(PyExc_MemoryError,
1355 "Not enough memory to preserve cross-interpreter data");
1356 PyErr_Print();
1357 return;
1358 }
1359 memcpy(copied, data, sizeof(_PyCrossInterpreterData));
1360 if (_Py_AddPendingCall(interp, 0, _release_xidata, copied) != 0) {
1361 // XXX Queue full or couldn't get lock. Try again somehow?
1362 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001363}
1364
1365PyObject *
1366_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1367{
1368 return data->new_object(data);
1369}
1370
1371/* registry of {type -> crossinterpdatafunc} */
1372
1373/* For now we use a global registry of shareable classes. An
1374 alternative would be to add a tp_* slot for a class's
1375 crossinterpdatafunc. It would be simpler and more efficient. */
1376
1377static int
1378_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1379{
1380 // Note that we effectively replace already registered classes
1381 // rather than failing.
1382 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1383 if (newhead == NULL)
1384 return -1;
1385 newhead->cls = cls;
1386 newhead->getdata = getdata;
1387 newhead->next = _PyRuntime.xidregistry.head;
1388 _PyRuntime.xidregistry.head = newhead;
1389 return 0;
1390}
1391
1392static void _register_builtins_for_crossinterpreter_data(void);
1393
1394int
Eric Snowbcfa4502019-03-01 16:50:31 -07001395_PyCrossInterpreterData_RegisterClass(PyTypeObject *cls,
Eric Snow7f8bfc92018-01-29 18:23:44 -07001396 crossinterpdatafunc getdata)
1397{
1398 if (!PyType_Check(cls)) {
1399 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1400 return -1;
1401 }
1402 if (getdata == NULL) {
1403 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1404 return -1;
1405 }
1406
1407 // Make sure the class isn't ever deallocated.
1408 Py_INCREF((PyObject *)cls);
1409
1410 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1411 if (_PyRuntime.xidregistry.head == NULL) {
1412 _register_builtins_for_crossinterpreter_data();
1413 }
1414 int res = _register_xidata(cls, getdata);
1415 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1416 return res;
1417}
1418
Eric Snow6d2cd902018-05-16 15:04:57 -04001419/* Cross-interpreter objects are looked up by exact match on the class.
1420 We can reassess this policy when we move from a global registry to a
1421 tp_* slot. */
1422
Eric Snow7f8bfc92018-01-29 18:23:44 -07001423crossinterpdatafunc
1424_PyCrossInterpreterData_Lookup(PyObject *obj)
1425{
1426 PyObject *cls = PyObject_Type(obj);
1427 crossinterpdatafunc getdata = NULL;
1428 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1429 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1430 if (cur == NULL) {
1431 _register_builtins_for_crossinterpreter_data();
1432 cur = _PyRuntime.xidregistry.head;
1433 }
1434 for(; cur != NULL; cur = cur->next) {
1435 if (cur->cls == (PyTypeObject *)cls) {
1436 getdata = cur->getdata;
1437 break;
1438 }
1439 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001440 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001441 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1442 return getdata;
1443}
1444
1445/* cross-interpreter data for builtin types */
1446
Eric Snow6d2cd902018-05-16 15:04:57 -04001447struct _shared_bytes_data {
1448 char *bytes;
1449 Py_ssize_t len;
1450};
1451
Eric Snow7f8bfc92018-01-29 18:23:44 -07001452static PyObject *
1453_new_bytes_object(_PyCrossInterpreterData *data)
1454{
Eric Snow6d2cd902018-05-16 15:04:57 -04001455 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1456 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001457}
1458
1459static int
1460_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1461{
Eric Snow6d2cd902018-05-16 15:04:57 -04001462 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1463 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1464 return -1;
1465 }
1466 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001467 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001468 data->obj = obj; // Will be "released" (decref'ed) when data released.
1469 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001470 data->free = PyMem_Free;
1471 return 0;
1472}
1473
1474struct _shared_str_data {
1475 int kind;
1476 const void *buffer;
1477 Py_ssize_t len;
1478};
1479
1480static PyObject *
1481_new_str_object(_PyCrossInterpreterData *data)
1482{
1483 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1484 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1485}
1486
1487static int
1488_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1489{
1490 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1491 shared->kind = PyUnicode_KIND(obj);
1492 shared->buffer = PyUnicode_DATA(obj);
1493 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1494 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001495 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001496 data->obj = obj; // Will be "released" (decref'ed) when data released.
1497 data->new_object = _new_str_object;
1498 data->free = PyMem_Free;
1499 return 0;
1500}
1501
1502static PyObject *
1503_new_long_object(_PyCrossInterpreterData *data)
1504{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001505 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001506}
1507
1508static int
1509_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1510{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001511 /* Note that this means the size of shareable ints is bounded by
1512 * sys.maxsize. Hence on 32-bit architectures that is half the
1513 * size of maximum shareable ints on 64-bit.
1514 */
1515 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001516 if (value == -1 && PyErr_Occurred()) {
1517 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1518 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1519 }
1520 return -1;
1521 }
1522 data->data = (void *)value;
1523 data->obj = NULL;
1524 data->new_object = _new_long_object;
1525 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001526 return 0;
1527}
1528
1529static PyObject *
1530_new_none_object(_PyCrossInterpreterData *data)
1531{
1532 // XXX Singleton refcounts are problematic across interpreters...
1533 Py_INCREF(Py_None);
1534 return Py_None;
1535}
1536
1537static int
1538_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1539{
1540 data->data = NULL;
1541 // data->obj remains NULL
1542 data->new_object = _new_none_object;
1543 data->free = NULL; // There is nothing to free.
1544 return 0;
1545}
1546
1547static void
1548_register_builtins_for_crossinterpreter_data(void)
1549{
1550 // None
1551 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1552 Py_FatalError("could not register None for cross-interpreter sharing");
1553 }
1554
Eric Snow6d2cd902018-05-16 15:04:57 -04001555 // int
1556 if (_register_xidata(&PyLong_Type, _long_shared) != 0) {
1557 Py_FatalError("could not register int for cross-interpreter sharing");
1558 }
1559
Eric Snow7f8bfc92018-01-29 18:23:44 -07001560 // bytes
1561 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1562 Py_FatalError("could not register bytes for cross-interpreter sharing");
1563 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001564
1565 // str
1566 if (_register_xidata(&PyUnicode_Type, _str_shared) != 0) {
1567 Py_FatalError("could not register str for cross-interpreter sharing");
1568 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001569}
1570
1571
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001572#ifdef __cplusplus
1573}
1574#endif