blob: a474549a8c730dc7807b6dd8723e856ca9e87756 [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;
106 /* Since we only call _PyRuntimeState_Init() once per process
107 (see _PyRuntime_Initialize()), we make sure the mutex is
108 initialized here. */
109 if (runtime->interpreters.mutex == NULL) {
110 runtime->interpreters.mutex = PyThread_allocate_lock();
Victor Stinnera7368ac2017-11-15 18:11:45 -0800111 if (runtime->interpreters.mutex == NULL) {
112 return _Py_INIT_ERR("Can't initialize threads for interpreter");
113 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600114 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800115 return _Py_INIT_OK();
Eric Snowe3774162017-05-22 19:46:40 -0700116}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000117
118PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000119PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000120{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +0200122 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123
Victor Stinnerd4341102017-11-23 00:12:09 +0100124 if (interp == NULL) {
125 return NULL;
126 }
127
128
129 interp->modules = NULL;
130 interp->modules_by_index = NULL;
131 interp->sysdict = NULL;
132 interp->builtins = NULL;
133 interp->builtins_copy = NULL;
134 interp->tstate_head = NULL;
135 interp->check_interval = 100;
136 interp->num_threads = 0;
137 interp->pythread_stacksize = 0;
138 interp->codec_search_path = NULL;
139 interp->codec_search_cache = NULL;
140 interp->codec_error_registry = NULL;
141 interp->codecs_initialized = 0;
142 interp->fscodec_initialized = 0;
143 interp->core_config = _PyCoreConfig_INIT;
144 interp->config = _PyMainInterpreterConfig_INIT;
145 interp->importlib = NULL;
146 interp->import_func = NULL;
147 interp->eval_frame = _PyEval_EvalFrameDefault;
148 interp->co_extra_user_count = 0;
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
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200156#ifdef HAVE_FORK
Victor Stinnerd4341102017-11-23 00:12:09 +0100157 interp->before_forkers = NULL;
158 interp->after_forkers_parent = NULL;
159 interp->after_forkers_child = NULL;
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200160#endif
Marcel Plch776407f2017-12-20 11:17:58 +0100161 interp->pyexitfunc = NULL;
162 interp->pyexitmodule = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000163
Victor Stinnerd4341102017-11-23 00:12:09 +0100164 HEAD_LOCK();
165 interp->next = _PyRuntime.interpreters.head;
166 if (_PyRuntime.interpreters.main == NULL) {
167 _PyRuntime.interpreters.main = interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 }
Victor Stinnerd4341102017-11-23 00:12:09 +0100169 _PyRuntime.interpreters.head = interp;
170 if (_PyRuntime.interpreters.next_id < 0) {
171 /* overflow or Py_Initialize() not called! */
172 PyErr_SetString(PyExc_RuntimeError,
173 "failed to get an interpreter ID");
Eric Snow7f8bfc92018-01-29 18:23:44 -0700174 /* XXX deallocate! */
Victor Stinnerd4341102017-11-23 00:12:09 +0100175 interp = NULL;
176 } else {
177 interp->id = _PyRuntime.interpreters.next_id;
178 _PyRuntime.interpreters.next_id += 1;
179 }
180 HEAD_UNLOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000181
Yury Selivanovf23746a2018-01-22 19:11:18 -0500182 interp->tstate_next_unique_id = 0;
183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000185}
186
187
188void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000189PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000190{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 PyThreadState *p;
192 HEAD_LOCK();
193 for (p = interp->tstate_head; p != NULL; p = p->next)
194 PyThreadState_Clear(p);
195 HEAD_UNLOCK();
Victor Stinnerda273412017-12-15 01:46:02 +0100196 _PyCoreConfig_Clear(&interp->core_config);
197 _PyMainInterpreterConfig_Clear(&interp->config);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000198 Py_CLEAR(interp->codec_search_path);
199 Py_CLEAR(interp->codec_search_cache);
200 Py_CLEAR(interp->codec_error_registry);
Eric Snow93c92f72017-09-13 23:46:04 -0700201 Py_CLEAR(interp->modules);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 Py_CLEAR(interp->sysdict);
204 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200205 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400206 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300207 Py_CLEAR(interp->import_func);
Antoine Pitrou346cbd32017-05-27 17:50:54 +0200208#ifdef HAVE_FORK
209 Py_CLEAR(interp->before_forkers);
210 Py_CLEAR(interp->after_forkers_parent);
211 Py_CLEAR(interp->after_forkers_child);
212#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000213}
214
215
216static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000217zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 PyThreadState *p;
220 /* No need to lock the mutex here because this should only happen
221 when the threads are all really dead (XXX famous last words). */
222 while ((p = interp->tstate_head) != NULL) {
223 PyThreadState_Delete(p);
224 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000225}
226
227
228void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000229PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 PyInterpreterState **p;
232 zapthreads(interp);
233 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600234 for (p = &_PyRuntime.interpreters.head; ; p = &(*p)->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 if (*p == NULL)
236 Py_FatalError(
237 "PyInterpreterState_Delete: invalid interp");
238 if (*p == interp)
239 break;
240 }
241 if (interp->tstate_head != NULL)
242 Py_FatalError("PyInterpreterState_Delete: remaining threads");
243 *p = interp->next;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600244 if (_PyRuntime.interpreters.main == interp) {
245 _PyRuntime.interpreters.main = NULL;
246 if (_PyRuntime.interpreters.head != NULL)
Eric Snow6b4be192017-05-22 21:36:03 -0700247 Py_FatalError("PyInterpreterState_Delete: remaining subinterpreters");
248 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200250 PyMem_RawFree(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000251}
252
253
Eric Snowe3774162017-05-22 19:46:40 -0700254int64_t
255PyInterpreterState_GetID(PyInterpreterState *interp)
256{
257 if (interp == NULL) {
258 PyErr_SetString(PyExc_RuntimeError, "no interpreter provided");
259 return -1;
260 }
261 return interp->id;
262}
263
264
Eric Snow7f8bfc92018-01-29 18:23:44 -0700265PyInterpreterState *
266_PyInterpreterState_LookUpID(PY_INT64_T requested_id)
267{
268 if (requested_id < 0)
269 goto error;
270
271 PyInterpreterState *interp = PyInterpreterState_Head();
272 while (interp != NULL) {
273 PY_INT64_T id = PyInterpreterState_GetID(interp);
274 if (id < 0)
275 return NULL;
276 if (requested_id == id)
277 return interp;
278 interp = PyInterpreterState_Next(interp);
279 }
280
281error:
282 PyErr_Format(PyExc_RuntimeError,
283 "unrecognized interpreter ID %lld", requested_id);
284 return NULL;
285}
286
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000287/* Default implementation for _PyThreadState_GetFrame */
288static struct _frame *
289threadstate_getframe(PyThreadState *self)
290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000292}
293
Victor Stinner45b9be52010-03-03 23:28:07 +0000294static PyThreadState *
295new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000296{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200297 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 if (_PyThreadState_GetFrame == NULL)
300 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 if (tstate != NULL) {
303 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 tstate->frame = NULL;
306 tstate->recursion_depth = 0;
307 tstate->overflowed = 0;
308 tstate->recursion_critical = 0;
pdox18967932017-10-25 23:03:01 -0700309 tstate->stackcheck_counter = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 tstate->tracing = 0;
311 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 tstate->gilstate_counter = 0;
313 tstate->async_exc = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 tstate->thread_id = PyThread_get_thread_ident();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 tstate->curexc_type = NULL;
319 tstate->curexc_value = NULL;
320 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000321
Mark Shannonae3087c2017-10-22 22:41:51 +0100322 tstate->exc_state.exc_type = NULL;
323 tstate->exc_state.exc_value = NULL;
324 tstate->exc_state.exc_traceback = NULL;
325 tstate->exc_state.previous_item = NULL;
326 tstate->exc_info = &tstate->exc_state;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000327
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 tstate->c_profilefunc = NULL;
329 tstate->c_tracefunc = NULL;
330 tstate->c_profileobj = NULL;
331 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000332
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200333 tstate->trash_delete_nesting = 0;
334 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200335 tstate->on_delete = NULL;
336 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200337
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800338 tstate->coroutine_origin_tracking_depth = 0;
339
Yury Selivanov75445082015-05-11 22:57:16 -0400340 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400341 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400342
Yury Selivanoveb636452016-09-08 22:01:51 -0700343 tstate->async_gen_firstiter = NULL;
344 tstate->async_gen_finalizer = NULL;
345
Yury Selivanovf23746a2018-01-22 19:11:18 -0500346 tstate->context = NULL;
347 tstate->context_ver = 1;
348
349 tstate->id = ++interp->tstate_next_unique_id;
350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 if (init)
352 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200355 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200357 if (tstate->next)
358 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 interp->tstate_head = tstate;
360 HEAD_UNLOCK();
361 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000362
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000364}
365
Victor Stinner45b9be52010-03-03 23:28:07 +0000366PyThreadState *
367PyThreadState_New(PyInterpreterState *interp)
368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000370}
371
372PyThreadState *
373_PyThreadState_Prealloc(PyInterpreterState *interp)
374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000376}
377
378void
379_PyThreadState_Init(PyThreadState *tstate)
380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000382}
383
Martin v. Löwis1a214512008-06-11 05:26:20 +0000384PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200385PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000386{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200387 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100388 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000390 if (module->m_slots) {
391 return NULL;
392 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 if (index == 0)
394 return NULL;
395 if (state->modules_by_index == NULL)
396 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200397 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 return NULL;
399 res = PyList_GET_ITEM(state->modules_by_index, index);
400 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000401}
402
403int
404_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
405{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000406 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300407 if (!def) {
408 assert(PyErr_Occurred());
409 return -1;
410 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000411 if (def->m_slots) {
412 PyErr_SetString(PyExc_SystemError,
413 "PyState_AddModule called on module with slots");
414 return -1;
415 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100416 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (!state->modules_by_index) {
418 state->modules_by_index = PyList_New(0);
419 if (!state->modules_by_index)
420 return -1;
421 }
422 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
423 if (PyList_Append(state->modules_by_index, Py_None) < 0)
424 return -1;
425 Py_INCREF(module);
426 return PyList_SetItem(state->modules_by_index,
427 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000428}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000429
Martin v. Löwis7800f752012-06-22 12:20:55 +0200430int
431PyState_AddModule(PyObject* module, struct PyModuleDef* def)
432{
433 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100434 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200435 if (!def) {
436 Py_FatalError("PyState_AddModule: Module Definition is NULL");
437 return -1;
438 }
439 index = def->m_base.m_index;
440 if (state->modules_by_index) {
441 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
442 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
443 Py_FatalError("PyState_AddModule: Module already added!");
444 return -1;
445 }
446 }
447 }
448 return _PyState_AddModule(module, def);
449}
450
451int
452PyState_RemoveModule(struct PyModuleDef* def)
453{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000454 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200455 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000456 if (def->m_slots) {
457 PyErr_SetString(PyExc_SystemError,
458 "PyState_RemoveModule called on module with slots");
459 return -1;
460 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100461 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200462 if (index == 0) {
463 Py_FatalError("PyState_RemoveModule: Module index invalid.");
464 return -1;
465 }
466 if (state->modules_by_index == NULL) {
467 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
468 return -1;
469 }
470 if (index > PyList_GET_SIZE(state->modules_by_index)) {
471 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
472 return -1;
473 }
474 return PyList_SetItem(state->modules_by_index, index, Py_None);
475}
476
Antoine Pitrou40322e62013-08-11 00:30:09 +0200477/* used by import.c:PyImport_Cleanup */
478void
479_PyState_ClearModules(void)
480{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100481 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200482 if (state->modules_by_index) {
483 Py_ssize_t i;
484 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
485 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
486 if (PyModule_Check(m)) {
487 /* cleanup the saved copy of module dicts */
488 PyModuleDef *md = PyModule_GetDef(m);
489 if (md)
490 Py_CLEAR(md->m_base.m_copy);
491 }
492 }
493 /* Setting modules_by_index to NULL could be dangerous, so we
494 clear the list instead. */
495 if (PyList_SetSlice(state->modules_by_index,
496 0, PyList_GET_SIZE(state->modules_by_index),
497 NULL))
498 PyErr_WriteUnraisable(state->modules_by_index);
499 }
500}
501
Guido van Rossuma027efa1997-05-05 20:56:21 +0000502void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000503PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 if (Py_VerboseFlag && tstate->frame != NULL)
506 fprintf(stderr,
507 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 Py_CLEAR(tstate->dict);
512 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 Py_CLEAR(tstate->curexc_type);
515 Py_CLEAR(tstate->curexc_value);
516 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000517
Mark Shannonae3087c2017-10-22 22:41:51 +0100518 Py_CLEAR(tstate->exc_state.exc_type);
519 Py_CLEAR(tstate->exc_state.exc_value);
520 Py_CLEAR(tstate->exc_state.exc_traceback);
Serhiy Storchakabdf42982017-10-26 16:59:40 +0300521
Mark Shannonae3087c2017-10-22 22:41:51 +0100522 /* The stack of exception states should contain just this thread. */
523 assert(tstate->exc_info->previous_item == NULL);
524 if (Py_VerboseFlag && tstate->exc_info != &tstate->exc_state) {
525 fprintf(stderr,
526 "PyThreadState_Clear: warning: thread still has a generator\n");
527 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 tstate->c_profilefunc = NULL;
530 tstate->c_tracefunc = NULL;
531 Py_CLEAR(tstate->c_profileobj);
532 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400533
534 Py_CLEAR(tstate->coroutine_wrapper);
Yury Selivanoveb636452016-09-08 22:01:51 -0700535 Py_CLEAR(tstate->async_gen_firstiter);
536 Py_CLEAR(tstate->async_gen_finalizer);
Yury Selivanovf23746a2018-01-22 19:11:18 -0500537
538 Py_CLEAR(tstate->context);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000539}
540
541
Guido van Rossum29757862001-01-23 01:46:06 +0000542/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
543static void
544tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 if (tstate == NULL)
548 Py_FatalError("PyThreadState_Delete: NULL tstate");
549 interp = tstate->interp;
550 if (interp == NULL)
551 Py_FatalError("PyThreadState_Delete: NULL interp");
552 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200553 if (tstate->prev)
554 tstate->prev->next = tstate->next;
555 else
556 interp->tstate_head = tstate->next;
557 if (tstate->next)
558 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200560 if (tstate->on_delete != NULL) {
561 tstate->on_delete(tstate->on_delete_data);
562 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200563 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000564}
565
566
Guido van Rossum29757862001-01-23 01:46:06 +0000567void
568PyThreadState_Delete(PyThreadState *tstate)
569{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100570 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 Py_FatalError("PyThreadState_Delete: tstate is still current");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600572 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900573 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600574 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900575 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600576 }
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200577 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000578}
579
580
Guido van Rossum29757862001-01-23 01:46:06 +0000581void
582PyThreadState_DeleteCurrent()
583{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100584 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 if (tstate == NULL)
586 Py_FatalError(
587 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100588 tstate_delete_common(tstate);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600589 if (_PyRuntime.gilstate.autoInterpreterState &&
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900590 PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600591 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900592 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, NULL);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600593 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100594 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000596}
Guido van Rossum29757862001-01-23 01:46:06 +0000597
598
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200599/*
600 * Delete all thread states except the one passed as argument.
601 * Note that, if there is a current thread state, it *must* be the one
602 * passed as argument. Also, this won't touch any other interpreters
603 * than the current one, since we don't know which thread state should
604 * be kept in those other interpreteres.
605 */
606void
607_PyThreadState_DeleteExcept(PyThreadState *tstate)
608{
609 PyInterpreterState *interp = tstate->interp;
610 PyThreadState *p, *next, *garbage;
611 HEAD_LOCK();
612 /* Remove all thread states, except tstate, from the linked list of
613 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200614 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200615 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200616 if (garbage == tstate)
617 garbage = tstate->next;
618 if (tstate->prev)
619 tstate->prev->next = tstate->next;
620 if (tstate->next)
621 tstate->next->prev = tstate->prev;
622 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200623 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200624 HEAD_UNLOCK();
625 /* Clear and deallocate all stale thread states. Even if this
626 executes Python code, we should be safe since it executes
627 in the current thread, not one of the stale threads. */
628 for (p = garbage; p; p = next) {
629 next = p->next;
630 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200631 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200632 }
633}
634
635
Guido van Rossuma027efa1997-05-05 20:56:21 +0000636PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100637_PyThreadState_UncheckedGet(void)
638{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100639 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100640}
641
642
643PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000644PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000645{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100646 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 if (tstate == NULL)
648 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000651}
652
653
654PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000655PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000656{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100657 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000658
Victor Stinnerb02ef712016-01-22 14:09:55 +0100659 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 /* It should not be possible for more than one thread state
661 to be used for a thread. Check this the best we can in debug
662 builds.
663 */
Antoine Pitroua6a4dc82017-09-07 18:56:24 +0200664#if defined(Py_DEBUG)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 if (newts) {
666 /* This can be called from PyEval_RestoreThread(). Similar
667 to it, we need to ensure errno doesn't change.
668 */
669 int err = errno;
670 PyThreadState *check = PyGILState_GetThisThreadState();
671 if (check && check->interp == newts->interp && check != newts)
672 Py_FatalError("Invalid thread state for this thread");
673 errno = err;
674 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000675#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000677}
Guido van Rossumede04391998-04-10 20:18:25 +0000678
679/* An extension mechanism to store arbitrary additional per-thread state.
680 PyThreadState_GetDict() returns a dictionary that can be used to hold such
681 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000682 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
683 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000684
685PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000686PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000687{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100688 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 if (tstate == NULL)
690 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (tstate->dict == NULL) {
693 PyObject *d;
694 tstate->dict = d = PyDict_New();
695 if (d == NULL)
696 PyErr_Clear();
697 }
698 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000699}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000700
701
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000702/* Asynchronously raise an exception in a thread.
703 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000704 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000705 to call this, or use ctypes. Must be called with the GIL held.
706 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
707 match any known thread id). Can be called with exc=NULL to clear an
708 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000709
710int
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200711PyThreadState_SetAsyncExc(unsigned long id, PyObject *exc)
712{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100713 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 /* Although the GIL is held, a few C API functions can be called
717 * without the GIL held, and in particular some that create and
718 * destroy thread and interpreter states. Those can mutate the
719 * list of thread states we're traversing, so to prevent that we lock
720 * head_mutex for the duration.
721 */
722 HEAD_LOCK();
723 for (p = interp->tstate_head; p != NULL; p = p->next) {
724 if (p->thread_id == id) {
725 /* Tricky: we need to decref the current value
726 * (if any) in p->async_exc, but that can in turn
727 * allow arbitrary Python code to run, including
728 * perhaps calls to this function. To prevent
729 * deadlock, we need to release head_mutex before
730 * the decref.
731 */
732 PyObject *old_exc = p->async_exc;
733 Py_XINCREF(exc);
734 p->async_exc = exc;
735 HEAD_UNLOCK();
736 Py_XDECREF(old_exc);
737 _PyEval_SignalAsyncExc();
738 return 1;
739 }
740 }
741 HEAD_UNLOCK();
742 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000743}
744
745
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000746/* Routines for advanced debuggers, requested by David Beazley.
747 Don't use unless you know what you are doing! */
748
749PyInterpreterState *
750PyInterpreterState_Head(void)
751{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600752 return _PyRuntime.interpreters.head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000753}
754
755PyInterpreterState *
Eric Snow6b4be192017-05-22 21:36:03 -0700756PyInterpreterState_Main(void)
757{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600758 return _PyRuntime.interpreters.main;
Eric Snow6b4be192017-05-22 21:36:03 -0700759}
760
761PyInterpreterState *
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000762PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000764}
765
766PyThreadState *
767PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000769}
770
771PyThreadState *
772PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000773 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000774}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000775
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000776/* The implementation of sys._current_frames(). This is intended to be
777 called with the GIL held, as it will be when called via
778 sys._current_frames(). It's possible it would work fine even without
779 the GIL held, but haven't thought enough about that.
780*/
781PyObject *
782_PyThread_CurrentFrames(void)
783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000784 PyObject *result;
785 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 result = PyDict_New();
788 if (result == NULL)
789 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 /* for i in all interpreters:
792 * for t in all of i's thread states:
793 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200794 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000795 * need to grab head_mutex for the duration.
796 */
797 HEAD_LOCK();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600798 for (i = _PyRuntime.interpreters.head; i != NULL; i = i->next) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 PyThreadState *t;
800 for (t = i->tstate_head; t != NULL; t = t->next) {
801 PyObject *id;
802 int stat;
803 struct _frame *frame = t->frame;
804 if (frame == NULL)
805 continue;
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +0200806 id = PyLong_FromUnsignedLong(t->thread_id);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 if (id == NULL)
808 goto Fail;
809 stat = PyDict_SetItem(result, id, (PyObject *)frame);
810 Py_DECREF(id);
811 if (stat < 0)
812 goto Fail;
813 }
814 }
815 HEAD_UNLOCK();
816 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000817
818 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 HEAD_UNLOCK();
820 Py_DECREF(result);
821 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000822}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000823
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000824/* Python "auto thread state" API. */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000825
826/* Keep this as a static, as it is not reliable! It can only
827 ever be compared to the state for the *current* thread.
828 * If not equal, then it doesn't matter that the actual
829 value may change immediately after comparison, as it can't
830 possibly change to the current thread's state.
831 * If equal, then the current thread holds the lock, so the value can't
832 change until we yield the lock.
833*/
834static int
835PyThreadState_IsCurrent(PyThreadState *tstate)
836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 /* Must be the tstate for this thread */
838 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100839 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000840}
841
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000842/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000843 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000844*/
Tim Peters19717fa2004-10-09 17:38:29 +0000845void
846_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848 assert(i && t); /* must init with valid states */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900849 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
850 Py_FatalError("Could not allocate TSS entry");
851 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600852 _PyRuntime.gilstate.autoInterpreterState = i;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900853 assert(PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000855
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000857}
858
Victor Stinner861d9ab2016-03-16 22:45:24 +0100859PyInterpreterState *
860_PyGILState_GetInterpreterStateUnsafe(void)
861{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600862 return _PyRuntime.gilstate.autoInterpreterState;
Victor Stinner861d9ab2016-03-16 22:45:24 +0100863}
864
Tim Peters19717fa2004-10-09 17:38:29 +0000865void
866_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000867{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900868 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600869 _PyRuntime.gilstate.autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000870}
871
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900872/* Reset the TSS key - called by PyOS_AfterFork_Child().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200873 * This should not be necessary, but some - buggy - pthread implementations
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900874 * don't reset TSS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200875 */
876void
877_PyGILState_Reinit(void)
878{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600879 _PyRuntime.interpreters.mutex = PyThread_allocate_lock();
880 if (_PyRuntime.interpreters.mutex == NULL)
881 Py_FatalError("Can't initialize threads for interpreter");
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200882 PyThreadState *tstate = PyGILState_GetThisThreadState();
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900883 PyThread_tss_delete(&_PyRuntime.gilstate.autoTSSkey);
884 if (PyThread_tss_create(&_PyRuntime.gilstate.autoTSSkey) != 0) {
885 Py_FatalError("Could not allocate TSS entry");
886 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200887
Charles-François Natalia233df82011-11-22 19:49:51 +0100888 /* If the thread had an associated auto thread state, reassociate it with
889 * the new key. */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900890 if (tstate &&
891 PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate) != 0)
892 {
893 Py_FatalError("Couldn't create autoTSSkey mapping");
894 }
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200895}
896
Michael W. Hudson188d4362005-06-20 16:52:57 +0000897/* When a thread state is created for a thread by some mechanism other than
898 PyGILState_Ensure, it's important that the GILState machinery knows about
899 it so it doesn't try to create another thread state for the thread (this is
900 a better fix for SF bug #1010677 than the first one attempted).
901*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000902static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000903_PyGILState_NoteThreadState(PyThreadState* tstate)
904{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900905 /* If autoTSSkey isn't initialized, this must be the very first
Antoine Pitrou079ce542010-09-08 12:37:10 +0000906 threadstate created in Py_Initialize(). Don't do anything for now
907 (we'll be back here when _PyGILState_Init is called). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600908 if (!_PyRuntime.gilstate.autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000910
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900911 /* Stick the thread state for this thread in thread specific storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 The only situation where you can legitimately have more than one
914 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100915 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000916
Victor Stinner590cebe2013-12-13 11:08:56 +0100917 You shouldn't really be using the PyGILState_ APIs anyway (see issues
918 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000919
Victor Stinner590cebe2013-12-13 11:08:56 +0100920 The first thread state created for that given OS level thread will
921 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 */
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900923 if (PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey) == NULL) {
924 if ((PyThread_tss_set(&_PyRuntime.gilstate.autoTSSkey, (void *)tstate)
925 ) != 0)
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600926 {
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900927 Py_FatalError("Couldn't create autoTSSkey mapping");
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600928 }
Victor Stinner590cebe2013-12-13 11:08:56 +0100929 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 /* PyGILState_Release must not try to delete this thread state. */
932 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000933}
934
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000935/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000936PyThreadState *
937PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000938{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600939 if (_PyRuntime.gilstate.autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 return NULL;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900941 return (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000942}
943
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700944int
945PyGILState_Check(void)
946{
Victor Stinner8a1be612016-03-14 22:07:55 +0100947 PyThreadState *tstate;
948
949 if (!_PyGILState_check_enabled)
950 return 1;
951
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900952 if (!PyThread_tss_is_created(&_PyRuntime.gilstate.autoTSSkey)) {
Victor Stinner8a1be612016-03-14 22:07:55 +0100953 return 1;
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900954 }
Victor Stinner8a1be612016-03-14 22:07:55 +0100955
956 tstate = GET_TSTATE();
957 if (tstate == NULL)
958 return 0;
959
960 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700961}
962
Tim Peters19717fa2004-10-09 17:38:29 +0000963PyGILState_STATE
964PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000965{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000966 int current;
967 PyThreadState *tcur;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100968 int need_init_threads = 0;
969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* Note that we do not auto-init Python here - apart from
971 potential races with 2 threads auto-initializing, pep-311
972 spells out other issues. Embedders are expected to have
973 called Py_Initialize() and usually PyEval_InitThreads().
974 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600975 /* Py_Initialize() hasn't been called! */
976 assert(_PyRuntime.gilstate.autoInterpreterState);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100977
Masayuki Yamamoto731e1892017-10-06 19:41:34 +0900978 tcur = (PyThreadState *)PyThread_tss_get(&_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 if (tcur == NULL) {
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100980 need_init_threads = 1;
Victor Stinner62ca1002013-12-13 01:46:43 +0100981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 /* Create a new thread state for this thread */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600983 tcur = PyThreadState_New(_PyRuntime.gilstate.autoInterpreterState);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 if (tcur == NULL)
985 Py_FatalError("Couldn't create thread-state for new thread");
986 /* This is our thread state! We'll need to delete it in the
987 matching call to PyGILState_Release(). */
988 tcur->gilstate_counter = 0;
989 current = 0; /* new thread state is never current */
990 }
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100991 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 current = PyThreadState_IsCurrent(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100993 }
994
995 if (current == 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 PyEval_RestoreThread(tcur);
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +0100997 }
998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 /* Update our counter in the thread-state - no need for locks:
1000 - tcur will remain valid as we hold the GIL.
1001 - the counter is safe as we are the only thread "allowed"
1002 to modify this value
1003 */
1004 ++tcur->gilstate_counter;
Victor Stinnerb4d1e1f2017-11-30 22:05:00 +01001005
1006 if (need_init_threads) {
1007 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
1008 called from a new thread for the first time, we need the create the
1009 GIL. */
1010 PyEval_InitThreads();
1011 }
1012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001014}
1015
Tim Peters19717fa2004-10-09 17:38:29 +00001016void
1017PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001018{
Masayuki Yamamoto731e1892017-10-06 19:41:34 +09001019 PyThreadState *tcur = (PyThreadState *)PyThread_tss_get(
1020 &_PyRuntime.gilstate.autoTSSkey);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 if (tcur == NULL)
1022 Py_FatalError("auto-releasing thread-state, "
1023 "but no thread-state for this thread");
1024 /* We must hold the GIL and have our thread state current */
1025 /* XXX - remove the check - the assert should be fine,
1026 but while this is very new (April 2003), the extra check
1027 by release-only users can't hurt.
1028 */
1029 if (! PyThreadState_IsCurrent(tcur))
1030 Py_FatalError("This thread state must be current when releasing");
1031 assert(PyThreadState_IsCurrent(tcur));
1032 --tcur->gilstate_counter;
1033 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 /* If we're going to destroy this thread-state, we must
1036 * clear it while the GIL is held, as destructors may run.
1037 */
1038 if (tcur->gilstate_counter == 0) {
1039 /* can't have been locked when we created it */
1040 assert(oldstate == PyGILState_UNLOCKED);
1041 PyThreadState_Clear(tcur);
1042 /* Delete the thread-state. Note this releases the GIL too!
1043 * It's vital that the GIL be held here, to avoid shutdown
1044 * races; see bugs 225673 and 1061968 (that nasty bug has a
1045 * habit of coming back).
1046 */
1047 PyThreadState_DeleteCurrent();
1048 }
1049 /* Release the lock if necessary */
1050 else if (oldstate == PyGILState_UNLOCKED)
1051 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +00001052}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001053
Benjamin Peterson3bf01752012-04-13 18:06:36 -04001054
Eric Snow7f8bfc92018-01-29 18:23:44 -07001055/**************************/
1056/* cross-interpreter data */
1057/**************************/
1058
1059/* cross-interpreter data */
1060
1061crossinterpdatafunc _PyCrossInterpreterData_Lookup(PyObject *);
1062
1063/* This is a separate func from _PyCrossInterpreterData_Lookup in order
1064 to keep the registry code separate. */
1065static crossinterpdatafunc
1066_lookup_getdata(PyObject *obj)
1067{
1068 crossinterpdatafunc getdata = _PyCrossInterpreterData_Lookup(obj);
1069 if (getdata == NULL && PyErr_Occurred() == 0)
1070 PyErr_Format(PyExc_ValueError,
1071 "%S does not support cross-interpreter data", obj);
1072 return getdata;
1073}
1074
1075int
1076_PyObject_CheckCrossInterpreterData(PyObject *obj)
1077{
1078 crossinterpdatafunc getdata = _lookup_getdata(obj);
1079 if (getdata == NULL) {
1080 return -1;
1081 }
1082 return 0;
1083}
1084
1085static int
1086_check_xidata(_PyCrossInterpreterData *data)
1087{
1088 // data->data can be anything, including NULL, so we don't check it.
1089
1090 // data->obj may be NULL, so we don't check it.
1091
1092 if (data->interp < 0) {
1093 PyErr_SetString(PyExc_SystemError, "missing interp");
1094 return -1;
1095 }
1096
1097 if (data->new_object == NULL) {
1098 PyErr_SetString(PyExc_SystemError, "missing new_object func");
1099 return -1;
1100 }
1101
1102 // data->free may be NULL, so we don't check it.
1103
1104 return 0;
1105}
1106
1107int
1108_PyObject_GetCrossInterpreterData(PyObject *obj, _PyCrossInterpreterData *data)
1109{
1110 PyThreadState *tstate = PyThreadState_Get();
1111 // PyThreadState_Get() aborts if lookup fails, so we don't need
1112 // to check the result for NULL.
1113 PyInterpreterState *interp = tstate->interp;
1114
1115 // Reset data before re-populating.
1116 *data = (_PyCrossInterpreterData){0};
1117 data->free = PyMem_RawFree; // Set a default that may be overridden.
1118
1119 // Call the "getdata" func for the object.
1120 Py_INCREF(obj);
1121 crossinterpdatafunc getdata = _lookup_getdata(obj);
1122 if (getdata == NULL) {
1123 Py_DECREF(obj);
1124 return -1;
1125 }
1126 int res = getdata(obj, data);
1127 Py_DECREF(obj);
1128 if (res != 0) {
1129 return -1;
1130 }
1131
1132 // Fill in the blanks and validate the result.
1133 Py_XINCREF(data->obj);
1134 data->interp = interp->id;
1135 if (_check_xidata(data) != 0) {
1136 _PyCrossInterpreterData_Release(data);
1137 return -1;
1138 }
1139
1140 return 0;
1141}
1142
1143void
1144_PyCrossInterpreterData_Release(_PyCrossInterpreterData *data)
1145{
1146 if (data->data == NULL && data->obj == NULL) {
1147 // Nothing to release!
1148 return;
1149 }
1150
1151 // Switch to the original interpreter.
1152 PyInterpreterState *interp = _PyInterpreterState_LookUpID(data->interp);
1153 if (interp == NULL) {
1154 // The intepreter was already destroyed.
1155 if (data->free != NULL) {
1156 // XXX Someone leaked some memory...
1157 }
1158 return;
1159 }
1160 PyThreadState *tstate = PyInterpreterState_ThreadHead(interp);
1161 PyThreadState *save_tstate = PyThreadState_Swap(tstate);
1162
1163 // "Release" the data and/or the object.
1164 if (data->free != NULL) {
1165 data->free(data->data);
1166 }
1167 Py_XDECREF(data->obj);
1168
1169 // Switch back.
1170 if (save_tstate != NULL)
1171 PyThreadState_Swap(save_tstate);
1172}
1173
1174PyObject *
1175_PyCrossInterpreterData_NewObject(_PyCrossInterpreterData *data)
1176{
1177 return data->new_object(data);
1178}
1179
1180/* registry of {type -> crossinterpdatafunc} */
1181
1182/* For now we use a global registry of shareable classes. An
1183 alternative would be to add a tp_* slot for a class's
1184 crossinterpdatafunc. It would be simpler and more efficient. */
1185
1186static int
1187_register_xidata(PyTypeObject *cls, crossinterpdatafunc getdata)
1188{
1189 // Note that we effectively replace already registered classes
1190 // rather than failing.
1191 struct _xidregitem *newhead = PyMem_RawMalloc(sizeof(struct _xidregitem));
1192 if (newhead == NULL)
1193 return -1;
1194 newhead->cls = cls;
1195 newhead->getdata = getdata;
1196 newhead->next = _PyRuntime.xidregistry.head;
1197 _PyRuntime.xidregistry.head = newhead;
1198 return 0;
1199}
1200
1201static void _register_builtins_for_crossinterpreter_data(void);
1202
1203int
1204_PyCrossInterpreterData_Register_Class(PyTypeObject *cls,
1205 crossinterpdatafunc getdata)
1206{
1207 if (!PyType_Check(cls)) {
1208 PyErr_Format(PyExc_ValueError, "only classes may be registered");
1209 return -1;
1210 }
1211 if (getdata == NULL) {
1212 PyErr_Format(PyExc_ValueError, "missing 'getdata' func");
1213 return -1;
1214 }
1215
1216 // Make sure the class isn't ever deallocated.
1217 Py_INCREF((PyObject *)cls);
1218
1219 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1220 if (_PyRuntime.xidregistry.head == NULL) {
1221 _register_builtins_for_crossinterpreter_data();
1222 }
1223 int res = _register_xidata(cls, getdata);
1224 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1225 return res;
1226}
1227
1228crossinterpdatafunc
1229_PyCrossInterpreterData_Lookup(PyObject *obj)
1230{
1231 PyObject *cls = PyObject_Type(obj);
1232 crossinterpdatafunc getdata = NULL;
1233 PyThread_acquire_lock(_PyRuntime.xidregistry.mutex, WAIT_LOCK);
1234 struct _xidregitem *cur = _PyRuntime.xidregistry.head;
1235 if (cur == NULL) {
1236 _register_builtins_for_crossinterpreter_data();
1237 cur = _PyRuntime.xidregistry.head;
1238 }
1239 for(; cur != NULL; cur = cur->next) {
1240 if (cur->cls == (PyTypeObject *)cls) {
1241 getdata = cur->getdata;
1242 break;
1243 }
1244 }
1245 PyThread_release_lock(_PyRuntime.xidregistry.mutex);
1246 return getdata;
1247}
1248
1249/* cross-interpreter data for builtin types */
1250
1251static PyObject *
1252_new_bytes_object(_PyCrossInterpreterData *data)
1253{
1254 return PyBytes_FromString((char *)(data->data));
1255}
1256
1257static int
1258_bytes_shared(PyObject *obj, _PyCrossInterpreterData *data)
1259{
1260 data->data = (void *)(PyBytes_AS_STRING(obj));
1261 data->obj = obj; // Will be "released" (decref'ed) when data released.
1262 data->new_object = _new_bytes_object;
1263 data->free = NULL; // Do not free the data (it belongs to the object).
1264 return 0;
1265}
1266
1267static PyObject *
1268_new_none_object(_PyCrossInterpreterData *data)
1269{
1270 // XXX Singleton refcounts are problematic across interpreters...
1271 Py_INCREF(Py_None);
1272 return Py_None;
1273}
1274
1275static int
1276_none_shared(PyObject *obj, _PyCrossInterpreterData *data)
1277{
1278 data->data = NULL;
1279 // data->obj remains NULL
1280 data->new_object = _new_none_object;
1281 data->free = NULL; // There is nothing to free.
1282 return 0;
1283}
1284
1285static void
1286_register_builtins_for_crossinterpreter_data(void)
1287{
1288 // None
1289 if (_register_xidata((PyTypeObject *)PyObject_Type(Py_None), _none_shared) != 0) {
1290 Py_FatalError("could not register None for cross-interpreter sharing");
1291 }
1292
1293 // bytes
1294 if (_register_xidata(&PyBytes_Type, _bytes_shared) != 0) {
1295 Py_FatalError("could not register bytes for cross-interpreter sharing");
1296 }
1297}
1298
1299
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001300#ifdef __cplusplus
1301}
1302#endif