blob: a9a425c2f49cb91bce75b3ff3d50dd6054630aa7 [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 Snow7f8bfc92018-01-29 18:23:44 -0700331PyInterpreterState *
332_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
333{
334 if (requested_id < 0)
335 goto error;
336
337 PyInterpreterState *interp = PyInterpreterState_Head();
338 while (interp != NULL) {
339 PY_INT64_T id = PyInterpreterState_GetID(interp);
340 if (id < 0)
341 return NULL;
342 if (requested_id == id)
343 return interp;
344 interp = PyInterpreterState_Next(interp);
345 }
346
347error:
348 PyErr_Format(PyExc_RuntimeError,
349 "unrecognized interpreter ID %lld", requested_id);
350 return NULL;
351}
352
Eric Snow4c6955e2018-02-16 18:53:40 -0700353
354int
355_PyInterpreterState_IDInitref(PyInterpreterState *interp)
356{
357 if (interp->id_mutex != NULL) {
358 return 0;
359 }
360 interp->id_mutex = PyThread_allocate_lock();
361 if (interp->id_mutex == NULL) {
362 PyErr_SetString(PyExc_RuntimeError,
363 "failed to create init interpreter ID mutex");
364 return -1;
365 }
366 interp->id_refcount = 0;
367 return 0;
368}
369
370
371void
372_PyInterpreterState_IDIncref(PyInterpreterState *interp)
373{
374 if (interp->id_mutex == NULL) {
375 return;
376 }
377 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
378 interp->id_refcount += 1;
379 PyThread_release_lock(interp->id_mutex);
380}
381
382
383void
384_PyInterpreterState_IDDecref(PyInterpreterState *interp)
385{
386 if (interp->id_mutex == NULL) {
387 return;
388 }
389 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
390 assert(interp->id_refcount != 0);
391 interp->id_refcount -= 1;
392 int64_t refcount = interp->id_refcount;
393 PyThread_release_lock(interp->id_mutex);
394
395 if (refcount == 0) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700396 // XXX Using the "head" thread isn't strictly correct.
397 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
398 // XXX Possible GILState issues?
399 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700400 Py_EndInterpreter(tstate);
401 PyThreadState_Swap(save_tstate);
402 }
403}
404
Eric Snowbe3b2952019-02-23 11:35:52 -0700405_PyCoreConfig *
406_PyInterpreterState_GetCoreConfig(PyInterpreterState *interp)
407{
408 return &interp->core_config;
409}
410
411_PyMainInterpreterConfig *
412_PyInterpreterState_GetMainConfig(PyInterpreterState *interp)
413{
414 return &interp->config;
415}
Eric Snow4c6955e2018-02-16 18:53:40 -0700416
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000417/* Default implementation for _PyThreadState_GetFrame */
418static struct _frame *
419threadstate_getframe(PyThreadState *self)
420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000422}
423
Victor Stinner45b9be52010-03-03 23:28:07 +0000424static PyThreadState *
425new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000426{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200427 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 if (_PyThreadState_GetFrame == NULL)
430 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 if (tstate != NULL) {
433 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 tstate->frame = NULL;
436 tstate->recursion_depth = 0;
437 tstate->overflowed = 0;
438 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700439 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 tstate->tracing = 0;
441 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 tstate->gilstate_counter = 0;
443 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 tstate->curexc_type = NULL;
449 tstate->curexc_value = NULL;
450 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000451
Mark Shannonae3087c2017-10-22 22:41:51 +0100452 tstate->exc_state.exc_type = NULL;
453 tstate->exc_state.exc_value = NULL;
454 tstate->exc_state.exc_traceback = NULL;
455 tstate->exc_state.previous_item = NULL;
456 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 tstate->c_profilefunc = NULL;
459 tstate->c_tracefunc = NULL;
460 tstate->c_profileobj = NULL;
461 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000462
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200463 tstate->trash_delete_nesting = 0;
464 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200465 tstate->on_delete = NULL;
466 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200467
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800468 tstate->coroutine_origin_tracking_depth = 0;
469
Yury Selivanov75445082015-05-11 22:57:16 -0400470 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400471 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400472
Yury Selivanoveb636452016-09-08 22:01:51 -0700473 tstate->async_gen_firstiter = NULL;
474 tstate->async_gen_finalizer = NULL;
475
Yury Selivanovf23746a2018-01-22 19:11:18 -0500476 tstate->context = NULL;
477 tstate->context_ver = 1;
478
479 tstate->id = ++interp->tstate_next_unique_id;
480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (init)
482 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200485 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200487 if (tstate->next)
488 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 interp->tstate_head = tstate;
490 HEAD_UNLOCK();
491 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000494}
495
Victor Stinner45b9be52010-03-03 23:28:07 +0000496PyThreadState *
497PyThreadState_New(PyInterpreterState *interp)
498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000500}
501
502PyThreadState *
503_PyThreadState_Prealloc(PyInterpreterState *interp)
504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000506}
507
508void
509_PyThreadState_Init(PyThreadState *tstate)
510{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000512}
513
Martin v. Löwis1a214512008-06-11 05:26:20 +0000514PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200515PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000516{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200517 Py_ssize_t index = module->m_base.m_index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100518 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000520 if (module->m_slots) {
521 return NULL;
522 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 if (index == 0)
524 return NULL;
525 if (state->modules_by_index == NULL)
526 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200527 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 return NULL;
529 res = PyList_GET_ITEM(state->modules_by_index, index);
530 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000531}
532
533int
534_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
535{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000536 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300537 if (!def) {
538 assert(PyErr_Occurred());
539 return -1;
540 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000541 if (def->m_slots) {
542 PyErr_SetString(PyExc_SystemError,
543 "PyState_AddModule called on module with slots");
544 return -1;
545 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100546 state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 if (!state->modules_by_index) {
548 state->modules_by_index = PyList_New(0);
549 if (!state->modules_by_index)
550 return -1;
551 }
552 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
553 if (PyList_Append(state->modules_by_index, Py_None) < 0)
554 return -1;
555 Py_INCREF(module);
556 return PyList_SetItem(state->modules_by_index,
557 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000558}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000559
Martin v. Löwis7800f752012-06-22 12:20:55 +0200560int
561PyState_AddModule(PyObject* module, struct PyModuleDef* def)
562{
563 Py_ssize_t index;
Victor Stinner9204fb82018-10-30 15:13:17 +0100564 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200565 if (!def) {
566 Py_FatalError("PyState_AddModule: Module Definition is NULL");
567 return -1;
568 }
569 index = def->m_base.m_index;
570 if (state->modules_by_index) {
571 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
572 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
573 Py_FatalError("PyState_AddModule: Module already added!");
574 return -1;
575 }
576 }
577 }
578 return _PyState_AddModule(module, def);
579}
580
581int
582PyState_RemoveModule(struct PyModuleDef* def)
583{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000584 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200585 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000586 if (def->m_slots) {
587 PyErr_SetString(PyExc_SystemError,
588 "PyState_RemoveModule called on module with slots");
589 return -1;
590 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100591 state = _PyInterpreterState_GET_UNSAFE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200592 if (index == 0) {
593 Py_FatalError("PyState_RemoveModule: Module index invalid.");
594 return -1;
595 }
596 if (state->modules_by_index == NULL) {
597 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
598 return -1;
599 }
600 if (index > PyList_GET_SIZE(state->modules_by_index)) {
601 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
602 return -1;
603 }
Zackery Spytz2a893432018-12-05 00:14:00 -0700604 Py_INCREF(Py_None);
Martin v. Löwis7800f752012-06-22 12:20:55 +0200605 return PyList_SetItem(state->modules_by_index, index, Py_None);
606}
607
Antoine Pitrou40322e62013-08-11 00:30:09 +0200608/* used by import.c:PyImport_Cleanup */
609void
610_PyState_ClearModules(void)
611{
Victor Stinner9204fb82018-10-30 15:13:17 +0100612 PyInterpreterState *state = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200613 if (state->modules_by_index) {
614 Py_ssize_t i;
615 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
616 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
617 if (PyModule_Check(m)) {
618 /* cleanup the saved copy of module dicts */
619 PyModuleDef *md = PyModule_GetDef(m);
620 if (md)
621 Py_CLEAR(md->m_base.m_copy);
622 }
623 }
624 /* Setting modules_by_index to NULL could be dangerous, so we
625 clear the list instead. */
626 if (PyList_SetSlice(state->modules_by_index,
627 0, PyList_GET_SIZE(state->modules_by_index),
628 NULL))
629 PyErr_WriteUnraisable(state->modules_by_index);
630 }
631}
632
Guido van Rossuma027efa1997-05-05 20:56:21 +0000633void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000634PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000635{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200636 int verbose = tstate->interp->core_config.verbose;
637
638 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 fprintf(stderr,
640 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000643
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 Py_CLEAR(tstate->dict);
645 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 Py_CLEAR(tstate->curexc_type);
648 Py_CLEAR(tstate->curexc_value);
649 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000650
Mark Shannonae3087c2017-10-22 22:41:51 +0100651 Py_CLEAR(tstate->exc_state.exc_type);
652 Py_CLEAR(tstate->exc_state.exc_value);
653 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300654
Mark Shannonae3087c2017-10-22 22:41:51 +0100655 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200656 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100657 fprintf(stderr,
658 "PyThreadState_Clear: warning: thread still has a generator\n");
659 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 tstate->c_profilefunc = NULL;
662 tstate->c_tracefunc = NULL;
663 Py_CLEAR(tstate->c_profileobj);
664 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400665
666 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700667 Py_CLEAR(tstate->async_gen_firstiter);
668 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500669
670 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000671}
672
673
Guido van Rossum29757862001-01-23 01:46:06 +0000674/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
675static void
676tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000677{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 if (tstate == NULL)
680 Py_FatalError("PyThreadState_Delete: NULL tstate");
681 interp = tstate->interp;
682 if (interp == NULL)
683 Py_FatalError("PyThreadState_Delete: NULL interp");
684 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200685 if (tstate->prev)
686 tstate->prev->next = tstate->next;
687 else
688 interp->tstate_head = tstate->next;
689 if (tstate->next)
690 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200692 if (tstate->on_delete != NULL) {
693 tstate->on_delete(tstate->on_delete_data);
694 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200695 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000696}
697
698
Guido van Rossum29757862001-01-23 01:46:06 +0000699void
700PyThreadState_Delete(PyThreadState *tstate)
701{
Victor Stinner50b48572018-11-01 01:51:40 +0100702 if (tstate == _PyThreadState_GET())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600704 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900705 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600706 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900707 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600708 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200709 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000710}
711
712
Guido van Rossum29757862001-01-23 01:46:06 +0000713void
714PyThreadState_DeleteCurrent()
715{
Victor Stinner50b48572018-11-01 01:51:40 +0100716 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 if (tstate == NULL)
718 Py_FatalError(
719 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100720 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600721 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900722 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600723 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900724 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600725 }
Victor Stinner9204fb82018-10-30 15:13:17 +0100726 _PyThreadState_SET(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000728}
Guido van Rossum29757862001-01-23 01:46:06 +0000729
730
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200731/*
732 * Delete all thread states except the one passed as argument.
733 * Note that, if there is a current thread state, it *must* be the one
734 * passed as argument. Also, this won't touch any other interpreters
735 * than the current one, since we don't know which thread state should
736 * be kept in those other interpreteres.
737 */
738void
739_PyThreadState_DeleteExcept(PyThreadState *tstate)
740{
741 PyInterpreterState *interp = tstate->interp;
742 PyThreadState *p, *next, *garbage;
743 HEAD_LOCK();
744 /* Remove all thread states, except tstate, from the linked list of
745 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200746 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200747 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200748 if (garbage == tstate)
749 garbage = tstate->next;
750 if (tstate->prev)
751 tstate->prev->next = tstate->next;
752 if (tstate->next)
753 tstate->next->prev = tstate->prev;
754 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200755 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200756 HEAD_UNLOCK();
757 /* Clear and deallocate all stale thread states. Even if this
758 executes Python code, we should be safe since it executes
759 in the current thread, not one of the stale threads. */
760 for (p = garbage; p; p = next) {
761 next = p->next;
762 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200763 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200764 }
765}
766
767
Guido van Rossuma027efa1997-05-05 20:56:21 +0000768PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100769_PyThreadState_UncheckedGet(void)
770{
Victor Stinner50b48572018-11-01 01:51:40 +0100771 return _PyThreadState_GET();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100772}
773
774
775PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000776PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000777{
Victor Stinner50b48572018-11-01 01:51:40 +0100778 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 if (tstate == NULL)
780 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000783}
784
785
786PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000787PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000788{
Victor Stinner50b48572018-11-01 01:51:40 +0100789 PyThreadState *oldts = _PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000790
Victor Stinner9204fb82018-10-30 15:13:17 +0100791 _PyThreadState_SET(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 /* It should not be possible for more than one thread state
793 to be used for a thread. Check this the best we can in debug
794 builds.
795 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200796#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 if (newts) {
798 /* This can be called from PyEval_RestoreThread(). Similar
799 to it, we need to ensure errno doesn't change.
800 */
801 int err = errno;
802 PyThreadState *check = PyGILState_GetThisThreadState();
803 if (check && check->interp == newts->interp && check != newts)
804 Py_FatalError("Invalid thread state for this thread");
805 errno = err;
806 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000807#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000809}
Guido van Rossumede04391998-04-10 20:18:25 +0000810
811/* An extension mechanism to store arbitrary additional per-thread state.
812 PyThreadState_GetDict() returns a dictionary that can be used to hold such
813 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000814 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
815 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000816
817PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000818PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000819{
Victor Stinner50b48572018-11-01 01:51:40 +0100820 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 if (tstate == NULL)
822 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 if (tstate->dict == NULL) {
825 PyObject *d;
826 tstate->dict = d = PyDict_New();
827 if (d == NULL)
828 PyErr_Clear();
829 }
830 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000831}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000832
833
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000834/* Asynchronously raise an exception in a thread.
835 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000836 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000837 to call this, or use ctypes. Must be called with the GIL held.
838 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
839 match any known thread id). Can be called with exc=NULL to clear an
840 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000841
842int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200843PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
844{
Victor Stinner9204fb82018-10-30 15:13:17 +0100845 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 /* Although the GIL is held, a few C API functions can be called
849 * without the GIL held, and in particular some that create and
850 * destroy thread and interpreter states. Those can mutate the
851 * list of thread states we're traversing, so to prevent that we lock
852 * head_mutex for the duration.
853 */
854 HEAD_LOCK();
855 for (p = interp->tstate_head; p != NULL; p = p->next) {
856 if (p->thread_id == id) {
857 /* Tricky: we need to decref the current value
858 * (if any) in p->async_exc, but that can in turn
859 * allow arbitrary Python code to run, including
860 * perhaps calls to this function. To prevent
861 * deadlock, we need to release head_mutex before
862 * the decref.
863 */
864 PyObject *old_exc = p->async_exc;
865 Py_XINCREF(exc);
866 p->async_exc = exc;
867 HEAD_UNLOCK();
868 Py_XDECREF(old_exc);
Eric Snowef4ac962019-02-24 15:40:47 -0800869 _PyEval_SignalAsyncExc(interp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 return 1;
871 }
872 }
873 HEAD_UNLOCK();
874 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000875}
876
877
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000878/* Routines for advanced debuggers, requested by David Beazley.
879 Don't use unless you know what you are doing! */
880
881PyInterpreterState *
882PyInterpreterState_Head(void)
883{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600884 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000885}
886
887PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700888PyInterpreterState_Main(void)
889{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600890 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700891}
892
893PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000894PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000896}
897
898PyThreadState *
899PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000901}
902
903PyThreadState *
904PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000906}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000907
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000908/* The implementation of sys._current_frames(). This is intended to be
909 called with the GIL held, as it will be when called via
910 sys._current_frames(). It's possible it would work fine even without
911 the GIL held, but haven't thought enough about that.
912*/
913PyObject *
914_PyThread_CurrentFrames(void)
915{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 PyObject *result;
917 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 result = PyDict_New();
920 if (result == NULL)
921 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 /* for i in all interpreters:
924 * for t in all of i's thread states:
925 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200926 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 * need to grab head_mutex for the duration.
928 */
929 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600930 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 PyThreadState *t;
932 for (t = i->tstate_head; t != NULL; t = t->next) {
933 PyObject *id;
934 int stat;
935 struct _frame *frame = t->frame;
936 if (frame == NULL)
937 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200938 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 if (id == NULL)
940 goto Fail;
941 stat = PyDict_SetItem(result, id, (PyObject *)frame);
942 Py_DECREF(id);
943 if (stat < 0)
944 goto Fail;
945 }
946 }
947 HEAD_UNLOCK();
948 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000949
950 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 HEAD_UNLOCK();
952 Py_DECREF(result);
953 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000954}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000955
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000956/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000957
958/* Keep this as a static, as it is not reliable! It can only
959 ever be compared to the state for the *current* thread.
960 * If not equal, then it doesn't matter that the actual
961 value may change immediately after comparison, as it can't
962 possibly change to the current thread's state.
963 * If equal, then the current thread holds the lock, so the value can't
964 change until we yield the lock.
965*/
966static int
967PyThreadState_IsCurrent(PyThreadState *tstate)
968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 /* Must be the tstate for this thread */
970 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinner50b48572018-11-01 01:51:40 +0100971 return tstate == _PyThreadState_GET();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000972}
973
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000974/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000975 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000976*/
Tim Peters19717fa2004-10-09 17:38:29 +0000977void
978_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000979{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900981 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
982 Py_FatalError("Could not allocate TSS entry");
983 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600984 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900985 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000989}
990
Victor Stinner861d9ab2016-03-16 22:45:24 +0100991PyInterpreterState *
992_PyGILState_GetInterpreterStateUnsafe(void)
993{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600994 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100995}
996
Tim Peters19717fa2004-10-09 17:38:29 +0000997void
998_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000999{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001000 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001001 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001002}
1003
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001004/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001005 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001006 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001007 */
1008void
1009_PyGILState_Reinit(void)
1010{
Victor Stinner5d926472018-03-06 14:31:37 +01001011 /* Force default allocator, since _PyRuntimeState_Fini() must
1012 use the same allocator than this function. */
1013 PyMemAllocatorEx old_alloc;
1014 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1015
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001016 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +01001017
1018 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1019
1020 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001021 Py_FatalError("Can't initialize threads for interpreter");
Victor Stinner5d926472018-03-06 14:31:37 +01001022 }
1023
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001024 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001025 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
1026 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
1027 Py_FatalError("Could not allocate TSS entry");
1028 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001029
Charles-François Natalia233df82011-11-22 19:49:51 +01001030 /* If the thread had an associated auto thread state, reassociate it with
1031 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001032 if (tstate &&
1033 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
1034 {
1035 Py_FatalError("Couldn't create autoTSSkey mapping");
1036 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +02001037}
1038
Michael W. Hudson188d4362005-06-20 16:52:57 +00001039/* When a thread state is created for a thread by some mechanism other than
1040 PyGILState_Ensure, it's important that the GILState machinery knows about
1041 it so it doesn't try to create another thread state for the thread (this is
1042 a better fix for SF bug #1010677 than the first one attempted).
1043*/
Thomas Wouters89f507f2006-12-13 04:49:30 +00001044static void
Michael W. Hudson188d4362005-06-20 16:52:57 +00001045_PyGILState_NoteThreadState(PyThreadState* tstate)
1046{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001047 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +00001048 threadstate created in Py_Initialize(). Don't do anything for now
1049 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001050 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001052
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001053 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 The only situation where you can legitimately have more than one
1056 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +01001057 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001058
Victor Stinner590cebe2013-12-13 11:08:56 +01001059 You shouldn't really be using the PyGILState_ APIs anyway (see issues
1060 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +00001061
Victor Stinner590cebe2013-12-13 11:08:56 +01001062 The first thread state created for that given OS level thread will
1063 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001065 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
1066 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1067 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001068 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001069 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001070 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001071 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 /* PyGILState_Release must not try to delete this thread state. */
1074 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001075}
1076
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001077/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001078PyThreadState *
1079PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001080{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001081 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001083 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001084}
1085
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001086int
1087PyGILState_Check(void)
1088{
Victor Stinner8a1be612016-03-14 22:07:55 +01001089 PyThreadState *tstate;
1090
1091 if (!_PyGILState_check_enabled)
1092 return 1;
1093
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001094 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001095 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001096 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001097
Victor Stinner50b48572018-11-01 01:51:40 +01001098 tstate = _PyThreadState_GET();
Victor Stinner8a1be612016-03-14 22:07:55 +01001099 if (tstate == NULL)
1100 return 0;
1101
1102 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001103}
1104
Tim Peters19717fa2004-10-09 17:38:29 +00001105PyGILState_STATE
1106PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 int current;
1109 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001110 int need_init_threads = 0;
1111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 /* Note that we do not auto-init Python here - apart from
1113 potential races with 2 threads auto-initializing, pep-311
1114 spells out other issues. Embedders are expected to have
1115 called Py_Initialize() and usually PyEval_InitThreads().
1116 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001117 /* Py_Initialize() hasn't been called! */
1118 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001119
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001120 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001122 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001124 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001125 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 if (tcur == NULL)
1127 Py_FatalError("Couldn't create thread-state for new thread");
1128 /* This is our thread state! We'll need to delete it in the
1129 matching call to PyGILState_Release(). */
1130 tcur->gilstate_counter = 0;
1131 current = 0; /* new thread state is never current */
1132 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001133 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001135 }
1136
1137 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001139 }
1140
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 /* Update our counter in the thread-state - no need for locks:
1142 - tcur will remain valid as we hold the GIL.
1143 - the counter is safe as we are the only thread "allowed"
1144 to modify this value
1145 */
1146 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001147
1148 if (need_init_threads) {
1149 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1150 called from a new thread for the first time, we need the create the
1151 GIL. */
1152 PyEval_InitThreads();
1153 }
1154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001155 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001156}
1157
Tim Peters19717fa2004-10-09 17:38:29 +00001158void
1159PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001160{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001161 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1162 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 if (tcur == NULL)
1164 Py_FatalError("auto-releasing thread-state, "
1165 "but no thread-state for this thread");
1166 /* We must hold the GIL and have our thread state current */
1167 /* XXX - remove the check - the assert should be fine,
1168 but while this is very new (April 2003), the extra check
1169 by release-only users can't hurt.
1170 */
1171 if (! PyThreadState_IsCurrent(tcur))
1172 Py_FatalError("This thread state must be current when releasing");
1173 assert(PyThreadState_IsCurrent(tcur));
1174 --tcur->gilstate_counter;
1175 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 /* If we're going to destroy this thread-state, we must
1178 * clear it while the GIL is held, as destructors may run.
1179 */
1180 if (tcur->gilstate_counter == 0) {
1181 /* can't have been locked when we created it */
1182 assert(oldstate == PyGILState_UNLOCKED);
1183 PyThreadState_Clear(tcur);
1184 /* Delete the thread-state. Note this releases the GIL too!
1185 * It's vital that the GIL be held here, to avoid shutdown
1186 * races; see bugs 225673 and 1061968 (that nasty bug has a
1187 * habit of coming back).
1188 */
1189 PyThreadState_DeleteCurrent();
1190 }
1191 /* Release the lock if necessary */
1192 else if (oldstate == PyGILState_UNLOCKED)
1193 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001194}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001195
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001196
Eric Snow7f8bfc92018-01-29 18:23:44 -07001197/**************************/
1198/* cross-interpreter data */
1199/**************************/
1200
1201/* cross-interpreter data */
1202
1203crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1204
1205/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1206 to keep the registry code separate. */
1207static crossinterpdatafunc
1208_lookup_getdata(PyObject *obj)
1209{
1210 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1211 if (getdata == NULL && PyErr_Occurred() == 0)
1212 PyErr_Format(PyExc_ValueError,
1213 "%S does not support cross-interpreter data", obj);
1214 return getdata;
1215}
1216
1217int
1218_PyObject_CheckCrossInterpreterData(PyObject *obj)
1219{
1220 crossinterpdatafunc getdata = _lookup_getdata(obj);
1221 if (getdata == NULL) {
1222 return -1;
1223 }
1224 return 0;
1225}
1226
1227static int
1228_check_xidata(_PyCrossInterpreterData *data)
1229{
1230 // data->data can be anything, including NULL, so we don't check it.
1231
1232 // data->obj may be NULL, so we don't check it.
1233
1234 if (data->interp < 0) {
1235 PyErr_SetString(PyExc_SystemError, "missing interp");
1236 return -1;
1237 }
1238
1239 if (data->new_object == NULL) {
1240 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1241 return -1;
1242 }
1243
1244 // data->free may be NULL, so we don't check it.
1245
1246 return 0;
1247}
1248
1249int
1250_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1251{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001252 // _PyInterpreterState_Get() aborts if lookup fails, so we don't need
Eric Snow7f8bfc92018-01-29 18:23:44 -07001253 // to check the result for NULL.
Victor Stinnercaba55b2018-08-03 15:33:52 +02001254 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow7f8bfc92018-01-29 18:23:44 -07001255
1256 // Reset data before re-populating.
1257 *data = (_PyCrossInterpreterData){0};
1258 data->free = PyMem_RawFree; // Set a default that may be overridden.
1259
1260 // Call the "getdata" func for the object.
1261 Py_INCREF(obj);
1262 crossinterpdatafunc getdata = _lookup_getdata(obj);
1263 if (getdata == NULL) {
1264 Py_DECREF(obj);
1265 return -1;
1266 }
1267 int res = getdata(obj, data);
1268 Py_DECREF(obj);
1269 if (res != 0) {
1270 return -1;
1271 }
1272
1273 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001274 data->interp = interp->id;
1275 if (_check_xidata(data) != 0) {
1276 _PyCrossInterpreterData_Release(data);
1277 return -1;
1278 }
1279
1280 return 0;
1281}
1282
Eric Snow63799132018-06-01 18:45:20 -06001283static void
1284_release_xidata(void *arg)
1285{
1286 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1287 if (data->free != NULL) {
1288 data->free(data->data);
1289 }
1290 Py_XDECREF(data->obj);
1291}
1292
1293static void
1294_call_in_interpreter(PyInterpreterState *interp,
1295 void (*func)(void *), void *arg)
1296{
1297 /* We would use Py_AddPendingCall() if it weren't specific to the
1298 * main interpreter (see bpo-33608). In the meantime we take a
1299 * naive approach.
1300 */
1301 PyThreadState *save_tstate = NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001302 if (interp != _PyInterpreterState_Get()) {
Eric Snow63799132018-06-01 18:45:20 -06001303 // XXX Using the "head" thread isn't strictly correct.
1304 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1305 // XXX Possible GILState issues?
1306 save_tstate = PyThreadState_Swap(tstate);
1307 }
1308
1309 func(arg);
1310
1311 // Switch back.
1312 if (save_tstate != NULL) {
1313 PyThreadState_Swap(save_tstate);
1314 }
1315}
1316
Eric Snow7f8bfc92018-01-29 18:23:44 -07001317void
1318_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1319{
1320 if (data->data == NULL && data->obj == NULL) {
1321 // Nothing to release!
1322 return;
1323 }
1324
1325 // Switch to the original interpreter.
1326 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1327 if (interp == NULL) {
1328 // The intepreter was already destroyed.
1329 if (data->free != NULL) {
1330 // XXX Someone leaked some memory...
1331 }
1332 return;
1333 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001334
Eric Snow7f8bfc92018-01-29 18:23:44 -07001335 // "Release" the data and/or the object.
Eric Snowef4ac962019-02-24 15:40:47 -08001336 // XXX Use _Py_AddPendingCall().
Eric Snow63799132018-06-01 18:45:20 -06001337 _call_in_interpreter(interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001338}
1339
1340PyObject *
1341_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1342{
1343 return data->new_object(data);
1344}
1345
1346/* registry of {type -> crossinterpdatafunc} */
1347
1348/* For now we use a global registry of shareable classes. An
1349 alternative would be to add a tp_* slot for a class's
1350 crossinterpdatafunc. It would be simpler and more efficient. */
1351
1352static int
1353_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1354{
1355 // Note that we effectively replace already registered classes
1356 // rather than failing.
1357 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1358 if (newhead == NULL)
1359 return -1;
1360 newhead->cls = cls;
1361 newhead->getdata = getdata;
1362 newhead->next = _PyRuntime.xidregistry.head;
1363 _PyRuntime.xidregistry.head = newhead;
1364 return 0;
1365}
1366
1367static void _register_builtins_for_crossinterpreter_data(void);
1368
1369int
1370_PyCrossInterpreterData_Register_Class(PyTypeObject *cls,
1371 crossinterpdatafunc getdata)
1372{
1373 if (!PyType_Check(cls)) {
1374 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1375 return -1;
1376 }
1377 if (getdata == NULL) {
1378 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1379 return -1;
1380 }
1381
1382 // Make sure the class isn't ever deallocated.
1383 Py_INCREF((PyObject *)cls);
1384
1385 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1386 if (_PyRuntime.xidregistry.head == NULL) {
1387 _register_builtins_for_crossinterpreter_data();
1388 }
1389 int res = _register_xidata(cls, getdata);
1390 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1391 return res;
1392}
1393
Eric Snow6d2cd902018-05-16 15:04:57 -04001394/* Cross-interpreter objects are looked up by exact match on the class.
1395 We can reassess this policy when we move from a global registry to a
1396 tp_* slot. */
1397
Eric Snow7f8bfc92018-01-29 18:23:44 -07001398crossinterpdatafunc
1399_PyCrossInterpreterData_Lookup(PyObject *obj)
1400{
1401 PyObject *cls = PyObject_Type(obj);
1402 crossinterpdatafunc getdata = NULL;
1403 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1404 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1405 if (cur == NULL) {
1406 _register_builtins_for_crossinterpreter_data();
1407 cur = _PyRuntime.xidregistry.head;
1408 }
1409 for(; cur != NULL; cur = cur->next) {
1410 if (cur->cls == (PyTypeObject *)cls) {
1411 getdata = cur->getdata;
1412 break;
1413 }
1414 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001415 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001416 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1417 return getdata;
1418}
1419
1420/* cross-interpreter data for builtin types */
1421
Eric Snow6d2cd902018-05-16 15:04:57 -04001422struct _shared_bytes_data {
1423 char *bytes;
1424 Py_ssize_t len;
1425};
1426
Eric Snow7f8bfc92018-01-29 18:23:44 -07001427static PyObject *
1428_new_bytes_object(_PyCrossInterpreterData *data)
1429{
Eric Snow6d2cd902018-05-16 15:04:57 -04001430 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1431 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001432}
1433
1434static int
1435_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1436{
Eric Snow6d2cd902018-05-16 15:04:57 -04001437 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1438 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1439 return -1;
1440 }
1441 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001442 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001443 data->obj = obj; // Will be "released" (decref'ed) when data released.
1444 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001445 data->free = PyMem_Free;
1446 return 0;
1447}
1448
1449struct _shared_str_data {
1450 int kind;
1451 const void *buffer;
1452 Py_ssize_t len;
1453};
1454
1455static PyObject *
1456_new_str_object(_PyCrossInterpreterData *data)
1457{
1458 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1459 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1460}
1461
1462static int
1463_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1464{
1465 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1466 shared->kind = PyUnicode_KIND(obj);
1467 shared->buffer = PyUnicode_DATA(obj);
1468 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1469 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001470 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001471 data->obj = obj; // Will be "released" (decref'ed) when data released.
1472 data->new_object = _new_str_object;
1473 data->free = PyMem_Free;
1474 return 0;
1475}
1476
1477static PyObject *
1478_new_long_object(_PyCrossInterpreterData *data)
1479{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001480 return PyLong_FromSsize_t((Py_ssize_t)(data->data));
Eric Snow6d2cd902018-05-16 15:04:57 -04001481}
1482
1483static int
1484_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1485{
Alexey Izbyshev16f842d2019-02-12 19:06:43 +03001486 /* Note that this means the size of shareable ints is bounded by
1487 * sys.maxsize. Hence on 32-bit architectures that is half the
1488 * size of maximum shareable ints on 64-bit.
1489 */
1490 Py_ssize_t value = PyLong_AsSsize_t(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001491 if (value == -1 && PyErr_Occurred()) {
1492 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1493 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1494 }
1495 return -1;
1496 }
1497 data->data = (void *)value;
1498 data->obj = NULL;
1499 data->new_object = _new_long_object;
1500 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001501 return 0;
1502}
1503
1504static PyObject *
1505_new_none_object(_PyCrossInterpreterData *data)
1506{
1507 // XXX Singleton refcounts are problematic across interpreters...
1508 Py_INCREF(Py_None);
1509 return Py_None;
1510}
1511
1512static int
1513_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1514{
1515 data->data = NULL;
1516 // data->obj remains NULL
1517 data->new_object = _new_none_object;
1518 data->free = NULL; // There is nothing to free.
1519 return 0;
1520}
1521
1522static void
1523_register_builtins_for_crossinterpreter_data(void)
1524{
1525 // None
1526 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1527 Py_FatalError("could not register None for cross-interpreter sharing");
1528 }
1529
Eric Snow6d2cd902018-05-16 15:04:57 -04001530 // int
1531 if (_register_xidata(&PyLong_Type, _long_shared) != 0) {
1532 Py_FatalError("could not register int for cross-interpreter sharing");
1533 }
1534
Eric Snow7f8bfc92018-01-29 18:23:44 -07001535 // bytes
1536 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1537 Py_FatalError("could not register bytes for cross-interpreter sharing");
1538 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001539
1540 // str
1541 if (_register_xidata(&PyUnicode_Type, _str_shared) != 0) {
1542 Py_FatalError("could not register str for cross-interpreter sharing");
1543 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001544}
1545
1546
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001547#ifdef __cplusplus
1548}
1549#endif