// Python interpreter retrieval routine adapted from // https://stackoverflow.com/a/8706144 std::string getPythonInterpreterStackTrace() { std::stringstream stack_trace; AutoGIL gil; PyThreadState *tstate = PyThreadState_GET(); if (NULL != tstate && NULL != tstate->frame) { PyFrameObject *frame = tstate->frame; while (NULL != frame) { int line = PyCode_Addr2Line(frame->f_code, frame->f_lasti); std::string filename = THPUtils_unpackString(frame->f_code->co_filename); std::string funcname = THPUtils_unpackString(frame->f_code->co_name); stack_trace << filename << "(" << line << "): " << funcname << "\n"; frame = frame->f_back; } } return stack_trace.str(); }
// Fetch the current error into object variables. NUITKA_MAY_BE_UNUSED static void FETCH_ERROR_OCCURRED( PyObject **exception_type, PyObject **exception_value, PyTracebackObject **exception_traceback) { PyThreadState *tstate = PyThreadState_GET(); *exception_type = tstate->curexc_type; *exception_value = tstate->curexc_value; *exception_traceback = (PyTracebackObject *)tstate->curexc_traceback; #if _DEBUG_EXCEPTIONS PRINT_STRING("FETCH_ERROR_OCCURRED:\n"); PRINT_EXCEPTION( tstate->curexc_type, tstate->curexc_value, tstate->curexc_traceback ); #endif tstate->curexc_type = NULL; tstate->curexc_value = NULL; tstate->curexc_traceback = NULL; }
/* Lookup the error handling callback function registered under the name error. As a special case NULL can be passed, in which case the error handling callback for strict encoding will be returned. */ PyObject *PyCodec_LookupError(const char *name) { PyObject *handler = NULL; PyInterpreterState *interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) return NULL; if (name==NULL) name = "strict"; handler = PyDict_GetItemString(interp->codec_error_registry, name); if (!handler) PyErr_Format(PyExc_LookupError, "unknown error handler name '%.400s'", name); else Py_INCREF(handler); return handler; }
static CHANNEL_SEND_EXCEPTION_HEAD(impl_channel_send_exception) { STACKLESS_GETARG(); PyThreadState *ts = PyThreadState_GET(); PyObject *bomb, *ret = NULL; assert(PyChannel_Check(self)); if (ts->st.main == NULL) return PyChannel_SendException_M(self, klass, args); bomb = slp_make_bomb(klass, args, "channel.send_exception"); if (bomb != NULL) { ret = generic_channel_action(self, bomb, 1, stackless); Py_DECREF(bomb); } return ret; }
inline void toPython() { PyErr_Restore( this->exception_type, this->exception_value, (PyObject *)this->exception_tb ); assert( this->exception_type ); #ifndef __NUITKA_NO_ASSERT__ PyThreadState *thread_state = PyThreadState_GET(); #endif assert( this->exception_type == thread_state->curexc_type ); assert( thread_state->curexc_type ); this->exception_type = NULL; this->exception_value = NULL; this->exception_tb = NULL; }
void _PyStackless_Init(void) { PyObject *dict; PyObject *modules; char *name = "stackless"; PySlpModuleObject *m; if (init_slpmoduletype()) return; /* record the thread state for thread support */ slp_initial_tstate = PyThreadState_GET(); /* Create the module and add the functions */ slp_module = PyModule_Create(&stacklessmodule); if (slp_module == NULL) return; /* errors handled by caller */ modules = PyImport_GetModuleDict(); if (PyDict_SetItemString(modules, name, slp_module)) { Py_DECREF(slp_module); return; } Py_DECREF(slp_module); /* Yes, it still exists, in modules! */ if (init_prickelpit()) return; dict = PyModule_GetDict(slp_module); #define INSERT(name, object) \ if (PyDict_SetItemString(dict, name, (PyObject*)object) < 0) return INSERT("slpmodule", PySlpModule_TypePtr); INSERT("cframe", &PyCFrame_Type); INSERT("cstack", &PyCStack_Type); INSERT("bomb", &PyBomb_Type); INSERT("tasklet", &PyTasklet_Type); INSERT("channel", &PyChannel_Type); INSERT("stackless", slp_module); m = (PySlpModuleObject *) slp_module; slpmodule_set__tasklet__(m, &PyTasklet_Type, NULL); slpmodule_set__channel__(m, &PyChannel_Type, NULL); }
static PyObject * impl_channel_send_throw(PyChannelObject *self, PyObject *exc, PyObject *val, PyObject *tb) { STACKLESS_GETARG(); PyThreadState *ts = PyThreadState_GET(); PyObject *bomb, *ret = NULL; assert(PyChannel_Check(self)); if (ts->st.main == NULL) return PyChannel_SendThrow_M(self, exc, val, tb); bomb = slp_exc_to_bomb(exc, val, tb); if (bomb != NULL) { ret = generic_channel_action(self, bomb, 1, stackless); Py_DECREF(bomb); } return ret; }
static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { #if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #else PyErr_Restore(type, value, tb); #endif }
PyObject *GPU_initPython(void) { PyObject *module; PyObject *submodule; PyObject *sys_modules = PyThreadState_GET()->interp->modules; module = PyInit_gpu(); PyModule_AddObject(module, "export_shader", (PyObject *)PyCFunction_New(meth_export_shader, NULL)); /* gpu.offscreen */ PyModule_AddObject(module, "offscreen", (submodule = BPyInit_gpu_offscreen())); PyDict_SetItem(sys_modules, PyModule_GetNameObject(submodule), submodule); Py_INCREF(submodule); PyDict_SetItem(PyImport_GetModuleDict(), PyModule_GetNameObject(module), module); return module; }
PyObject* PyState_FindModule(struct PyModuleDef* module) { Py_ssize_t index = module->m_base.m_index; PyInterpreterState *state = PyThreadState_GET()->interp; PyObject *res; if (module->m_slots) { return NULL; } if (index == 0) return NULL; if (state->modules_by_index == NULL) return NULL; if (index >= PyList_GET_SIZE(state->modules_by_index)) return NULL; res = PyList_GET_ITEM(state->modules_by_index, index); return res==Py_None ? NULL : res; }
static PyObject * restore_tracing(PyFrameObject *f, int exc, PyObject *retval) { PyThreadState *ts = PyThreadState_GET(); PyCFrameObject *cf = (PyCFrameObject *) f; f = cf->f_back; ts->c_tracefunc = cf->any1; ts->c_profilefunc = cf->any2; ts->c_traceobj = cf->ob1; ts->c_profileobj = cf->ob2; ts->tracing = cf->i; ts->use_tracing = cf->n; /* the objects *have* extra references here */ Py_DECREF(cf); ts->frame = f; return STACKLESS_PACK(retval); }
void PyErr_SetExcInfo(PyObject *p_type, PyObject *p_value, PyObject *p_traceback) { PyObject *oldtype, *oldvalue, *oldtraceback; PyThreadState *tstate = PyThreadState_GET(); oldtype = tstate->exc_type; oldvalue = tstate->exc_value; oldtraceback = tstate->exc_traceback; tstate->exc_type = p_type; tstate->exc_value = p_value; tstate->exc_traceback = p_traceback; Py_XDECREF(oldtype); Py_XDECREF(oldvalue); Py_XDECREF(oldtraceback); }
int PyCodec_Register(PyObject *search_function) { PyInterpreterState *interp = PyThreadState_GET()->interp; if (interp->codec_search_path == NULL && _PyCodecRegistry_Init()) goto onError; if (search_function == NULL) { PyErr_BadArgument(); goto onError; } if (!PyCallable_Check(search_function)) { PyErr_SetString(PyExc_TypeError, "argument must be callable"); goto onError; } return PyList_Append(interp->codec_search_path, search_function); onError: return -1; }
int _PyState_AddModule(PyObject* module, struct PyModuleDef* def) { PyInterpreterState *state = PyThreadState_GET()->interp; if (!def) return -1; if (!state->modules_by_index) { state->modules_by_index = PyList_New(0); if (!state->modules_by_index) return -1; } while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index) if (PyList_Append(state->modules_by_index, Py_None) < 0) return -1; Py_INCREF(module); return PyList_SetItem(state->modules_by_index, def->m_base.m_index, module); }
//============================================================================= // METHOD : SPELLwsWarmStartImpl::fixState() //============================================================================= PyFrameObject* SPELLwsWarmStartImpl::fixState() { DEBUG("[WS] Fixing state =============================================="); // Synchronize so that nothing can be done while saving SPELLmonitor m(m_lock); // Get the head interpreter state PyInterpreterState* istate = PyInterpreterState_Head(); // Get the current thread state PyThreadState* oldState = PyThreadState_GET(); DEBUG("[WS] Old state: " + PSTR(oldState)); DEBUG("[WS] Interpreter head: " + PSTR(istate->tstate_head)); DEBUG("[WS] Interpreter next: " + PSTR(istate->next)); DEBUG("[WS] State recursion depth: " + ISTR(oldState->recursion_depth)); DEBUG("[WS] State next: " + PSTR(oldState->next)); // Create a fresh thread state PyThreadState* newState = PyThreadState_New(istate); istate->tstate_head = newState; newState->recursion_depth = oldState->recursion_depth; newState->tracing = oldState->tracing; newState->use_tracing = oldState->use_tracing; newState->tick_counter = oldState->tick_counter; newState->gilstate_counter = oldState->gilstate_counter; newState->dict = PyDict_Copy(oldState->dict); FrameList::iterator it; unsigned int frameCount = m_frames.size(); DEBUG("[WS] Total frames to fix " + ISTR(frameCount)); m_topFrame = NULL; for( unsigned int index = 0; index < frameCount; index++) { bool isHead = (index == (frameCount-1)); DEBUG("[WS] Fix state on frame index " + ISTR(index) + " frame=" + PYCREPR(m_frames[index])); m_topFrame = m_frames[index]; m_topFrame->fixState(newState, isHead); } DEBUG("[WS] State fixed ==============================================="); PyErr_Clear(); return m_topFrame->getFrameObject(); }
static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { PyObject *local_type, *local_value, *local_tb; PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); local_type = tstate->curexc_type; local_value = tstate->curexc_value; local_tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; PyErr_NormalizeException(&local_type, &local_value, &local_tb); if (unlikely(tstate->curexc_type)) goto bad; #if PY_MAJOR_VERSION >= 3 if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) goto bad; #endif *type = local_type; *value = local_value; *tb = local_tb; Py_INCREF(local_type); Py_INCREF(local_value); Py_INCREF(local_tb); tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = local_type; tstate->exc_value = local_value; tstate->exc_traceback = local_tb; /* Make sure tstate is in a consistent state when we XDECREF these objects (XDECREF may run arbitrary code). */ Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); return 0; bad: *type = 0; *value = 0; *tb = 0; Py_XDECREF(local_type); Py_XDECREF(local_value); Py_XDECREF(local_tb); return -1; }
void signal_handler(int sig_num) { printf("Trapped signal %d in C++ layer, exiting\n", sig_num); //PyErr_SetString(PyExc_ValueError,"Trapped signal in C++ layer, exiting"); printf("\n"); PyThreadState *tstate = PyThreadState_GET(); if (NULL != tstate && NULL != tstate->frame) { PyFrameObject *frame = tstate->frame; printf("Python stack trace:\n"); while (NULL != frame) { int line = frame->f_lineno; const char *filename = PyString_AsString(frame->f_code->co_filename); const char *funcname = PyString_AsString(frame->f_code->co_name); printf(" %s(%d): %s\n", filename, line, funcname); frame = frame->f_back; } } exit(0); }
// Clear error, which is not likely set. This is about bugs from CPython, // use CLEAR_ERROR_OCCURRED is not sure. NUITKA_MAY_BE_UNUSED static inline void DROP_ERROR_OCCURRED( void ) { PyThreadState *tstate = PyThreadState_GET(); if (unlikely( tstate->curexc_type != NULL )) { PyObject *old_type = tstate->curexc_type; PyObject *old_value = tstate->curexc_value; PyObject *old_tb = tstate->curexc_traceback; tstate->curexc_type = NULL; tstate->curexc_value = NULL; tstate->curexc_traceback = NULL; Py_DECREF( old_type ); Py_XDECREF( old_value ); Py_XDECREF( old_tb ); } }
static TASKLET_RAISE_EXCEPTION_HEAD(impl_tasklet_raise_exception) { STACKLESS_GETARG(); PyThreadState *ts = PyThreadState_GET(); PyObject *bomb; if (ts->st.main == NULL) return PyTasklet_RaiseException_M(self, klass, args); bomb = slp_make_bomb(klass, args, "tasklet.raise_exception"); if (bomb == NULL) return NULL; TASKLET_SETVAL_OWN(self, bomb); /* if the tasklet is dead, do not run it (no frame) but explode */ if (slp_get_frame(self) == NULL) { TASKLET_CLAIMVAL(self, &bomb); return slp_bomb_explode(bomb); } return slp_schedule_task(ts->st.current, self, stackless, 0); }
PyMODINIT_FUNC PyInit_mathutils(void) { PyObject *submodule; PyObject *item; PyObject *sys_modules= PyThreadState_GET()->interp->modules; if (PyType_Ready(&vector_Type) < 0) return NULL; if (PyType_Ready(&matrix_Type) < 0) return NULL; if (PyType_Ready(&euler_Type) < 0) return NULL; if (PyType_Ready(&quaternion_Type) < 0) return NULL; if (PyType_Ready(&color_Type) < 0) return NULL; submodule = PyModule_Create(&M_Mathutils_module_def); /* each type has its own new() function */ PyModule_AddObject(submodule, "Vector", (PyObject *)&vector_Type); PyModule_AddObject(submodule, "Matrix", (PyObject *)&matrix_Type); PyModule_AddObject(submodule, "Euler", (PyObject *)&euler_Type); PyModule_AddObject(submodule, "Quaternion", (PyObject *)&quaternion_Type); PyModule_AddObject(submodule, "Color", (PyObject *)&color_Type); /* submodule */ PyModule_AddObject(submodule, "geometry", (item=PyInit_mathutils_geometry())); /* XXX, python doesnt do imports with this usefully yet * 'from mathutils.geometry import PolyFill' * ...fails without this. */ PyDict_SetItemString(sys_modules, "mathutils.geometry", item); Py_INCREF(item); /* Noise submodule */ PyModule_AddObject(submodule, "noise", (item=PyInit_mathutils_noise())); PyDict_SetItemString(sys_modules, "mathutils.noise", item); Py_INCREF(item); mathutils_matrix_vector_cb_index= Mathutils_RegisterCallback(&mathutils_matrix_vector_cb); return submodule; }
static PyObject * schedule_task_destruct(PyTaskletObject *prev, PyTaskletObject *next) { /* * The problem is to leave the dying tasklet alive * until we have done the switch. * This cannot easily be done by hard switching, since * the C stack we are leaving is never returned to, * and who should do the dereferencing? * Therefore, we enforce a soft-switch. */ PyThreadState *ts = PyThreadState_GET(); PyObject *retval; /* we should have no nesting level */ assert(ts->st.nesting_level == 0); /* even there is a (buggy) nesting, ensure soft switch */ if (ts->st.nesting_level != 0) { printf("XXX error, nesting_level = %d\n", ts->st.nesting_level); ts->st.nesting_level = 0; } /* update what's not yet updated */ assert(ts->recursion_depth == 0); prev->recursion_depth = 0; assert(ts->frame == NULL); prev->f.frame = NULL; /* do a soft switch */ if (prev != next) retval = slp_schedule_task(prev, next, 1); else { retval = prev->tempval; Py_INCREF(retval); if (PyBomb_Check(retval)) retval = slp_bomb_explode(prev); } prev->ob_type->tp_clear((PyObject *)prev); /* now it is safe to derefence prev */ Py_DECREF(prev); return retval; }
static void CHAIN_EXCEPTION( PyObject *exception_type, PyObject *exception_value ) { // Implicit chain of exception already existing. PyThreadState *thread_state = PyThreadState_GET(); // Normalize existing exception first. TODO: Will normally be done already. NORMALIZE_EXCEPTION( &thread_state->exc_type, &thread_state->exc_value, (PyTracebackObject **)&thread_state->exc_traceback ); PyObject *old_exc_value = thread_state->exc_value; if ( old_exc_value != NULL && old_exc_value != Py_None && old_exc_value != exception_value ) { PyObject *current = old_exc_value; while( true ) { PyObject *context = PyException_GetContext( current ); if (!context) break; CHECK_OBJECT( context ); Py_DECREF( context ); CHECK_OBJECT( context ); if ( context == exception_value ) { PyException_SetContext( current, NULL ); break; } current = context; } CHECK_OBJECT( old_exc_value ); Py_INCREF( old_exc_value ); PyException_SetContext( exception_value, old_exc_value ); CHECK_OBJECT( thread_state->exc_traceback ); PyException_SetTraceback( old_exc_value, thread_state->exc_traceback ); } }
int PyState_RemoveModule(struct PyModuleDef* def) { Py_ssize_t index = def->m_base.m_index; PyInterpreterState *state = PyThreadState_GET()->interp; if (index == 0) { Py_FatalError("PyState_RemoveModule: Module index invalid."); return -1; } if (state->modules_by_index == NULL) { Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible."); return -1; } if (index > PyList_GET_SIZE(state->modules_by_index)) { Py_FatalError("PyState_RemoveModule: Module index out of bounds."); return -1; } return PyList_SetItem(state->modules_by_index, index, Py_None); }
static PyObject * slpmodule_getthreads(PySlpModuleObject *mod, void *context) { PyObject *lis = PyList_New(0); PyThreadState *ts = PyThreadState_GET(); PyInterpreterState *interp = ts->interp; if (lis == NULL) return NULL; for (ts = interp->tstate_head; ts != NULL; ts = ts->next) { PyObject *id = PyInt_FromLong(ts->thread_id); if (id == NULL || PyList_Append(lis, id)) return NULL; } PyList_Reverse(lis); return lis; }
PyObject * PyStackless_Call_Main(PyObject *func, PyObject *args, PyObject *kwds) { PyThreadState *ts = PyThreadState_GET(); PyCFrameObject *c; PyObject *retval; if (ts->st.main != NULL) RUNTIME_ERROR( "Call_Main cannot run within a main tasklet", NULL); c = slp_cframe_newfunc(func, args, kwds, 0); if (c == NULL) return NULL; /* frames eat their own reference when returning */ Py_INCREF((PyObject *)c); retval = slp_eval_frame((PyFrameObject *) c); Py_DECREF((PyObject *)c); return retval; }
PyObject * PyStackless_Schedule(PyObject *retval, int remove) { STACKLESS_GETARG(); PyThreadState *ts = PyThreadState_GET(); PyTaskletObject *prev = ts->st.current, *next = prev->next; PyObject *ret = NULL; if (ts->st.main == NULL) return PyStackless_Schedule_M(retval, remove); Py_INCREF(prev); TASKLET_SETVAL(prev, retval); if (remove) { slp_current_remove(); Py_DECREF(prev); } ret = slp_schedule_task(prev, next, stackless); Py_DECREF(prev); return ret; }
// Preserve the current exception as the frame to restore. NUITKA_MAY_BE_UNUSED static inline void PRESERVE_FRAME_EXCEPTION( PyFrameObject *frame_object ) { // Setting exception for frame if not already done. if ( frame_object->f_exc_type == NULL ) { PyThreadState *thread_state = PyThreadState_GET(); if ( thread_state->exc_type != NULL && thread_state->exc_type != Py_None ) { #if _DEBUG_EXCEPTIONS PRINT_STRING("PRESERVE_FRAME_EXCEPTION: preserve thread exception\n"); #endif frame_object->f_exc_type = thread_state->exc_type; Py_INCREF( frame_object->f_exc_type ); frame_object->f_exc_value = thread_state->exc_value; Py_XINCREF( frame_object->f_exc_value ); frame_object->f_exc_traceback = thread_state->exc_traceback; Py_XINCREF( frame_object->f_exc_traceback ); } else { #if _DEBUG_EXCEPTIONS PRINT_STRING("PRESERVE_FRAME_EXCEPTION: no exception to preserve\n"); #endif frame_object->f_exc_type = Py_None; Py_INCREF( frame_object->f_exc_type ); frame_object->f_exc_value = NULL; frame_object->f_exc_traceback = NULL; } } #if _DEBUG_EXCEPTIONS else { PRINT_STRING("PRESERVE_FRAME_EXCEPTION: already preserving\n"); } PRINT_ITEM( (PyObject *)frame_object ); PRINT_NEW_LINE(); PRINT_EXCEPTION( frame_object->f_exc_type, frame_object->f_exc_value, frame_object->f_exc_traceback ); #endif }
static PyObject* clear_stats(PyObject *self, PyObject *args) { PyObject *d; if (!yapphavestats) { Py_RETURN_NONE; } current_ctx = NULL; prev_ctx = NULL; initial_ctx = NULL; henum(contexts, _ctxenumdel, NULL); htdestroy(contexts); contexts = NULL; fldestroy(flpit); flpit = NULL; fldestroy(flctx); flctx = NULL; yappinitialized = 0; yapphavestats = 0; ycurfuncindex = 0; ycurthreadindex = 0; d = PyThreadState_GET()->dict; if (PyDict_GetItemString(d, "_yappi_tid")) { PyDict_DelItemString(d, "_yappi_tid"); } Py_CLEAR(test_timings); // check for mem leaks if DEBUG_MEM is specified #ifdef DEBUG_MEM YMEMLEAKCHECK(); #endif Py_RETURN_NONE; }
static int tasklet_traverse(PyTaskletObject *t, visitproc visit, void *arg) { PyFrameObject *f; PyThreadState *ts = PyThreadState_GET(); /* tasklets that need to be switched to for the kill, can't be collected. * Only trivial decrefs are allowed during GC collect */ if (tasklet_has_c_stack(t)) PyObject_GC_Collectable((PyObject *)t, visit, arg, 0); /* we own the "execute reference" of all the frames */ for (f = t->f.frame; f != NULL; f = f->f_back) { Py_VISIT(f); } Py_VISIT(t->tempval); Py_VISIT(t->cstate); return 0; }
int PyState_AddModule(PyObject* module, struct PyModuleDef* def) { Py_ssize_t index; PyInterpreterState *state = PyThreadState_GET()->interp; if (!def) { Py_FatalError("PyState_AddModule: Module Definition is NULL"); return -1; } index = def->m_base.m_index; if (state->modules_by_index) { if(PyList_GET_SIZE(state->modules_by_index) >= index) { if(module == PyList_GET_ITEM(state->modules_by_index, index)) { Py_FatalError("PyState_AddModule: Module already added!"); return -1; } } } return _PyState_AddModule(module, def); }