blob: e8d390dfcfb4c696549f239d9ac4b3f02fbc4831 [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"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06005#include "internal/pystate.h"
Guido van Rossuma027efa1997-05-05 20:56:21 +00006
Victor Stinnerb02ef712016-01-22 14:09:55 +01007#define GET_TSTATE() \
8 ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current))
9#define SET_TSTATE(value) \
Benjamin Petersonca470632016-09-06 13:47:26 -070010 _Py_atomic_store_relaxed(&_PyThreadState_Current, (uintptr_t)(value))
Victor Stinnerb02ef712016-01-22 14:09:55 +010011#define GET_INTERP_STATE() \
12 (GET_TSTATE()->interp)
13
Victor Stinnerbfd316e2016-01-20 11:12:38 +010014
Tim Peters84705582004-10-10 02:47:33 +000015/* --------------------------------------------------------------------------
16CAUTION
17
Victor Stinner1a7425f2013-07-07 16:25:15 +020018Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
19number of these functions are advertised as safe to call when the GIL isn't
20held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
21debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
22to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000023-------------------------------------------------------------------------- */
24
Martin v. Löwisf0473d52001-07-18 16:17:16 +000025#ifdef HAVE_DLOPEN
26#ifdef HAVE_DLFCN_H
27#include <dlfcn.h>
28#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030029#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000030#define RTLD_LAZY 1
31#endif
32#endif
33
Benjamin Peterson43162b82012-04-13 11:58:27 -040034#ifdef __cplusplus
35extern "C" {
36#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000037
Victor Stinner5d39e042017-11-29 17:20:38 +010038static _PyInitError
39_PyRuntimeState_Init_impl(_PyRuntimeState *runtime)
Eric Snow2ebc5ce2017-09-07 23:51:28 -060040{
41 memset(runtime, 0, sizeof(*runtime));
Victor Stinner8a1be612016-03-14 22:07:55 +010042
Eric Snow2ebc5ce2017-09-07 23:51:28 -060043 _PyGC_Initialize(&runtime->gc);
44 _PyEval_Initialize(&runtime->ceval);
Michael W. Hudson188d4362005-06-20 16:52:57 +000045
Eric Snow2ebc5ce2017-09-07 23:51:28 -060046 runtime->gilstate.check_enabled = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080047
Masayuki Yamamoto731e1892017-10-06 19:41:34 +090048 /* A TSS key must be initialized with Py_tss_NEEDS_INIT
49 in accordance with the specification. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080050 Py_tss_t initial = Py_tss_NEEDS_INIT;
51 runtime->gilstate.autoTSSkey = initial;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000052
Eric Snow2ebc5ce2017-09-07 23:51:28 -060053 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnerf7e5b562017-11-15 15:48:08 -080054 if (runtime->interpreters.mutex == NULL) {
55 return _Py_INIT_ERR("Can't initialize threads for interpreter");
56 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060057 runtime->interpreters.next_id = -1;
Eric Snow7f8bfc92018-01-29 18:23:44 -070058
59 runtime->xidregistry.mutex = PyThread_allocate_lock();
60 if (runtime->xidregistry.mutex == NULL) {
61 return _Py_INIT_ERR("Can't initialize threads for cross-interpreter data registry");
62 }
63
Victor Stinnerf7e5b562017-11-15 15:48:08 -080064 return _Py_INIT_OK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -060065}
Eric Snow05351c12017-09-05 21:43:08 -070066
Victor Stinner5d39e042017-11-29 17:20:38 +010067_PyInitError
68_PyRuntimeState_Init(_PyRuntimeState *runtime)
69{
70 /* Force default allocator, since _PyRuntimeState_Fini() must
71 use the same allocator than this function. */
72 PyMemAllocatorEx old_alloc;
73 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
74
75 _PyInitError err = _PyRuntimeState_Init_impl(runtime);
76
77 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
78 return err;
79}
80
Eric Snow2ebc5ce2017-09-07 23:51:28 -060081void
82_PyRuntimeState_Fini(_PyRuntimeState *runtime)
83{
Victor Stinner5d39e042017-11-29 17:20:38 +010084 /* Force the allocator used by _PyRuntimeState_Init(). */
85 PyMemAllocatorEx old_alloc;
86 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Victor Stinnerccb04422017-11-16 03:20:31 -080087
Eric Snow2ebc5ce2017-09-07 23:51:28 -060088 if (runtime->interpreters.mutex != NULL) {
89 PyThread_free_lock(runtime->interpreters.mutex);
90 runtime->interpreters.mutex = NULL;
91 }
Victor Stinnerccb04422017-11-16 03:20:31 -080092
93 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060094}
95
96#define HEAD_LOCK() PyThread_acquire_lock(_PyRuntime.interpreters.mutex, \
97 WAIT_LOCK)
98#define HEAD_UNLOCK() PyThread_release_lock(_PyRuntime.interpreters.mutex)
Eric Snow05351c12017-09-05 21:43:08 -070099
Michael W. Hudson188d4362005-06-20 16:52:57 +0000100static void _PyGILState_NoteThreadState(PyThreadState* tstate);
101
Victor Stinnera7368ac2017-11-15 18:11:45 -0800102_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600103_PyInterpreterState_Enable(_PyRuntimeState *runtime)
Eric Snowe3774162017-05-22 19:46:40 -0700104{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600105 runtime->interpreters.next_id = 0;
Victor Stinner5d926472018-03-06 14:31:37 +0100106
107 /* Py_Finalize() calls _PyRuntimeState_Fini() which clears the mutex.
108 Create a new mutex if needed. */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600109 if (runtime->interpreters.mutex == NULL) {
Victor Stinner5d926472018-03-06 14:31:37 +0100110 /* Force default allocator, since _PyRuntimeState_Fini() must
111 use the same allocator than this function. */
112 PyMemAllocatorEx old_alloc;
113 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
114
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600115 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100116
117 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
118
Victor Stinnera7368ac2017-11-15 18:11:45 -0800119 if (runtime->interpreters.mutex == NULL) {
120 return _Py_INIT_ERR("Can't initialize threads for interpreter");
121 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600122 }
Victor Stinner5d926472018-03-06 14:31:37 +0100123
Victor Stinnera7368ac2017-11-15 18:11:45 -0800124 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700125}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000126
127PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000128PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000130 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200131 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000132
Victor Stinnerd4341102017-11-23 00:12:09 +0100133 if (interp == NULL) {
134 return NULL;
135 }
136
Eric Snow4c6955e2018-02-16 18:53:40 -0700137 interp->id_refcount = -1;
138 interp->id_mutex = NULL;
Victor Stinnerd4341102017-11-23 00:12:09 +0100139 interp->modules = NULL;
140 interp->modules_by_index = NULL;
141 interp->sysdict = NULL;
142 interp->builtins = NULL;
143 interp->builtins_copy = NULL;
144 interp->tstate_head = NULL;
145 interp->check_interval = 100;
146 interp->num_threads = 0;
147 interp->pythread_stacksize = 0;
148 interp->codec_search_path = NULL;
149 interp->codec_search_cache = NULL;
150 interp->codec_error_registry = NULL;
151 interp->codecs_initialized = 0;
152 interp->fscodec_initialized = 0;
153 interp->core_config = _PyCoreConfig_INIT;
154 interp->config = _PyMainInterpreterConfig_INIT;
155 interp->importlib = NULL;
156 interp->import_func = NULL;
157 interp->eval_frame = _PyEval_EvalFrameDefault;
158 interp->co_extra_user_count = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000159#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +0300160#if HAVE_DECL_RTLD_NOW
Victor Stinnerd4341102017-11-23 00:12:09 +0100161 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000162#else
Victor Stinnerd4341102017-11-23 00:12:09 +0100163 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000164#endif
165#endif
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200166#ifdef HAVE_FORK
Victor Stinnerd4341102017-11-23 00:12:09 +0100167 interp->before_forkers = NULL;
168 interp->after_forkers_parent = NULL;
169 interp->after_forkers_child = NULL;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200170#endif
Marcel Plch776407f2017-12-20 11:17:58 +0100171 interp->pyexitfunc = NULL;
172 interp->pyexitmodule = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000173
Victor Stinnerd4341102017-11-23 00:12:09 +0100174 HEAD_LOCK();
175 interp->next = _PyRuntime.interpreters.head;
176 if (_PyRuntime.interpreters.main == NULL) {
177 _PyRuntime.interpreters.main = interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 }
Victor Stinnerd4341102017-11-23 00:12:09 +0100179 _PyRuntime.interpreters.head = interp;
180 if (_PyRuntime.interpreters.next_id < 0) {
181 /* overflow or Py_Initialize() not called! */
182 PyErr_SetString(PyExc_RuntimeError,
183 "failed to get an interpreter ID");
Eric Snow7f8bfc92018-01-29 18:23:44 -0700184 /* XXX deallocate! */
Victor Stinnerd4341102017-11-23 00:12:09 +0100185 interp = NULL;
186 } else {
187 interp->id = _PyRuntime.interpreters.next_id;
188 _PyRuntime.interpreters.next_id += 1;
189 }
190 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000191
Yury Selivanovf23746a2018-01-22 19:11:18 -0500192 interp->tstate_next_unique_id = 0;
193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000195}
196
197
198void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000199PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000201 PyThreadState *p;
202 HEAD_LOCK();
203 for (p = interp->tstate_head; p != NULL; p = p->next)
204 PyThreadState_Clear(p);
205 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100206 _PyCoreConfig_Clear(&interp->core_config);
207 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 Py_CLEAR(interp->codec_search_path);
209 Py_CLEAR(interp->codec_search_cache);
210 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700211 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 Py_CLEAR(interp->sysdict);
214 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200215 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400216 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300217 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200218#ifdef HAVE_FORK
219 Py_CLEAR(interp->before_forkers);
220 Py_CLEAR(interp->after_forkers_parent);
221 Py_CLEAR(interp->after_forkers_child);
222#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000223}
224
225
226static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000227zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 PyThreadState *p;
230 /* No need to lock the mutex here because this should only happen
231 when the threads are all really dead (XXX famous last words). */
232 while ((p = interp->tstate_head) != NULL) {
233 PyThreadState_Delete(p);
234 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000235}
236
237
238void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000239PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 PyInterpreterState **p;
242 zapthreads(interp);
243 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600244 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 if (*p == NULL)
246 Py_FatalError(
247 "PyInterpreterState_Delete: invalid interp");
248 if (*p == interp)
249 break;
250 }
251 if (interp->tstate_head != NULL)
252 Py_FatalError("PyInterpreterState_Delete: remaining threads");
253 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600254 if (_PyRuntime.interpreters.main == interp) {
255 _PyRuntime.interpreters.main = NULL;
256 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700257 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
258 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 HEAD_UNLOCK();
Eric Snow4c6955e2018-02-16 18:53:40 -0700260 if (interp->id_mutex != NULL) {
261 PyThread_free_lock(interp->id_mutex);
262 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200263 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000264}
265
266
Eric Snowe3774162017-05-22 19:46:40 -0700267int64_t
268PyInterpreterState_GetID(PyInterpreterState *interp)
269{
270 if (interp == NULL) {
271 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
272 return -1;
273 }
274 return interp->id;
275}
276
277
Eric Snow7f8bfc92018-01-29 18:23:44 -0700278PyInterpreterState *
279_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
280{
281 if (requested_id < 0)
282 goto error;
283
284 PyInterpreterState *interp = PyInterpreterState_Head();
285 while (interp != NULL) {
286 PY_INT64_T id = PyInterpreterState_GetID(interp);
287 if (id < 0)
288 return NULL;
289 if (requested_id == id)
290 return interp;
291 interp = PyInterpreterState_Next(interp);
292 }
293
294error:
295 PyErr_Format(PyExc_RuntimeError,
296 "unrecognized interpreter ID %lld", requested_id);
297 return NULL;
298}
299
Eric Snow4c6955e2018-02-16 18:53:40 -0700300
301int
302_PyInterpreterState_IDInitref(PyInterpreterState *interp)
303{
304 if (interp->id_mutex != NULL) {
305 return 0;
306 }
307 interp->id_mutex = PyThread_allocate_lock();
308 if (interp->id_mutex == NULL) {
309 PyErr_SetString(PyExc_RuntimeError,
310 "failed to create init interpreter ID mutex");
311 return -1;
312 }
313 interp->id_refcount = 0;
314 return 0;
315}
316
317
318void
319_PyInterpreterState_IDIncref(PyInterpreterState *interp)
320{
321 if (interp->id_mutex == NULL) {
322 return;
323 }
324 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
325 interp->id_refcount += 1;
326 PyThread_release_lock(interp->id_mutex);
327}
328
329
330void
331_PyInterpreterState_IDDecref(PyInterpreterState *interp)
332{
333 if (interp->id_mutex == NULL) {
334 return;
335 }
336 PyThread_acquire_lock(interp->id_mutex, WAIT_LOCK);
337 assert(interp->id_refcount != 0);
338 interp->id_refcount -= 1;
339 int64_t refcount = interp->id_refcount;
340 PyThread_release_lock(interp->id_mutex);
341
342 if (refcount == 0) {
Eric Snowf53d9f22018-02-20 16:30:17 -0700343 // XXX Using the "head" thread isn't strictly correct.
344 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
345 // XXX Possible GILState issues?
346 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
Eric Snow4c6955e2018-02-16 18:53:40 -0700347 Py_EndInterpreter(tstate);
348 PyThreadState_Swap(save_tstate);
349 }
350}
351
352
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000353/* Default implementation for _PyThreadState_GetFrame */
354static struct _frame *
355threadstate_getframe(PyThreadState *self)
356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000358}
359
Victor Stinner45b9be52010-03-03 23:28:07 +0000360static PyThreadState *
361new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000362{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200363 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (_PyThreadState_GetFrame == NULL)
366 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (tstate != NULL) {
369 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 tstate->frame = NULL;
372 tstate->recursion_depth = 0;
373 tstate->overflowed = 0;
374 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700375 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 tstate->tracing = 0;
377 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 tstate->gilstate_counter = 0;
379 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 tstate->curexc_type = NULL;
385 tstate->curexc_value = NULL;
386 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000387
Mark Shannonae3087c2017-10-22 22:41:51 +0100388 tstate->exc_state.exc_type = NULL;
389 tstate->exc_state.exc_value = NULL;
390 tstate->exc_state.exc_traceback = NULL;
391 tstate->exc_state.previous_item = NULL;
392 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 tstate->c_profilefunc = NULL;
395 tstate->c_tracefunc = NULL;
396 tstate->c_profileobj = NULL;
397 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000398
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200399 tstate->trash_delete_nesting = 0;
400 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200401 tstate->on_delete = NULL;
402 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200403
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800404 tstate->coroutine_origin_tracking_depth = 0;
405
Yury Selivanov75445082015-05-11 22:57:16 -0400406 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400407 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400408
Yury Selivanoveb636452016-09-08 22:01:51 -0700409 tstate->async_gen_firstiter = NULL;
410 tstate->async_gen_finalizer = NULL;
411
Yury Selivanovf23746a2018-01-22 19:11:18 -0500412 tstate->context = NULL;
413 tstate->context_ver = 1;
414
415 tstate->id = ++interp->tstate_next_unique_id;
416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (init)
418 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200421 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200423 if (tstate->next)
424 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 interp->tstate_head = tstate;
426 HEAD_UNLOCK();
427 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000430}
431
Victor Stinner45b9be52010-03-03 23:28:07 +0000432PyThreadState *
433PyThreadState_New(PyInterpreterState *interp)
434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000436}
437
438PyThreadState *
439_PyThreadState_Prealloc(PyInterpreterState *interp)
440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000442}
443
444void
445_PyThreadState_Init(PyThreadState *tstate)
446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000448}
449
Martin v. Löwis1a214512008-06-11 05:26:20 +0000450PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200451PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000452{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200453 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100454 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000456 if (module->m_slots) {
457 return NULL;
458 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (index == 0)
460 return NULL;
461 if (state->modules_by_index == NULL)
462 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200463 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 return NULL;
465 res = PyList_GET_ITEM(state->modules_by_index, index);
466 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000467}
468
469int
470_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
471{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000472 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300473 if (!def) {
474 assert(PyErr_Occurred());
475 return -1;
476 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000477 if (def->m_slots) {
478 PyErr_SetString(PyExc_SystemError,
479 "PyState_AddModule called on module with slots");
480 return -1;
481 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100482 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 if (!state->modules_by_index) {
484 state->modules_by_index = PyList_New(0);
485 if (!state->modules_by_index)
486 return -1;
487 }
488 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
489 if (PyList_Append(state->modules_by_index, Py_None) < 0)
490 return -1;
491 Py_INCREF(module);
492 return PyList_SetItem(state->modules_by_index,
493 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000494}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000495
Martin v. Löwis7800f752012-06-22 12:20:55 +0200496int
497PyState_AddModule(PyObject* module, struct PyModuleDef* def)
498{
499 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100500 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200501 if (!def) {
502 Py_FatalError("PyState_AddModule: Module Definition is NULL");
503 return -1;
504 }
505 index = def->m_base.m_index;
506 if (state->modules_by_index) {
507 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
508 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
509 Py_FatalError("PyState_AddModule: Module already added!");
510 return -1;
511 }
512 }
513 }
514 return _PyState_AddModule(module, def);
515}
516
517int
518PyState_RemoveModule(struct PyModuleDef* def)
519{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000520 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200521 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000522 if (def->m_slots) {
523 PyErr_SetString(PyExc_SystemError,
524 "PyState_RemoveModule called on module with slots");
525 return -1;
526 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100527 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200528 if (index == 0) {
529 Py_FatalError("PyState_RemoveModule: Module index invalid.");
530 return -1;
531 }
532 if (state->modules_by_index == NULL) {
533 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
534 return -1;
535 }
536 if (index > PyList_GET_SIZE(state->modules_by_index)) {
537 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
538 return -1;
539 }
540 return PyList_SetItem(state->modules_by_index, index, Py_None);
541}
542
Antoine Pitrou40322e62013-08-11 00:30:09 +0200543/* used by import.c:PyImport_Cleanup */
544void
545_PyState_ClearModules(void)
546{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100547 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200548 if (state->modules_by_index) {
549 Py_ssize_t i;
550 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
551 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
552 if (PyModule_Check(m)) {
553 /* cleanup the saved copy of module dicts */
554 PyModuleDef *md = PyModule_GetDef(m);
555 if (md)
556 Py_CLEAR(md->m_base.m_copy);
557 }
558 }
559 /* Setting modules_by_index to NULL could be dangerous, so we
560 clear the list instead. */
561 if (PyList_SetSlice(state->modules_by_index,
562 0, PyList_GET_SIZE(state->modules_by_index),
563 NULL))
564 PyErr_WriteUnraisable(state->modules_by_index);
565 }
566}
567
Guido van Rossuma027efa1997-05-05 20:56:21 +0000568void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000569PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000570{
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200571 int verbose = tstate->interp->core_config.verbose;
572
573 if (verbose && tstate->frame != NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 fprintf(stderr,
575 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 Py_CLEAR(tstate->dict);
580 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 Py_CLEAR(tstate->curexc_type);
583 Py_CLEAR(tstate->curexc_value);
584 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000585
Mark Shannonae3087c2017-10-22 22:41:51 +0100586 Py_CLEAR(tstate->exc_state.exc_type);
587 Py_CLEAR(tstate->exc_state.exc_value);
588 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300589
Mark Shannonae3087c2017-10-22 22:41:51 +0100590 /* The stack of exception states should contain just this thread. */
Victor Stinner53b7d4e2018-07-25 01:37:05 +0200591 if (verbose && tstate->exc_info != &tstate->exc_state) {
Mark Shannonae3087c2017-10-22 22:41:51 +0100592 fprintf(stderr,
593 "PyThreadState_Clear: warning: thread still has a generator\n");
594 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 tstate->c_profilefunc = NULL;
597 tstate->c_tracefunc = NULL;
598 Py_CLEAR(tstate->c_profileobj);
599 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400600
601 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700602 Py_CLEAR(tstate->async_gen_firstiter);
603 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500604
605 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000606}
607
608
Guido van Rossum29757862001-01-23 01:46:06 +0000609/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
610static void
611tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (tstate == NULL)
615 Py_FatalError("PyThreadState_Delete: NULL tstate");
616 interp = tstate->interp;
617 if (interp == NULL)
618 Py_FatalError("PyThreadState_Delete: NULL interp");
619 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200620 if (tstate->prev)
621 tstate->prev->next = tstate->next;
622 else
623 interp->tstate_head = tstate->next;
624 if (tstate->next)
625 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200627 if (tstate->on_delete != NULL) {
628 tstate->on_delete(tstate->on_delete_data);
629 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200630 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000631}
632
633
Guido van Rossum29757862001-01-23 01:46:06 +0000634void
635PyThreadState_Delete(PyThreadState *tstate)
636{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100637 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600639 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900640 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600641 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900642 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600643 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200644 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000645}
646
647
Guido van Rossum29757862001-01-23 01:46:06 +0000648void
649PyThreadState_DeleteCurrent()
650{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100651 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 if (tstate == NULL)
653 Py_FatalError(
654 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100655 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600656 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900657 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600658 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900659 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600660 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100661 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000663}
Guido van Rossum29757862001-01-23 01:46:06 +0000664
665
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200666/*
667 * Delete all thread states except the one passed as argument.
668 * Note that, if there is a current thread state, it *must* be the one
669 * passed as argument. Also, this won't touch any other interpreters
670 * than the current one, since we don't know which thread state should
671 * be kept in those other interpreteres.
672 */
673void
674_PyThreadState_DeleteExcept(PyThreadState *tstate)
675{
676 PyInterpreterState *interp = tstate->interp;
677 PyThreadState *p, *next, *garbage;
678 HEAD_LOCK();
679 /* Remove all thread states, except tstate, from the linked list of
680 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200681 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200682 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200683 if (garbage == tstate)
684 garbage = tstate->next;
685 if (tstate->prev)
686 tstate->prev->next = tstate->next;
687 if (tstate->next)
688 tstate->next->prev = tstate->prev;
689 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200690 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200691 HEAD_UNLOCK();
692 /* Clear and deallocate all stale thread states. Even if this
693 executes Python code, we should be safe since it executes
694 in the current thread, not one of the stale threads. */
695 for (p = garbage; p; p = next) {
696 next = p->next;
697 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200698 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200699 }
700}
701
702
Guido van Rossuma027efa1997-05-05 20:56:21 +0000703PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100704_PyThreadState_UncheckedGet(void)
705{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100706 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100707}
708
709
710PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000711PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000712{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100713 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 if (tstate == NULL)
715 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000716
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000718}
719
720
721PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000722PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000723{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100724 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000725
Victor Stinnerb02ef712016-01-22 14:09:55 +0100726 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000727 /* It should not be possible for more than one thread state
728 to be used for a thread. Check this the best we can in debug
729 builds.
730 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200731#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 if (newts) {
733 /* This can be called from PyEval_RestoreThread(). Similar
734 to it, we need to ensure errno doesn't change.
735 */
736 int err = errno;
737 PyThreadState *check = PyGILState_GetThisThreadState();
738 if (check && check->interp == newts->interp && check != newts)
739 Py_FatalError("Invalid thread state for this thread");
740 errno = err;
741 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000742#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000744}
Guido van Rossumede04391998-04-10 20:18:25 +0000745
746/* An extension mechanism to store arbitrary additional per-thread state.
747 PyThreadState_GetDict() returns a dictionary that can be used to hold such
748 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000749 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
750 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000751
752PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000753PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000754{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100755 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 if (tstate == NULL)
757 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 if (tstate->dict == NULL) {
760 PyObject *d;
761 tstate->dict = d = PyDict_New();
762 if (d == NULL)
763 PyErr_Clear();
764 }
765 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000766}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000767
768
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000769/* Asynchronously raise an exception in a thread.
770 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000771 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000772 to call this, or use ctypes. Must be called with the GIL held.
773 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
774 match any known thread id). Can be called with exc=NULL to clear an
775 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000776
777int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200778PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
779{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100780 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 /* Although the GIL is held, a few C API functions can be called
784 * without the GIL held, and in particular some that create and
785 * destroy thread and interpreter states. Those can mutate the
786 * list of thread states we're traversing, so to prevent that we lock
787 * head_mutex for the duration.
788 */
789 HEAD_LOCK();
790 for (p = interp->tstate_head; p != NULL; p = p->next) {
791 if (p->thread_id == id) {
792 /* Tricky: we need to decref the current value
793 * (if any) in p->async_exc, but that can in turn
794 * allow arbitrary Python code to run, including
795 * perhaps calls to this function. To prevent
796 * deadlock, we need to release head_mutex before
797 * the decref.
798 */
799 PyObject *old_exc = p->async_exc;
800 Py_XINCREF(exc);
801 p->async_exc = exc;
802 HEAD_UNLOCK();
803 Py_XDECREF(old_exc);
804 _PyEval_SignalAsyncExc();
805 return 1;
806 }
807 }
808 HEAD_UNLOCK();
809 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000810}
811
812
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000813/* Routines for advanced debuggers, requested by David Beazley.
814 Don't use unless you know what you are doing! */
815
816PyInterpreterState *
817PyInterpreterState_Head(void)
818{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600819 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000820}
821
822PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700823PyInterpreterState_Main(void)
824{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600825 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700826}
827
828PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000829PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000831}
832
833PyThreadState *
834PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000836}
837
838PyThreadState *
839PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000841}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000842
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000843/* The implementation of sys._current_frames(). This is intended to be
844 called with the GIL held, as it will be when called via
845 sys._current_frames(). It's possible it would work fine even without
846 the GIL held, but haven't thought enough about that.
847*/
848PyObject *
849_PyThread_CurrentFrames(void)
850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 PyObject *result;
852 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 result = PyDict_New();
855 if (result == NULL)
856 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000857
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 /* for i in all interpreters:
859 * for t in all of i's thread states:
860 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200861 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 * need to grab head_mutex for the duration.
863 */
864 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600865 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 PyThreadState *t;
867 for (t = i->tstate_head; t != NULL; t = t->next) {
868 PyObject *id;
869 int stat;
870 struct _frame *frame = t->frame;
871 if (frame == NULL)
872 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200873 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 if (id == NULL)
875 goto Fail;
876 stat = PyDict_SetItem(result, id, (PyObject *)frame);
877 Py_DECREF(id);
878 if (stat < 0)
879 goto Fail;
880 }
881 }
882 HEAD_UNLOCK();
883 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000884
885 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 HEAD_UNLOCK();
887 Py_DECREF(result);
888 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000889}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000890
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000891/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000892
893/* Keep this as a static, as it is not reliable! It can only
894 ever be compared to the state for the *current* thread.
895 * If not equal, then it doesn't matter that the actual
896 value may change immediately after comparison, as it can't
897 possibly change to the current thread's state.
898 * If equal, then the current thread holds the lock, so the value can't
899 change until we yield the lock.
900*/
901static int
902PyThreadState_IsCurrent(PyThreadState *tstate)
903{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 /* Must be the tstate for this thread */
905 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100906 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000907}
908
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000909/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000910 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000911*/
Tim Peters19717fa2004-10-09 17:38:29 +0000912void
913_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900916 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
917 Py_FatalError("Could not allocate TSS entry");
918 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600919 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900920 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000924}
925
Victor Stinner861d9ab2016-03-16 22:45:24 +0100926PyInterpreterState *
927_PyGILState_GetInterpreterStateUnsafe(void)
928{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600929 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100930}
931
Tim Peters19717fa2004-10-09 17:38:29 +0000932void
933_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000934{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900935 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600936 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000937}
938
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900939/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200940 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900941 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200942 */
943void
944_PyGILState_Reinit(void)
945{
Victor Stinner5d926472018-03-06 14:31:37 +0100946 /* Force default allocator, since _PyRuntimeState_Fini() must
947 use the same allocator than this function. */
948 PyMemAllocatorEx old_alloc;
949 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
950
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600951 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
Victor Stinner5d926472018-03-06 14:31:37 +0100952
953 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
954
955 if (_PyRuntime.interpreters.mutex == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600956 Py_FatalError("Can't initialize threads for interpreter");
Victor Stinner5d926472018-03-06 14:31:37 +0100957 }
958
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200959 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900960 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
961 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
962 Py_FatalError("Could not allocate TSS entry");
963 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200964
Charles-François Natalia233df82011-11-22 19:49:51 +0100965 /* If the thread had an associated auto thread state, reassociate it with
966 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900967 if (tstate &&
968 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
969 {
970 Py_FatalError("Couldn't create autoTSSkey mapping");
971 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200972}
973
Michael W. Hudson188d4362005-06-20 16:52:57 +0000974/* When a thread state is created for a thread by some mechanism other than
975 PyGILState_Ensure, it's important that the GILState machinery knows about
976 it so it doesn't try to create another thread state for the thread (this is
977 a better fix for SF bug #1010677 than the first one attempted).
978*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000979static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000980_PyGILState_NoteThreadState(PyThreadState* tstate)
981{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900982 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +0000983 threadstate created in Py_Initialize(). Don't do anything for now
984 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600985 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000987
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900988 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 The only situation where you can legitimately have more than one
991 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100992 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000993
Victor Stinner590cebe2013-12-13 11:08:56 +0100994 You shouldn't really be using the PyGILState_ APIs anyway (see issues
995 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000996
Victor Stinner590cebe2013-12-13 11:08:56 +0100997 The first thread state created for that given OS level thread will
998 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001000 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
1001 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
1002 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001003 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001004 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001005 }
Victor Stinner590cebe2013-12-13 11:08:56 +01001006 }
Michael W. Hudson188d4362005-06-20 16:52:57 +00001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 /* PyGILState_Release must not try to delete this thread state. */
1009 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +00001010}
1011
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001012/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +00001013PyThreadState *
1014PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001015{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001016 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001018 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001019}
1020
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001021int
1022PyGILState_Check(void)
1023{
Victor Stinner8a1be612016-03-14 22:07:55 +01001024 PyThreadState *tstate;
1025
1026 if (!_PyGILState_check_enabled)
1027 return 1;
1028
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001029 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +01001030 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001031 }
Victor Stinner8a1be612016-03-14 22:07:55 +01001032
1033 tstate = GET_TSTATE();
1034 if (tstate == NULL)
1035 return 0;
1036
1037 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -07001038}
1039
Tim Peters19717fa2004-10-09 17:38:29 +00001040PyGILState_STATE
1041PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 int current;
1044 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001045 int need_init_threads = 0;
1046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 /* Note that we do not auto-init Python here - apart from
1048 potential races with 2 threads auto-initializing, pep-311
1049 spells out other issues. Embedders are expected to have
1050 called Py_Initialize() and usually PyEval_InitThreads().
1051 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001052 /* Py_Initialize() hasn't been called! */
1053 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001054
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001055 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001057 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +01001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001060 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 if (tcur == NULL)
1062 Py_FatalError("Couldn't create thread-state for new thread");
1063 /* This is our thread state! We'll need to delete it in the
1064 matching call to PyGILState_Release(). */
1065 tcur->gilstate_counter = 0;
1066 current = 0; /* new thread state is never current */
1067 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001068 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001070 }
1071
1072 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001074 }
1075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 /* Update our counter in the thread-state - no need for locks:
1077 - tcur will remain valid as we hold the GIL.
1078 - the counter is safe as we are the only thread "allowed"
1079 to modify this value
1080 */
1081 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001082
1083 if (need_init_threads) {
1084 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1085 called from a new thread for the first time, we need the create the
1086 GIL. */
1087 PyEval_InitThreads();
1088 }
1089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001091}
1092
Tim Peters19717fa2004-10-09 17:38:29 +00001093void
1094PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001095{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001096 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1097 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 if (tcur == NULL)
1099 Py_FatalError("auto-releasing thread-state, "
1100 "but no thread-state for this thread");
1101 /* We must hold the GIL and have our thread state current */
1102 /* XXX - remove the check - the assert should be fine,
1103 but while this is very new (April 2003), the extra check
1104 by release-only users can't hurt.
1105 */
1106 if (! PyThreadState_IsCurrent(tcur))
1107 Py_FatalError("This thread state must be current when releasing");
1108 assert(PyThreadState_IsCurrent(tcur));
1109 --tcur->gilstate_counter;
1110 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 /* If we're going to destroy this thread-state, we must
1113 * clear it while the GIL is held, as destructors may run.
1114 */
1115 if (tcur->gilstate_counter == 0) {
1116 /* can't have been locked when we created it */
1117 assert(oldstate == PyGILState_UNLOCKED);
1118 PyThreadState_Clear(tcur);
1119 /* Delete the thread-state. Note this releases the GIL too!
1120 * It's vital that the GIL be held here, to avoid shutdown
1121 * races; see bugs 225673 and 1061968 (that nasty bug has a
1122 * habit of coming back).
1123 */
1124 PyThreadState_DeleteCurrent();
1125 }
1126 /* Release the lock if necessary */
1127 else if (oldstate == PyGILState_UNLOCKED)
1128 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001129}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001130
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001131
Eric Snow7f8bfc92018-01-29 18:23:44 -07001132/**************************/
1133/* cross-interpreter data */
1134/**************************/
1135
1136/* cross-interpreter data */
1137
1138crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1139
1140/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1141 to keep the registry code separate. */
1142static crossinterpdatafunc
1143_lookup_getdata(PyObject *obj)
1144{
1145 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1146 if (getdata == NULL && PyErr_Occurred() == 0)
1147 PyErr_Format(PyExc_ValueError,
1148 "%S does not support cross-interpreter data", obj);
1149 return getdata;
1150}
1151
1152int
1153_PyObject_CheckCrossInterpreterData(PyObject *obj)
1154{
1155 crossinterpdatafunc getdata = _lookup_getdata(obj);
1156 if (getdata == NULL) {
1157 return -1;
1158 }
1159 return 0;
1160}
1161
1162static int
1163_check_xidata(_PyCrossInterpreterData *data)
1164{
1165 // data->data can be anything, including NULL, so we don't check it.
1166
1167 // data->obj may be NULL, so we don't check it.
1168
1169 if (data->interp < 0) {
1170 PyErr_SetString(PyExc_SystemError, "missing interp");
1171 return -1;
1172 }
1173
1174 if (data->new_object == NULL) {
1175 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1176 return -1;
1177 }
1178
1179 // data->free may be NULL, so we don't check it.
1180
1181 return 0;
1182}
1183
1184int
1185_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1186{
1187 PyThreadState *tstate = PyThreadState_Get();
1188 // PyThreadState_Get() aborts if lookup fails, so we don't need
1189 // to check the result for NULL.
1190 PyInterpreterState *interp = tstate->interp;
1191
1192 // Reset data before re-populating.
1193 *data = (_PyCrossInterpreterData){0};
1194 data->free = PyMem_RawFree; // Set a default that may be overridden.
1195
1196 // Call the "getdata" func for the object.
1197 Py_INCREF(obj);
1198 crossinterpdatafunc getdata = _lookup_getdata(obj);
1199 if (getdata == NULL) {
1200 Py_DECREF(obj);
1201 return -1;
1202 }
1203 int res = getdata(obj, data);
1204 Py_DECREF(obj);
1205 if (res != 0) {
1206 return -1;
1207 }
1208
1209 // Fill in the blanks and validate the result.
Eric Snow7f8bfc92018-01-29 18:23:44 -07001210 data->interp = interp->id;
1211 if (_check_xidata(data) != 0) {
1212 _PyCrossInterpreterData_Release(data);
1213 return -1;
1214 }
1215
1216 return 0;
1217}
1218
Eric Snow63799132018-06-01 18:45:20 -06001219static void
1220_release_xidata(void *arg)
1221{
1222 _PyCrossInterpreterData *data = (_PyCrossInterpreterData *)arg;
1223 if (data->free != NULL) {
1224 data->free(data->data);
1225 }
1226 Py_XDECREF(data->obj);
1227}
1228
1229static void
1230_call_in_interpreter(PyInterpreterState *interp,
1231 void (*func)(void *), void *arg)
1232{
1233 /* We would use Py_AddPendingCall() if it weren't specific to the
1234 * main interpreter (see bpo-33608). In the meantime we take a
1235 * naive approach.
1236 */
1237 PyThreadState *save_tstate = NULL;
1238 if (interp != PyThreadState_Get()->interp) {
1239 // XXX Using the "head" thread isn't strictly correct.
1240 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1241 // XXX Possible GILState issues?
1242 save_tstate = PyThreadState_Swap(tstate);
1243 }
1244
1245 func(arg);
1246
1247 // Switch back.
1248 if (save_tstate != NULL) {
1249 PyThreadState_Swap(save_tstate);
1250 }
1251}
1252
Eric Snow7f8bfc92018-01-29 18:23:44 -07001253void
1254_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1255{
1256 if (data->data == NULL && data->obj == NULL) {
1257 // Nothing to release!
1258 return;
1259 }
1260
1261 // Switch to the original interpreter.
1262 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1263 if (interp == NULL) {
1264 // The intepreter was already destroyed.
1265 if (data->free != NULL) {
1266 // XXX Someone leaked some memory...
1267 }
1268 return;
1269 }
Eric Snowf53d9f22018-02-20 16:30:17 -07001270
Eric Snow7f8bfc92018-01-29 18:23:44 -07001271 // "Release" the data and/or the object.
Eric Snow63799132018-06-01 18:45:20 -06001272 _call_in_interpreter(interp, _release_xidata, data);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001273}
1274
1275PyObject *
1276_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1277{
1278 return data->new_object(data);
1279}
1280
1281/* registry of {type -> crossinterpdatafunc} */
1282
1283/* For now we use a global registry of shareable classes. An
1284 alternative would be to add a tp_* slot for a class's
1285 crossinterpdatafunc. It would be simpler and more efficient. */
1286
1287static int
1288_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1289{
1290 // Note that we effectively replace already registered classes
1291 // rather than failing.
1292 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1293 if (newhead == NULL)
1294 return -1;
1295 newhead->cls = cls;
1296 newhead->getdata = getdata;
1297 newhead->next = _PyRuntime.xidregistry.head;
1298 _PyRuntime.xidregistry.head = newhead;
1299 return 0;
1300}
1301
1302static void _register_builtins_for_crossinterpreter_data(void);
1303
1304int
1305_PyCrossInterpreterData_Register_Class(PyTypeObject *cls,
1306 crossinterpdatafunc getdata)
1307{
1308 if (!PyType_Check(cls)) {
1309 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1310 return -1;
1311 }
1312 if (getdata == NULL) {
1313 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1314 return -1;
1315 }
1316
1317 // Make sure the class isn't ever deallocated.
1318 Py_INCREF((PyObject *)cls);
1319
1320 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1321 if (_PyRuntime.xidregistry.head == NULL) {
1322 _register_builtins_for_crossinterpreter_data();
1323 }
1324 int res = _register_xidata(cls, getdata);
1325 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1326 return res;
1327}
1328
Eric Snow6d2cd902018-05-16 15:04:57 -04001329/* Cross-interpreter objects are looked up by exact match on the class.
1330 We can reassess this policy when we move from a global registry to a
1331 tp_* slot. */
1332
Eric Snow7f8bfc92018-01-29 18:23:44 -07001333crossinterpdatafunc
1334_PyCrossInterpreterData_Lookup(PyObject *obj)
1335{
1336 PyObject *cls = PyObject_Type(obj);
1337 crossinterpdatafunc getdata = NULL;
1338 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1339 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1340 if (cur == NULL) {
1341 _register_builtins_for_crossinterpreter_data();
1342 cur = _PyRuntime.xidregistry.head;
1343 }
1344 for(; cur != NULL; cur = cur->next) {
1345 if (cur->cls == (PyTypeObject *)cls) {
1346 getdata = cur->getdata;
1347 break;
1348 }
1349 }
Eric Snow4e9da0d2018-02-02 21:49:49 -07001350 Py_DECREF(cls);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001351 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1352 return getdata;
1353}
1354
1355/* cross-interpreter data for builtin types */
1356
Eric Snow6d2cd902018-05-16 15:04:57 -04001357struct _shared_bytes_data {
1358 char *bytes;
1359 Py_ssize_t len;
1360};
1361
Eric Snow7f8bfc92018-01-29 18:23:44 -07001362static PyObject *
1363_new_bytes_object(_PyCrossInterpreterData *data)
1364{
Eric Snow6d2cd902018-05-16 15:04:57 -04001365 struct _shared_bytes_data *shared = (struct _shared_bytes_data *)(data->data);
1366 return PyBytes_FromStringAndSize(shared->bytes, shared->len);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001367}
1368
1369static int
1370_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1371{
Eric Snow6d2cd902018-05-16 15:04:57 -04001372 struct _shared_bytes_data *shared = PyMem_NEW(struct _shared_bytes_data, 1);
1373 if (PyBytes_AsStringAndSize(obj, &shared->bytes, &shared->len) < 0) {
1374 return -1;
1375 }
1376 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001377 Py_INCREF(obj);
Eric Snow7f8bfc92018-01-29 18:23:44 -07001378 data->obj = obj; // Will be "released" (decref'ed) when data released.
1379 data->new_object = _new_bytes_object;
Eric Snow6d2cd902018-05-16 15:04:57 -04001380 data->free = PyMem_Free;
1381 return 0;
1382}
1383
1384struct _shared_str_data {
1385 int kind;
1386 const void *buffer;
1387 Py_ssize_t len;
1388};
1389
1390static PyObject *
1391_new_str_object(_PyCrossInterpreterData *data)
1392{
1393 struct _shared_str_data *shared = (struct _shared_str_data *)(data->data);
1394 return PyUnicode_FromKindAndData(shared->kind, shared->buffer, shared->len);
1395}
1396
1397static int
1398_str_shared(PyObject *obj, _PyCrossInterpreterData *data)
1399{
1400 struct _shared_str_data *shared = PyMem_NEW(struct _shared_str_data, 1);
1401 shared->kind = PyUnicode_KIND(obj);
1402 shared->buffer = PyUnicode_DATA(obj);
1403 shared->len = PyUnicode_GET_LENGTH(obj) - 1;
1404 data->data = (void *)shared;
Eric Snow63799132018-06-01 18:45:20 -06001405 Py_INCREF(obj);
Eric Snow6d2cd902018-05-16 15:04:57 -04001406 data->obj = obj; // Will be "released" (decref'ed) when data released.
1407 data->new_object = _new_str_object;
1408 data->free = PyMem_Free;
1409 return 0;
1410}
1411
1412static PyObject *
1413_new_long_object(_PyCrossInterpreterData *data)
1414{
1415 return PyLong_FromLongLong((int64_t)(data->data));
1416}
1417
1418static int
1419_long_shared(PyObject *obj, _PyCrossInterpreterData *data)
1420{
1421 int64_t value = PyLong_AsLongLong(obj);
1422 if (value == -1 && PyErr_Occurred()) {
1423 if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
1424 PyErr_SetString(PyExc_OverflowError, "try sending as bytes");
1425 }
1426 return -1;
1427 }
1428 data->data = (void *)value;
1429 data->obj = NULL;
1430 data->new_object = _new_long_object;
1431 data->free = NULL;
Eric Snow7f8bfc92018-01-29 18:23:44 -07001432 return 0;
1433}
1434
1435static PyObject *
1436_new_none_object(_PyCrossInterpreterData *data)
1437{
1438 // XXX Singleton refcounts are problematic across interpreters...
1439 Py_INCREF(Py_None);
1440 return Py_None;
1441}
1442
1443static int
1444_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1445{
1446 data->data = NULL;
1447 // data->obj remains NULL
1448 data->new_object = _new_none_object;
1449 data->free = NULL; // There is nothing to free.
1450 return 0;
1451}
1452
1453static void
1454_register_builtins_for_crossinterpreter_data(void)
1455{
1456 // None
1457 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1458 Py_FatalError("could not register None for cross-interpreter sharing");
1459 }
1460
Eric Snow6d2cd902018-05-16 15:04:57 -04001461 // int
1462 if (_register_xidata(&PyLong_Type, _long_shared) != 0) {
1463 Py_FatalError("could not register int for cross-interpreter sharing");
1464 }
1465
Eric Snow7f8bfc92018-01-29 18:23:44 -07001466 // bytes
1467 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1468 Py_FatalError("could not register bytes for cross-interpreter sharing");
1469 }
Eric Snow6d2cd902018-05-16 15:04:57 -04001470
1471 // str
1472 if (_register_xidata(&PyUnicode_Type, _str_shared) != 0) {
1473 Py_FatalError("could not register str for cross-interpreter sharing");
1474 }
Eric Snow7f8bfc92018-01-29 18:23:44 -07001475}
1476
1477
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001478#ifdef __cplusplus
1479}
1480#endif