+++ /dev/null
-\r
-/* Python interpreter top-level routines, including init/exit */\r
-\r
-#include "Python.h"\r
-\r
-#include "Python-ast.h"\r
-#undef Yield /* undefine macro conflicting with winbase.h */\r
-#include "grammar.h"\r
-#include "node.h"\r
-#include "token.h"\r
-#include "parsetok.h"\r
-#include "errcode.h"\r
-#include "code.h"\r
-#include "compile.h"\r
-#include "symtable.h"\r
-#include "pyarena.h"\r
-#include "ast.h"\r
-#include "eval.h"\r
-#include "marshal.h"\r
-#include "abstract.h"\r
-\r
-#ifdef HAVE_SIGNAL_H\r
-#include <signal.h>\r
-#endif\r
-\r
-#ifdef MS_WINDOWS\r
-#include "malloc.h" /* for alloca */\r
-#endif\r
-\r
-#ifdef HAVE_LANGINFO_H\r
-#include <locale.h>\r
-#include <langinfo.h>\r
-#endif\r
-\r
-#ifdef MS_WINDOWS\r
-#undef BYTE\r
-#include "windows.h"\r
-#endif\r
-\r
-#ifndef Py_REF_DEBUG\r
-#define PRINT_TOTAL_REFS()\r
-#else /* Py_REF_DEBUG */\r
-#define PRINT_TOTAL_REFS() fprintf(stderr, \\r
- "[%" PY_FORMAT_SIZE_T "d refs]\n", \\r
- _Py_GetRefTotal())\r
-#endif\r
-\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-\r
-extern char *Py_GetPath(void);\r
-\r
-extern grammar _PyParser_Grammar; /* From graminit.c */\r
-\r
-/* Forward */\r
-static void initmain(void);\r
-static void initsite(void);\r
-static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,\r
- PyCompilerFlags *, PyArena *);\r
-static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,\r
- PyCompilerFlags *);\r
-static void err_input(perrdetail *);\r
-static void initsigs(void);\r
-static void wait_for_thread_shutdown(void);\r
-static void call_sys_exitfunc(void);\r
-static void call_ll_exitfuncs(void);\r
-extern void _PyUnicode_Init(void);\r
-extern void _PyUnicode_Fini(void);\r
-\r
-#ifdef WITH_THREAD\r
-extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);\r
-extern void _PyGILState_Fini(void);\r
-#endif /* WITH_THREAD */\r
-\r
-int Py_DebugFlag; /* Needed by parser.c */\r
-int Py_VerboseFlag; /* Needed by import.c */\r
-int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */\r
-int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */\r
-int Py_NoSiteFlag; /* Suppress 'import site' */\r
-int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */\r
-int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */\r
-int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */\r
-int Py_FrozenFlag; /* Needed by getpath.c */\r
-int Py_UnicodeFlag = 0; /* Needed by compile.c */\r
-int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */\r
-/* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,\r
- on the command line, and is used in 2.2 by ceval.c to make all "/" divisions\r
- true divisions (which they will be in 2.3). */\r
-int _Py_QnewFlag = 0;\r
-int Py_NoUserSiteDirectory = 0; /* for -s and site.py */\r
-int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */\r
-\r
-\r
-/* Hack to force loading of object files */\r
-int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \\r
- PyOS_mystrnicmp; /* Python/pystrcmp.o */\r
-\r
-/* PyModule_GetWarningsModule is no longer necessary as of 2.6\r
-since _warnings is builtin. This API should not be used. */\r
-PyObject *\r
-PyModule_GetWarningsModule(void)\r
-{\r
- return PyImport_ImportModule("warnings");\r
-}\r
-\r
-static int initialized = 0;\r
-\r
-/* API to access the initialized flag -- useful for esoteric use */\r
-\r
-int\r
-Py_IsInitialized(void)\r
-{\r
- return initialized;\r
-}\r
-\r
-/* Global initializations. Can be undone by Py_Finalize(). Don't\r
- call this twice without an intervening Py_Finalize() call. When\r
- initializations fail, a fatal error is issued and the function does\r
- not return. On return, the first thread and interpreter state have\r
- been created.\r
-\r
- Locking: you must hold the interpreter lock while calling this.\r
- (If the lock has not yet been initialized, that's equivalent to\r
- having the lock, but you cannot use multiple threads.)\r
-\r
-*/\r
-\r
-static int\r
-add_flag(int flag, const char *envs)\r
-{\r
- int env = atoi(envs);\r
- if (flag < env)\r
- flag = env;\r
- if (flag < 1)\r
- flag = 1;\r
- return flag;\r
-}\r
-\r
-void\r
-Py_InitializeEx(int install_sigs)\r
-{\r
- PyInterpreterState *interp;\r
- PyThreadState *tstate;\r
- PyObject *bimod, *sysmod;\r
- char *p;\r
- char *icodeset = NULL; /* On Windows, input codeset may theoretically\r
- differ from output codeset. */\r
- char *codeset = NULL;\r
- char *errors = NULL;\r
- int free_codeset = 0;\r
- int overridden = 0;\r
- PyObject *sys_stream, *sys_isatty;\r
-#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)\r
- char *saved_locale, *loc_codeset;\r
-#endif\r
-#ifdef MS_WINDOWS\r
- char ibuf[128];\r
- char buf[128];\r
-#endif\r
- extern void _Py_ReadyTypes(void);\r
-\r
- if (initialized)\r
- return;\r
- initialized = 1;\r
-\r
- if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')\r
- Py_DebugFlag = add_flag(Py_DebugFlag, p);\r
- if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')\r
- Py_VerboseFlag = add_flag(Py_VerboseFlag, p);\r
- if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')\r
- Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);\r
- if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')\r
- Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);\r
- /* The variable is only tested for existence here; _PyRandom_Init will\r
- check its value further. */\r
- if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')\r
- Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);\r
-\r
- _PyRandom_Init();\r
-\r
- interp = PyInterpreterState_New();\r
- if (interp == NULL)\r
- Py_FatalError("Py_Initialize: can't make first interpreter");\r
-\r
- tstate = PyThreadState_New(interp);\r
- if (tstate == NULL)\r
- Py_FatalError("Py_Initialize: can't make first thread");\r
- (void) PyThreadState_Swap(tstate);\r
-\r
- _Py_ReadyTypes();\r
-\r
- if (!_PyFrame_Init())\r
- Py_FatalError("Py_Initialize: can't init frames");\r
-\r
- if (!_PyInt_Init())\r
- Py_FatalError("Py_Initialize: can't init ints");\r
-\r
- if (!_PyLong_Init())\r
- Py_FatalError("Py_Initialize: can't init longs");\r
-\r
- if (!PyByteArray_Init())\r
- Py_FatalError("Py_Initialize: can't init bytearray");\r
-\r
- _PyFloat_Init();\r
-\r
- interp->modules = PyDict_New();\r
- if (interp->modules == NULL)\r
- Py_FatalError("Py_Initialize: can't make modules dictionary");\r
- interp->modules_reloading = PyDict_New();\r
- if (interp->modules_reloading == NULL)\r
- Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");\r
-\r
-#ifdef Py_USING_UNICODE\r
- /* Init Unicode implementation; relies on the codec registry */\r
- _PyUnicode_Init();\r
-#endif\r
-\r
- bimod = _PyBuiltin_Init();\r
- if (bimod == NULL)\r
- Py_FatalError("Py_Initialize: can't initialize __builtin__");\r
- interp->builtins = PyModule_GetDict(bimod);\r
- if (interp->builtins == NULL)\r
- Py_FatalError("Py_Initialize: can't initialize builtins dict");\r
- Py_INCREF(interp->builtins);\r
-\r
- sysmod = _PySys_Init();\r
- if (sysmod == NULL)\r
- Py_FatalError("Py_Initialize: can't initialize sys");\r
- interp->sysdict = PyModule_GetDict(sysmod);\r
- if (interp->sysdict == NULL)\r
- Py_FatalError("Py_Initialize: can't initialize sys dict");\r
- Py_INCREF(interp->sysdict);\r
- _PyImport_FixupExtension("sys", "sys");\r
- PySys_SetPath(Py_GetPath());\r
- PyDict_SetItemString(interp->sysdict, "modules",\r
- interp->modules);\r
-\r
- _PyImport_Init();\r
-\r
- /* initialize builtin exceptions */\r
- _PyExc_Init();\r
- _PyImport_FixupExtension("exceptions", "exceptions");\r
-\r
- /* phase 2 of builtins */\r
- _PyImport_FixupExtension("__builtin__", "__builtin__");\r
-\r
- _PyImportHooks_Init();\r
-\r
- if (install_sigs)\r
- initsigs(); /* Signal handling stuff, including initintr() */\r
-\r
- /* Initialize warnings. */\r
- _PyWarnings_Init();\r
- if (PySys_HasWarnOptions()) {\r
- PyObject *warnings_module = PyImport_ImportModule("warnings");\r
- if (!warnings_module)\r
- PyErr_Clear();\r
- Py_XDECREF(warnings_module);\r
- }\r
-\r
- initmain(); /* Module __main__ */\r
-\r
- /* auto-thread-state API, if available */\r
-#ifdef WITH_THREAD\r
- _PyGILState_Init(interp, tstate);\r
-#endif /* WITH_THREAD */\r
-\r
- if (!Py_NoSiteFlag)\r
- initsite(); /* Module site */\r
-\r
- if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {\r
- p = icodeset = codeset = strdup(p);\r
- free_codeset = 1;\r
- errors = strchr(p, ':');\r
- if (errors) {\r
- *errors = '\0';\r
- errors++;\r
- }\r
- overridden = 1;\r
- }\r
-\r
-#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)\r
- /* On Unix, set the file system encoding according to the\r
- user's preference, if the CODESET names a well-known\r
- Python codec, and Py_FileSystemDefaultEncoding isn't\r
- initialized by other means. Also set the encoding of\r
- stdin and stdout if these are terminals, unless overridden. */\r
-\r
- if (!overridden || !Py_FileSystemDefaultEncoding) {\r
- saved_locale = strdup(setlocale(LC_CTYPE, NULL));\r
- setlocale(LC_CTYPE, "");\r
- loc_codeset = nl_langinfo(CODESET);\r
- if (loc_codeset && *loc_codeset) {\r
- PyObject *enc = PyCodec_Encoder(loc_codeset);\r
- if (enc) {\r
- loc_codeset = strdup(loc_codeset);\r
- Py_DECREF(enc);\r
- } else {\r
- if (PyErr_ExceptionMatches(PyExc_LookupError)) {\r
- PyErr_Clear();\r
- loc_codeset = NULL;\r
- } else {\r
- PyErr_Print();\r
- exit(1);\r
- }\r
- }\r
- } else\r
- loc_codeset = NULL;\r
- setlocale(LC_CTYPE, saved_locale);\r
- free(saved_locale);\r
-\r
- if (!overridden) {\r
- codeset = icodeset = loc_codeset;\r
- free_codeset = 1;\r
- }\r
-\r
- /* Initialize Py_FileSystemDefaultEncoding from\r
- locale even if PYTHONIOENCODING is set. */\r
- if (!Py_FileSystemDefaultEncoding) {\r
- Py_FileSystemDefaultEncoding = loc_codeset;\r
- if (!overridden)\r
- free_codeset = 0;\r
- }\r
- }\r
-#endif\r
-\r
-#ifdef MS_WINDOWS\r
- if (!overridden) {\r
- icodeset = ibuf;\r
- codeset = buf;\r
- sprintf(ibuf, "cp%d", GetConsoleCP());\r
- sprintf(buf, "cp%d", GetConsoleOutputCP());\r
- }\r
-#endif\r
-\r
- if (codeset) {\r
- sys_stream = PySys_GetObject("stdin");\r
- sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");\r
- if (!sys_isatty)\r
- PyErr_Clear();\r
- if ((overridden ||\r
- (sys_isatty && PyObject_IsTrue(sys_isatty))) &&\r
- PyFile_Check(sys_stream)) {\r
- if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))\r
- Py_FatalError("Cannot set codeset of stdin");\r
- }\r
- Py_XDECREF(sys_isatty);\r
-\r
- sys_stream = PySys_GetObject("stdout");\r
- sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");\r
- if (!sys_isatty)\r
- PyErr_Clear();\r
- if ((overridden ||\r
- (sys_isatty && PyObject_IsTrue(sys_isatty))) &&\r
- PyFile_Check(sys_stream)) {\r
- if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))\r
- Py_FatalError("Cannot set codeset of stdout");\r
- }\r
- Py_XDECREF(sys_isatty);\r
-\r
- sys_stream = PySys_GetObject("stderr");\r
- sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");\r
- if (!sys_isatty)\r
- PyErr_Clear();\r
- if((overridden ||\r
- (sys_isatty && PyObject_IsTrue(sys_isatty))) &&\r
- PyFile_Check(sys_stream)) {\r
- if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))\r
- Py_FatalError("Cannot set codeset of stderr");\r
- }\r
- Py_XDECREF(sys_isatty);\r
-\r
- if (free_codeset)\r
- free(codeset);\r
- }\r
-}\r
-\r
-void\r
-Py_Initialize(void)\r
-{\r
- Py_InitializeEx(1);\r
-}\r
-\r
-\r
-#ifdef COUNT_ALLOCS\r
-extern void dump_counts(FILE*);\r
-#endif\r
-\r
-/* Undo the effect of Py_Initialize().\r
-\r
- Beware: if multiple interpreter and/or thread states exist, these\r
- are not wiped out; only the current thread and interpreter state\r
- are deleted. But since everything else is deleted, those other\r
- interpreter and thread states should no longer be used.\r
-\r
- (XXX We should do better, e.g. wipe out all interpreters and\r
- threads.)\r
-\r
- Locking: as above.\r
-\r
-*/\r
-\r
-void\r
-Py_Finalize(void)\r
-{\r
- PyInterpreterState *interp;\r
- PyThreadState *tstate;\r
-\r
- if (!initialized)\r
- return;\r
-\r
- wait_for_thread_shutdown();\r
-\r
- /* The interpreter is still entirely intact at this point, and the\r
- * exit funcs may be relying on that. In particular, if some thread\r
- * or exit func is still waiting to do an import, the import machinery\r
- * expects Py_IsInitialized() to return true. So don't say the\r
- * interpreter is uninitialized until after the exit funcs have run.\r
- * Note that Threading.py uses an exit func to do a join on all the\r
- * threads created thru it, so this also protects pending imports in\r
- * the threads created via Threading.\r
- */\r
- call_sys_exitfunc();\r
- initialized = 0;\r
-\r
- /* Get current thread state and interpreter pointer */\r
- tstate = PyThreadState_GET();\r
- interp = tstate->interp;\r
-\r
- /* Disable signal handling */\r
- PyOS_FiniInterrupts();\r
-\r
- /* Clear type lookup cache */\r
- PyType_ClearCache();\r
-\r
- /* Collect garbage. This may call finalizers; it's nice to call these\r
- * before all modules are destroyed.\r
- * XXX If a __del__ or weakref callback is triggered here, and tries to\r
- * XXX import a module, bad things can happen, because Python no\r
- * XXX longer believes it's initialized.\r
- * XXX Fatal Python error: Interpreter not initialized (version mismatch?)\r
- * XXX is easy to provoke that way. I've also seen, e.g.,\r
- * XXX Exception exceptions.ImportError: 'No module named sha'\r
- * XXX in <function callback at 0x008F5718> ignored\r
- * XXX but I'm unclear on exactly how that one happens. In any case,\r
- * XXX I haven't seen a real-life report of either of these.\r
- */\r
- PyGC_Collect();\r
-#ifdef COUNT_ALLOCS\r
- /* With COUNT_ALLOCS, it helps to run GC multiple times:\r
- each collection might release some types from the type\r
- list, so they become garbage. */\r
- while (PyGC_Collect() > 0)\r
- /* nothing */;\r
-#endif\r
-\r
- /* Destroy all modules */\r
- PyImport_Cleanup();\r
-\r
- /* Collect final garbage. This disposes of cycles created by\r
- * new-style class definitions, for example.\r
- * XXX This is disabled because it caused too many problems. If\r
- * XXX a __del__ or weakref callback triggers here, Python code has\r
- * XXX a hard time running, because even the sys module has been\r
- * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).\r
- * XXX One symptom is a sequence of information-free messages\r
- * XXX coming from threads (if a __del__ or callback is invoked,\r
- * XXX other threads can execute too, and any exception they encounter\r
- * XXX triggers a comedy of errors as subsystem after subsystem\r
- * XXX fails to find what it *expects* to find in sys to help report\r
- * XXX the exception and consequent unexpected failures). I've also\r
- * XXX seen segfaults then, after adding print statements to the\r
- * XXX Python code getting called.\r
- */\r
-#if 0\r
- PyGC_Collect();\r
-#endif\r
-\r
- /* Destroy the database used by _PyImport_{Fixup,Find}Extension */\r
- _PyImport_Fini();\r
-\r
- /* Debugging stuff */\r
-#ifdef COUNT_ALLOCS\r
- dump_counts(stdout);\r
-#endif\r
-\r
- PRINT_TOTAL_REFS();\r
-\r
-#ifdef Py_TRACE_REFS\r
- /* Display all objects still alive -- this can invoke arbitrary\r
- * __repr__ overrides, so requires a mostly-intact interpreter.\r
- * Alas, a lot of stuff may still be alive now that will be cleaned\r
- * up later.\r
- */\r
- if (Py_GETENV("PYTHONDUMPREFS"))\r
- _Py_PrintReferences(stderr);\r
-#endif /* Py_TRACE_REFS */\r
-\r
- /* Clear interpreter state */\r
- PyInterpreterState_Clear(interp);\r
-\r
- /* Now we decref the exception classes. After this point nothing\r
- can raise an exception. That's okay, because each Fini() method\r
- below has been checked to make sure no exceptions are ever\r
- raised.\r
- */\r
-\r
- _PyExc_Fini();\r
-\r
- /* Cleanup auto-thread-state */\r
-#ifdef WITH_THREAD\r
- _PyGILState_Fini();\r
-#endif /* WITH_THREAD */\r
-\r
- /* Delete current thread */\r
- PyThreadState_Swap(NULL);\r
- PyInterpreterState_Delete(interp);\r
-\r
- /* Sundry finalizers */\r
- PyMethod_Fini();\r
- PyFrame_Fini();\r
- PyCFunction_Fini();\r
- PyTuple_Fini();\r
- PyList_Fini();\r
- PySet_Fini();\r
- PyString_Fini();\r
- PyByteArray_Fini();\r
- PyInt_Fini();\r
- PyFloat_Fini();\r
- PyDict_Fini();\r
- _PyRandom_Fini();\r
-\r
-#ifdef Py_USING_UNICODE\r
- /* Cleanup Unicode implementation */\r
- _PyUnicode_Fini();\r
-#endif\r
-\r
- /* XXX Still allocated:\r
- - various static ad-hoc pointers to interned strings\r
- - int and float free list blocks\r
- - whatever various modules and libraries allocate\r
- */\r
-\r
- PyGrammar_RemoveAccelerators(&_PyParser_Grammar);\r
-\r
-#ifdef Py_TRACE_REFS\r
- /* Display addresses (& refcnts) of all objects still alive.\r
- * An address can be used to find the repr of the object, printed\r
- * above by _Py_PrintReferences.\r
- */\r
- if (Py_GETENV("PYTHONDUMPREFS"))\r
- _Py_PrintReferenceAddresses(stderr);\r
-#endif /* Py_TRACE_REFS */\r
-#ifdef PYMALLOC_DEBUG\r
- if (Py_GETENV("PYTHONMALLOCSTATS"))\r
- _PyObject_DebugMallocStats();\r
-#endif\r
-\r
- call_ll_exitfuncs();\r
-}\r
-\r
-/* Create and initialize a new interpreter and thread, and return the\r
- new thread. This requires that Py_Initialize() has been called\r
- first.\r
-\r
- Unsuccessful initialization yields a NULL pointer. Note that *no*\r
- exception information is available even in this case -- the\r
- exception information is held in the thread, and there is no\r
- thread.\r
-\r
- Locking: as above.\r
-\r
-*/\r
-\r
-PyThreadState *\r
-Py_NewInterpreter(void)\r
-{\r
- PyInterpreterState *interp;\r
- PyThreadState *tstate, *save_tstate;\r
- PyObject *bimod, *sysmod;\r
-\r
- if (!initialized)\r
- Py_FatalError("Py_NewInterpreter: call Py_Initialize first");\r
-\r
- interp = PyInterpreterState_New();\r
- if (interp == NULL)\r
- return NULL;\r
-\r
- tstate = PyThreadState_New(interp);\r
- if (tstate == NULL) {\r
- PyInterpreterState_Delete(interp);\r
- return NULL;\r
- }\r
-\r
- save_tstate = PyThreadState_Swap(tstate);\r
-\r
- /* XXX The following is lax in error checking */\r
-\r
- interp->modules = PyDict_New();\r
- interp->modules_reloading = PyDict_New();\r
-\r
- bimod = _PyImport_FindExtension("__builtin__", "__builtin__");\r
- if (bimod != NULL) {\r
- interp->builtins = PyModule_GetDict(bimod);\r
- if (interp->builtins == NULL)\r
- goto handle_error;\r
- Py_INCREF(interp->builtins);\r
- }\r
- sysmod = _PyImport_FindExtension("sys", "sys");\r
- if (bimod != NULL && sysmod != NULL) {\r
- interp->sysdict = PyModule_GetDict(sysmod);\r
- if (interp->sysdict == NULL)\r
- goto handle_error;\r
- Py_INCREF(interp->sysdict);\r
- PySys_SetPath(Py_GetPath());\r
- PyDict_SetItemString(interp->sysdict, "modules",\r
- interp->modules);\r
- _PyImportHooks_Init();\r
- initmain();\r
- if (!Py_NoSiteFlag)\r
- initsite();\r
- }\r
-\r
- if (!PyErr_Occurred())\r
- return tstate;\r
-\r
-handle_error:\r
- /* Oops, it didn't work. Undo it all. */\r
-\r
- PyErr_Print();\r
- PyThreadState_Clear(tstate);\r
- PyThreadState_Swap(save_tstate);\r
- PyThreadState_Delete(tstate);\r
- PyInterpreterState_Delete(interp);\r
-\r
- return NULL;\r
-}\r
-\r
-/* Delete an interpreter and its last thread. This requires that the\r
- given thread state is current, that the thread has no remaining\r
- frames, and that it is its interpreter's only remaining thread.\r
- It is a fatal error to violate these constraints.\r
-\r
- (Py_Finalize() doesn't have these constraints -- it zaps\r
- everything, regardless.)\r
-\r
- Locking: as above.\r
-\r
-*/\r
-\r
-void\r
-Py_EndInterpreter(PyThreadState *tstate)\r
-{\r
- PyInterpreterState *interp = tstate->interp;\r
-\r
- if (tstate != PyThreadState_GET())\r
- Py_FatalError("Py_EndInterpreter: thread is not current");\r
- if (tstate->frame != NULL)\r
- Py_FatalError("Py_EndInterpreter: thread still has a frame");\r
- if (tstate != interp->tstate_head || tstate->next != NULL)\r
- Py_FatalError("Py_EndInterpreter: not the last thread");\r
-\r
- PyImport_Cleanup();\r
- PyInterpreterState_Clear(interp);\r
- PyThreadState_Swap(NULL);\r
- PyInterpreterState_Delete(interp);\r
-}\r
-\r
-static char *progname = "python";\r
-\r
-void\r
-Py_SetProgramName(char *pn)\r
-{\r
- if (pn && *pn)\r
- progname = pn;\r
-}\r
-\r
-char *\r
-Py_GetProgramName(void)\r
-{\r
- return progname;\r
-}\r
-\r
-static char *default_home = NULL;\r
-\r
-void\r
-Py_SetPythonHome(char *home)\r
-{\r
- default_home = home;\r
-}\r
-\r
-char *\r
-Py_GetPythonHome(void)\r
-{\r
- char *home = default_home;\r
- if (home == NULL && !Py_IgnoreEnvironmentFlag)\r
- home = Py_GETENV("PYTHONHOME");\r
- return home;\r
-}\r
-\r
-/* Create __main__ module */\r
-\r
-static void\r
-initmain(void)\r
-{\r
- PyObject *m, *d;\r
- m = PyImport_AddModule("__main__");\r
- if (m == NULL)\r
- Py_FatalError("can't create __main__ module");\r
- d = PyModule_GetDict(m);\r
- if (PyDict_GetItemString(d, "__builtins__") == NULL) {\r
- PyObject *bimod = PyImport_ImportModule("__builtin__");\r
- if (bimod == NULL ||\r
- PyDict_SetItemString(d, "__builtins__", bimod) != 0)\r
- Py_FatalError("can't add __builtins__ to __main__");\r
- Py_XDECREF(bimod);\r
- }\r
-}\r
-\r
-/* Import the site module (not into __main__ though) */\r
-\r
-static void\r
-initsite(void)\r
-{\r
- PyObject *m;\r
- m = PyImport_ImportModule("site");\r
- if (m == NULL) {\r
- PyErr_Print();\r
- Py_Finalize();\r
- exit(1);\r
- }\r
- else {\r
- Py_DECREF(m);\r
- }\r
-}\r
-\r
-/* Parse input from a file and execute it */\r
-\r
-int\r
-PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,\r
- PyCompilerFlags *flags)\r
-{\r
- if (filename == NULL)\r
- filename = "???";\r
- if (Py_FdIsInteractive(fp, filename)) {\r
- int err = PyRun_InteractiveLoopFlags(fp, filename, flags);\r
- if (closeit)\r
- fclose(fp);\r
- return err;\r
- }\r
- else\r
- return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);\r
-}\r
-\r
-int\r
-PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)\r
-{\r
- PyObject *v;\r
- int ret;\r
- PyCompilerFlags local_flags;\r
-\r
- if (flags == NULL) {\r
- flags = &local_flags;\r
- local_flags.cf_flags = 0;\r
- }\r
- v = PySys_GetObject("ps1");\r
- if (v == NULL) {\r
- PySys_SetObject("ps1", v = PyString_FromString(">>> "));\r
- Py_XDECREF(v);\r
- }\r
- v = PySys_GetObject("ps2");\r
- if (v == NULL) {\r
- PySys_SetObject("ps2", v = PyString_FromString("... "));\r
- Py_XDECREF(v);\r
- }\r
- for (;;) {\r
- ret = PyRun_InteractiveOneFlags(fp, filename, flags);\r
- PRINT_TOTAL_REFS();\r
- if (ret == E_EOF)\r
- return 0;\r
- /*\r
- if (ret == E_NOMEM)\r
- return -1;\r
- */\r
- }\r
-}\r
-\r
-#if 0\r
-/* compute parser flags based on compiler flags */\r
-#define PARSER_FLAGS(flags) \\r
- ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \\r
- PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)\r
-#endif\r
-#if 1\r
-/* Keep an example of flags with future keyword support. */\r
-#define PARSER_FLAGS(flags) \\r
- ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \\r
- PyPARSE_DONT_IMPLY_DEDENT : 0) \\r
- | (((flags)->cf_flags & CO_FUTURE_PRINT_FUNCTION) ? \\r
- PyPARSE_PRINT_IS_FUNCTION : 0) \\r
- | (((flags)->cf_flags & CO_FUTURE_UNICODE_LITERALS) ? \\r
- PyPARSE_UNICODE_LITERALS : 0) \\r
- ) : 0)\r
-#endif\r
-\r
-int\r
-PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)\r
-{\r
- PyObject *m, *d, *v, *w;\r
- mod_ty mod;\r
- PyArena *arena;\r
- char *ps1 = "", *ps2 = "";\r
- int errcode = 0;\r
-\r
- v = PySys_GetObject("ps1");\r
- if (v != NULL) {\r
- v = PyObject_Str(v);\r
- if (v == NULL)\r
- PyErr_Clear();\r
- else if (PyString_Check(v))\r
- ps1 = PyString_AsString(v);\r
- }\r
- w = PySys_GetObject("ps2");\r
- if (w != NULL) {\r
- w = PyObject_Str(w);\r
- if (w == NULL)\r
- PyErr_Clear();\r
- else if (PyString_Check(w))\r
- ps2 = PyString_AsString(w);\r
- }\r
- arena = PyArena_New();\r
- if (arena == NULL) {\r
- Py_XDECREF(v);\r
- Py_XDECREF(w);\r
- return -1;\r
- }\r
- mod = PyParser_ASTFromFile(fp, filename,\r
- Py_single_input, ps1, ps2,\r
- flags, &errcode, arena);\r
- Py_XDECREF(v);\r
- Py_XDECREF(w);\r
- if (mod == NULL) {\r
- PyArena_Free(arena);\r
- if (errcode == E_EOF) {\r
- PyErr_Clear();\r
- return E_EOF;\r
- }\r
- PyErr_Print();\r
- return -1;\r
- }\r
- m = PyImport_AddModule("__main__");\r
- if (m == NULL) {\r
- PyArena_Free(arena);\r
- return -1;\r
- }\r
- d = PyModule_GetDict(m);\r
- v = run_mod(mod, filename, d, d, flags, arena);\r
- PyArena_Free(arena);\r
- if (v == NULL) {\r
- PyErr_Print();\r
- return -1;\r
- }\r
- Py_DECREF(v);\r
- if (Py_FlushLine())\r
- PyErr_Clear();\r
- return 0;\r
-}\r
-\r
-/* Check whether a file maybe a pyc file: Look at the extension,\r
- the file type, and, if we may close it, at the first few bytes. */\r
-\r
-static int\r
-maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)\r
-{\r
- if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)\r
- return 1;\r
-\r
- /* Only look into the file if we are allowed to close it, since\r
- it then should also be seekable. */\r
- if (closeit) {\r
- /* Read only two bytes of the magic. If the file was opened in\r
- text mode, the bytes 3 and 4 of the magic (\r\n) might not\r
- be read as they are on disk. */\r
- unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;\r
- unsigned char buf[2];\r
- /* Mess: In case of -x, the stream is NOT at its start now,\r
- and ungetc() was used to push back the first newline,\r
- which makes the current stream position formally undefined,\r
- and a x-platform nightmare.\r
- Unfortunately, we have no direct way to know whether -x\r
- was specified. So we use a terrible hack: if the current\r
- stream position is not 0, we assume -x was specified, and\r
- give up. Bug 132850 on SourceForge spells out the\r
- hopelessness of trying anything else (fseek and ftell\r
- don't work predictably x-platform for text-mode files).\r
- */\r
- int ispyc = 0;\r
- if (ftell(fp) == 0) {\r
- if (fread(buf, 1, 2, fp) == 2 &&\r
- ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)\r
- ispyc = 1;\r
- rewind(fp);\r
- }\r
- return ispyc;\r
- }\r
- return 0;\r
-}\r
-\r
-int\r
-PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,\r
- PyCompilerFlags *flags)\r
-{\r
- PyObject *m, *d, *v;\r
- const char *ext;\r
- int set_file_name = 0, len, ret = -1;\r
-\r
- m = PyImport_AddModule("__main__");\r
- if (m == NULL)\r
- return -1;\r
- Py_INCREF(m);\r
- d = PyModule_GetDict(m);\r
- if (PyDict_GetItemString(d, "__file__") == NULL) {\r
- PyObject *f = PyString_FromString(filename);\r
- if (f == NULL)\r
- goto done;\r
- if (PyDict_SetItemString(d, "__file__", f) < 0) {\r
- Py_DECREF(f);\r
- goto done;\r
- }\r
- set_file_name = 1;\r
- Py_DECREF(f);\r
- }\r
- len = strlen(filename);\r
- ext = filename + len - (len > 4 ? 4 : 0);\r
- if (maybe_pyc_file(fp, filename, ext, closeit)) {\r
- /* Try to run a pyc file. First, re-open in binary */\r
- if (closeit)\r
- fclose(fp);\r
- if ((fp = fopen(filename, "rb")) == NULL) {\r
- fprintf(stderr, "python: Can't reopen .pyc file\n");\r
- goto done;\r
- }\r
- /* Turn on optimization if a .pyo file is given */\r
- if (strcmp(ext, ".pyo") == 0)\r
- Py_OptimizeFlag = 1;\r
- v = run_pyc_file(fp, filename, d, d, flags);\r
- } else {\r
- v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,\r
- closeit, flags);\r
- }\r
- if (v == NULL) {\r
- PyErr_Print();\r
- goto done;\r
- }\r
- Py_DECREF(v);\r
- if (Py_FlushLine())\r
- PyErr_Clear();\r
- ret = 0;\r
- done:\r
- if (set_file_name && PyDict_DelItemString(d, "__file__"))\r
- PyErr_Clear();\r
- Py_DECREF(m);\r
- return ret;\r
-}\r
-\r
-int\r
-PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)\r
-{\r
- PyObject *m, *d, *v;\r
- m = PyImport_AddModule("__main__");\r
- if (m == NULL)\r
- return -1;\r
- d = PyModule_GetDict(m);\r
- v = PyRun_StringFlags(command, Py_file_input, d, d, flags);\r
- if (v == NULL) {\r
- PyErr_Print();\r
- return -1;\r
- }\r
- Py_DECREF(v);\r
- if (Py_FlushLine())\r
- PyErr_Clear();\r
- return 0;\r
-}\r
-\r
-static int\r
-parse_syntax_error(PyObject *err, PyObject **message, const char **filename,\r
- int *lineno, int *offset, const char **text)\r
-{\r
- long hold;\r
- PyObject *v;\r
-\r
- /* old style errors */\r
- if (PyTuple_Check(err))\r
- return PyArg_ParseTuple(err, "O(ziiz)", message, filename,\r
- lineno, offset, text);\r
-\r
- *message = NULL;\r
-\r
- /* new style errors. `err' is an instance */\r
- *message = PyObject_GetAttrString(err, "msg");\r
- if (!*message)\r
- goto finally;\r
-\r
- v = PyObject_GetAttrString(err, "filename");\r
- if (!v)\r
- goto finally;\r
- if (v == Py_None) {\r
- Py_DECREF(v);\r
- *filename = NULL;\r
- }\r
- else {\r
- *filename = PyString_AsString(v);\r
- Py_DECREF(v);\r
- if (!*filename)\r
- goto finally;\r
- }\r
-\r
- v = PyObject_GetAttrString(err, "lineno");\r
- if (!v)\r
- goto finally;\r
- hold = PyInt_AsLong(v);\r
- Py_DECREF(v);\r
- if (hold < 0 && PyErr_Occurred())\r
- goto finally;\r
- *lineno = (int)hold;\r
-\r
- v = PyObject_GetAttrString(err, "offset");\r
- if (!v)\r
- goto finally;\r
- if (v == Py_None) {\r
- *offset = -1;\r
- Py_DECREF(v);\r
- } else {\r
- hold = PyInt_AsLong(v);\r
- Py_DECREF(v);\r
- if (hold < 0 && PyErr_Occurred())\r
- goto finally;\r
- *offset = (int)hold;\r
- }\r
-\r
- v = PyObject_GetAttrString(err, "text");\r
- if (!v)\r
- goto finally;\r
- if (v == Py_None) {\r
- Py_DECREF(v);\r
- *text = NULL;\r
- }\r
- else {\r
- *text = PyString_AsString(v);\r
- Py_DECREF(v);\r
- if (!*text)\r
- goto finally;\r
- }\r
- return 1;\r
-\r
-finally:\r
- Py_XDECREF(*message);\r
- return 0;\r
-}\r
-\r
-void\r
-PyErr_Print(void)\r
-{\r
- PyErr_PrintEx(1);\r
-}\r
-\r
-static void\r
-print_error_text(PyObject *f, int offset, const char *text)\r
-{\r
- char *nl;\r
- if (offset >= 0) {\r
- if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')\r
- offset--;\r
- for (;;) {\r
- nl = strchr(text, '\n');\r
- if (nl == NULL || nl-text >= offset)\r
- break;\r
- offset -= (int)(nl+1-text);\r
- text = nl+1;\r
- }\r
- while (*text == ' ' || *text == '\t') {\r
- text++;\r
- offset--;\r
- }\r
- }\r
- PyFile_WriteString(" ", f);\r
- PyFile_WriteString(text, f);\r
- if (*text == '\0' || text[strlen(text)-1] != '\n')\r
- PyFile_WriteString("\n", f);\r
- if (offset == -1)\r
- return;\r
- PyFile_WriteString(" ", f);\r
- offset--;\r
- while (offset > 0) {\r
- PyFile_WriteString(" ", f);\r
- offset--;\r
- }\r
- PyFile_WriteString("^\n", f);\r
-}\r
-\r
-static void\r
-handle_system_exit(void)\r
-{\r
- PyObject *exception, *value, *tb;\r
- int exitcode = 0;\r
-\r
- if (Py_InspectFlag)\r
- /* Don't exit if -i flag was given. This flag is set to 0\r
- * when entering interactive mode for inspecting. */\r
- return;\r
-\r
- PyErr_Fetch(&exception, &value, &tb);\r
- if (Py_FlushLine())\r
- PyErr_Clear();\r
- fflush(stdout);\r
- if (value == NULL || value == Py_None)\r
- goto done;\r
- if (PyExceptionInstance_Check(value)) {\r
- /* The error code should be in the `code' attribute. */\r
- PyObject *code = PyObject_GetAttrString(value, "code");\r
- if (code) {\r
- Py_DECREF(value);\r
- value = code;\r
- if (value == Py_None)\r
- goto done;\r
- }\r
- /* If we failed to dig out the 'code' attribute,\r
- just let the else clause below print the error. */\r
- }\r
- if (PyInt_Check(value))\r
- exitcode = (int)PyInt_AsLong(value);\r
- else {\r
- PyObject *sys_stderr = PySys_GetObject("stderr");\r
- if (sys_stderr != NULL && sys_stderr != Py_None) {\r
- PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);\r
- } else {\r
- PyObject_Print(value, stderr, Py_PRINT_RAW);\r
- fflush(stderr);\r
- }\r
- PySys_WriteStderr("\n");\r
- exitcode = 1;\r
- }\r
- done:\r
- /* Restore and clear the exception info, in order to properly decref\r
- * the exception, value, and traceback. If we just exit instead,\r
- * these leak, which confuses PYTHONDUMPREFS output, and may prevent\r
- * some finalizers from running.\r
- */\r
- PyErr_Restore(exception, value, tb);\r
- PyErr_Clear();\r
- Py_Exit(exitcode);\r
- /* NOTREACHED */\r
-}\r
-\r
-void\r
-PyErr_PrintEx(int set_sys_last_vars)\r
-{\r
- PyObject *exception, *v, *tb, *hook;\r
-\r
- if (PyErr_ExceptionMatches(PyExc_SystemExit)) {\r
- handle_system_exit();\r
- }\r
- PyErr_Fetch(&exception, &v, &tb);\r
- if (exception == NULL)\r
- return;\r
- PyErr_NormalizeException(&exception, &v, &tb);\r
- if (exception == NULL)\r
- return;\r
- /* Now we know v != NULL too */\r
- if (set_sys_last_vars) {\r
- PySys_SetObject("last_type", exception);\r
- PySys_SetObject("last_value", v);\r
- PySys_SetObject("last_traceback", tb);\r
- }\r
- hook = PySys_GetObject("excepthook");\r
- if (hook && hook != Py_None) {\r
- PyObject *args = PyTuple_Pack(3,\r
- exception, v, tb ? tb : Py_None);\r
- PyObject *result = PyEval_CallObject(hook, args);\r
- if (result == NULL) {\r
- PyObject *exception2, *v2, *tb2;\r
- if (PyErr_ExceptionMatches(PyExc_SystemExit)) {\r
- handle_system_exit();\r
- }\r
- PyErr_Fetch(&exception2, &v2, &tb2);\r
- PyErr_NormalizeException(&exception2, &v2, &tb2);\r
- /* It should not be possible for exception2 or v2\r
- to be NULL. However PyErr_Display() can't\r
- tolerate NULLs, so just be safe. */\r
- if (exception2 == NULL) {\r
- exception2 = Py_None;\r
- Py_INCREF(exception2);\r
- }\r
- if (v2 == NULL) {\r
- v2 = Py_None;\r
- Py_INCREF(v2);\r
- }\r
- if (Py_FlushLine())\r
- PyErr_Clear();\r
- fflush(stdout);\r
- PySys_WriteStderr("Error in sys.excepthook:\n");\r
- PyErr_Display(exception2, v2, tb2);\r
- PySys_WriteStderr("\nOriginal exception was:\n");\r
- PyErr_Display(exception, v, tb);\r
- Py_DECREF(exception2);\r
- Py_DECREF(v2);\r
- Py_XDECREF(tb2);\r
- }\r
- Py_XDECREF(result);\r
- Py_XDECREF(args);\r
- } else {\r
- PySys_WriteStderr("sys.excepthook is missing\n");\r
- PyErr_Display(exception, v, tb);\r
- }\r
- Py_XDECREF(exception);\r
- Py_XDECREF(v);\r
- Py_XDECREF(tb);\r
-}\r
-\r
-void\r
-PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)\r
-{\r
- int err = 0;\r
- PyObject *f = PySys_GetObject("stderr");\r
- Py_INCREF(value);\r
- if (f == NULL || f == Py_None)\r
- fprintf(stderr, "lost sys.stderr\n");\r
- else {\r
- if (Py_FlushLine())\r
- PyErr_Clear();\r
- fflush(stdout);\r
- if (tb && tb != Py_None)\r
- err = PyTraceBack_Print(tb, f);\r
- if (err == 0 &&\r
- PyObject_HasAttrString(value, "print_file_and_line"))\r
- {\r
- PyObject *message;\r
- const char *filename, *text;\r
- int lineno, offset;\r
- if (!parse_syntax_error(value, &message, &filename,\r
- &lineno, &offset, &text))\r
- PyErr_Clear();\r
- else {\r
- char buf[10];\r
- PyFile_WriteString(" File \"", f);\r
- if (filename == NULL)\r
- PyFile_WriteString("<string>", f);\r
- else\r
- PyFile_WriteString(filename, f);\r
- PyFile_WriteString("\", line ", f);\r
- PyOS_snprintf(buf, sizeof(buf), "%d", lineno);\r
- PyFile_WriteString(buf, f);\r
- PyFile_WriteString("\n", f);\r
- if (text != NULL)\r
- print_error_text(f, offset, text);\r
- Py_DECREF(value);\r
- value = message;\r
- /* Can't be bothered to check all those\r
- PyFile_WriteString() calls */\r
- if (PyErr_Occurred())\r
- err = -1;\r
- }\r
- }\r
- if (err) {\r
- /* Don't do anything else */\r
- }\r
- else if (PyExceptionClass_Check(exception)) {\r
- PyObject* moduleName;\r
- char* className = PyExceptionClass_Name(exception);\r
- if (className != NULL) {\r
- char *dot = strrchr(className, '.');\r
- if (dot != NULL)\r
- className = dot+1;\r
- }\r
-\r
- moduleName = PyObject_GetAttrString(exception, "__module__");\r
- if (moduleName == NULL)\r
- err = PyFile_WriteString("<unknown>", f);\r
- else {\r
- char* modstr = PyString_AsString(moduleName);\r
- if (modstr && strcmp(modstr, "exceptions"))\r
- {\r
- err = PyFile_WriteString(modstr, f);\r
- err += PyFile_WriteString(".", f);\r
- }\r
- Py_DECREF(moduleName);\r
- }\r
- if (err == 0) {\r
- if (className == NULL)\r
- err = PyFile_WriteString("<unknown>", f);\r
- else\r
- err = PyFile_WriteString(className, f);\r
- }\r
- }\r
- else\r
- err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);\r
- if (err == 0 && (value != Py_None)) {\r
- PyObject *s = PyObject_Str(value);\r
- /* only print colon if the str() of the\r
- object is not the empty string\r
- */\r
- if (s == NULL)\r
- err = -1;\r
- else if (!PyString_Check(s) ||\r
- PyString_GET_SIZE(s) != 0)\r
- err = PyFile_WriteString(": ", f);\r
- if (err == 0)\r
- err = PyFile_WriteObject(s, f, Py_PRINT_RAW);\r
- Py_XDECREF(s);\r
- }\r
- /* try to write a newline in any case */\r
- err += PyFile_WriteString("\n", f);\r
- }\r
- Py_DECREF(value);\r
- /* If an error happened here, don't show it.\r
- XXX This is wrong, but too many callers rely on this behavior. */\r
- if (err != 0)\r
- PyErr_Clear();\r
-}\r
-\r
-PyObject *\r
-PyRun_StringFlags(const char *str, int start, PyObject *globals,\r
- PyObject *locals, PyCompilerFlags *flags)\r
-{\r
- PyObject *ret = NULL;\r
- mod_ty mod;\r
- PyArena *arena = PyArena_New();\r
- if (arena == NULL)\r
- return NULL;\r
-\r
- mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);\r
- if (mod != NULL)\r
- ret = run_mod(mod, "<string>", globals, locals, flags, arena);\r
- PyArena_Free(arena);\r
- return ret;\r
-}\r
-\r
-PyObject *\r
-PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,\r
- PyObject *locals, int closeit, PyCompilerFlags *flags)\r
-{\r
- PyObject *ret;\r
- mod_ty mod;\r
- PyArena *arena = PyArena_New();\r
- if (arena == NULL)\r
- return NULL;\r
-\r
- mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,\r
- flags, NULL, arena);\r
- if (closeit)\r
- fclose(fp);\r
- if (mod == NULL) {\r
- PyArena_Free(arena);\r
- return NULL;\r
- }\r
- ret = run_mod(mod, filename, globals, locals, flags, arena);\r
- PyArena_Free(arena);\r
- return ret;\r
-}\r
-\r
-static PyObject *\r
-run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,\r
- PyCompilerFlags *flags, PyArena *arena)\r
-{\r
- PyCodeObject *co;\r
- PyObject *v;\r
- co = PyAST_Compile(mod, filename, flags, arena);\r
- if (co == NULL)\r
- return NULL;\r
- v = PyEval_EvalCode(co, globals, locals);\r
- Py_DECREF(co);\r
- return v;\r
-}\r
-\r
-static PyObject *\r
-run_pyc_file(FILE *fp, const char *filename, PyObject *globals,\r
- PyObject *locals, PyCompilerFlags *flags)\r
-{\r
- PyCodeObject *co;\r
- PyObject *v;\r
- long magic;\r
- long PyImport_GetMagicNumber(void);\r
-\r
- magic = PyMarshal_ReadLongFromFile(fp);\r
- if (magic != PyImport_GetMagicNumber()) {\r
- PyErr_SetString(PyExc_RuntimeError,\r
- "Bad magic number in .pyc file");\r
- return NULL;\r
- }\r
- (void) PyMarshal_ReadLongFromFile(fp);\r
- v = PyMarshal_ReadLastObjectFromFile(fp);\r
- fclose(fp);\r
- if (v == NULL || !PyCode_Check(v)) {\r
- Py_XDECREF(v);\r
- PyErr_SetString(PyExc_RuntimeError,\r
- "Bad code object in .pyc file");\r
- return NULL;\r
- }\r
- co = (PyCodeObject *)v;\r
- v = PyEval_EvalCode(co, globals, locals);\r
- if (v && flags)\r
- flags->cf_flags |= (co->co_flags & PyCF_MASK);\r
- Py_DECREF(co);\r
- return v;\r
-}\r
-\r
-PyObject *\r
-Py_CompileStringFlags(const char *str, const char *filename, int start,\r
- PyCompilerFlags *flags)\r
-{\r
- PyCodeObject *co;\r
- mod_ty mod;\r
- PyArena *arena = PyArena_New();\r
- if (arena == NULL)\r
- return NULL;\r
-\r
- mod = PyParser_ASTFromString(str, filename, start, flags, arena);\r
- if (mod == NULL) {\r
- PyArena_Free(arena);\r
- return NULL;\r
- }\r
- if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {\r
- PyObject *result = PyAST_mod2obj(mod);\r
- PyArena_Free(arena);\r
- return result;\r
- }\r
- co = PyAST_Compile(mod, filename, flags, arena);\r
- PyArena_Free(arena);\r
- return (PyObject *)co;\r
-}\r
-\r
-struct symtable *\r
-Py_SymtableString(const char *str, const char *filename, int start)\r
-{\r
- struct symtable *st;\r
- mod_ty mod;\r
- PyCompilerFlags flags;\r
- PyArena *arena = PyArena_New();\r
- if (arena == NULL)\r
- return NULL;\r
-\r
- flags.cf_flags = 0;\r
-\r
- mod = PyParser_ASTFromString(str, filename, start, &flags, arena);\r
- if (mod == NULL) {\r
- PyArena_Free(arena);\r
- return NULL;\r
- }\r
- st = PySymtable_Build(mod, filename, 0);\r
- PyArena_Free(arena);\r
- return st;\r
-}\r
-\r
-/* Preferred access to parser is through AST. */\r
-mod_ty\r
-PyParser_ASTFromString(const char *s, const char *filename, int start,\r
- PyCompilerFlags *flags, PyArena *arena)\r
-{\r
- mod_ty mod;\r
- PyCompilerFlags localflags;\r
- perrdetail err;\r
- int iflags = PARSER_FLAGS(flags);\r
-\r
- node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,\r
- &_PyParser_Grammar, start, &err,\r
- &iflags);\r
- if (flags == NULL) {\r
- localflags.cf_flags = 0;\r
- flags = &localflags;\r
- }\r
- if (n) {\r
- flags->cf_flags |= iflags & PyCF_MASK;\r
- mod = PyAST_FromNode(n, flags, filename, arena);\r
- PyNode_Free(n);\r
- return mod;\r
- }\r
- else {\r
- err_input(&err);\r
- return NULL;\r
- }\r
-}\r
-\r
-mod_ty\r
-PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,\r
- char *ps2, PyCompilerFlags *flags, int *errcode,\r
- PyArena *arena)\r
-{\r
- mod_ty mod;\r
- PyCompilerFlags localflags;\r
- perrdetail err;\r
- int iflags = PARSER_FLAGS(flags);\r
-\r
- node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,\r
- start, ps1, ps2, &err, &iflags);\r
- if (flags == NULL) {\r
- localflags.cf_flags = 0;\r
- flags = &localflags;\r
- }\r
- if (n) {\r
- flags->cf_flags |= iflags & PyCF_MASK;\r
- mod = PyAST_FromNode(n, flags, filename, arena);\r
- PyNode_Free(n);\r
- return mod;\r
- }\r
- else {\r
- err_input(&err);\r
- if (errcode)\r
- *errcode = err.error;\r
- return NULL;\r
- }\r
-}\r
-\r
-/* Simplified interface to parsefile -- return node or set exception */\r
-\r
-node *\r
-PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)\r
-{\r
- perrdetail err;\r
- node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,\r
- start, NULL, NULL, &err, flags);\r
- if (n == NULL)\r
- err_input(&err);\r
-\r
- return n;\r
-}\r
-\r
-/* Simplified interface to parsestring -- return node or set exception */\r
-\r
-node *\r
-PyParser_SimpleParseStringFlags(const char *str, int start, int flags)\r
-{\r
- perrdetail err;\r
- node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,\r
- start, &err, flags);\r
- if (n == NULL)\r
- err_input(&err);\r
- return n;\r
-}\r
-\r
-node *\r
-PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,\r
- int start, int flags)\r
-{\r
- perrdetail err;\r
- node *n = PyParser_ParseStringFlagsFilename(str, filename,\r
- &_PyParser_Grammar, start, &err, flags);\r
- if (n == NULL)\r
- err_input(&err);\r
- return n;\r
-}\r
-\r
-node *\r
-PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)\r
-{\r
- return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);\r
-}\r
-\r
-/* May want to move a more generalized form of this to parsetok.c or\r
- even parser modules. */\r
-\r
-void\r
-PyParser_SetError(perrdetail *err)\r
-{\r
- err_input(err);\r
-}\r
-\r
-/* Set the error appropriate to the given input error code (see errcode.h) */\r
-\r
-static void\r
-err_input(perrdetail *err)\r
-{\r
- PyObject *v, *w, *errtype;\r
- PyObject* u = NULL;\r
- char *msg = NULL;\r
- errtype = PyExc_SyntaxError;\r
- switch (err->error) {\r
- case E_ERROR:\r
- return;\r
- case E_SYNTAX:\r
- errtype = PyExc_IndentationError;\r
- if (err->expected == INDENT)\r
- msg = "expected an indented block";\r
- else if (err->token == INDENT)\r
- msg = "unexpected indent";\r
- else if (err->token == DEDENT)\r
- msg = "unexpected unindent";\r
- else {\r
- errtype = PyExc_SyntaxError;\r
- msg = "invalid syntax";\r
- }\r
- break;\r
- case E_TOKEN:\r
- msg = "invalid token";\r
- break;\r
- case E_EOFS:\r
- msg = "EOF while scanning triple-quoted string literal";\r
- break;\r
- case E_EOLS:\r
- msg = "EOL while scanning string literal";\r
- break;\r
- case E_INTR:\r
- if (!PyErr_Occurred())\r
- PyErr_SetNone(PyExc_KeyboardInterrupt);\r
- goto cleanup;\r
- case E_NOMEM:\r
- PyErr_NoMemory();\r
- goto cleanup;\r
- case E_EOF:\r
- msg = "unexpected EOF while parsing";\r
- break;\r
- case E_TABSPACE:\r
- errtype = PyExc_TabError;\r
- msg = "inconsistent use of tabs and spaces in indentation";\r
- break;\r
- case E_OVERFLOW:\r
- msg = "expression too long";\r
- break;\r
- case E_DEDENT:\r
- errtype = PyExc_IndentationError;\r
- msg = "unindent does not match any outer indentation level";\r
- break;\r
- case E_TOODEEP:\r
- errtype = PyExc_IndentationError;\r
- msg = "too many levels of indentation";\r
- break;\r
- case E_DECODE: {\r
- PyObject *type, *value, *tb;\r
- PyErr_Fetch(&type, &value, &tb);\r
- if (value != NULL) {\r
- u = PyObject_Str(value);\r
- if (u != NULL) {\r
- msg = PyString_AsString(u);\r
- }\r
- }\r
- if (msg == NULL)\r
- msg = "unknown decode error";\r
- Py_XDECREF(type);\r
- Py_XDECREF(value);\r
- Py_XDECREF(tb);\r
- break;\r
- }\r
- case E_LINECONT:\r
- msg = "unexpected character after line continuation character";\r
- break;\r
- default:\r
- fprintf(stderr, "error=%d\n", err->error);\r
- msg = "unknown parsing error";\r
- break;\r
- }\r
- v = Py_BuildValue("(ziiz)", err->filename,\r
- err->lineno, err->offset, err->text);\r
- w = NULL;\r
- if (v != NULL)\r
- w = Py_BuildValue("(sO)", msg, v);\r
- Py_XDECREF(u);\r
- Py_XDECREF(v);\r
- PyErr_SetObject(errtype, w);\r
- Py_XDECREF(w);\r
-cleanup:\r
- if (err->text != NULL) {\r
- PyObject_FREE(err->text);\r
- err->text = NULL;\r
- }\r
-}\r
-\r
-/* Print fatal error message and abort */\r
-\r
-void\r
-Py_FatalError(const char *msg)\r
-{\r
- fprintf(stderr, "Fatal Python error: %s\n", msg);\r
- fflush(stderr); /* it helps in Windows debug build */\r
-\r
-#ifdef MS_WINDOWS\r
- {\r
- size_t len = strlen(msg);\r
- WCHAR* buffer;\r
- size_t i;\r
-\r
- /* Convert the message to wchar_t. This uses a simple one-to-one\r
- conversion, assuming that the this error message actually uses ASCII\r
- only. If this ceases to be true, we will have to convert. */\r
- buffer = alloca( (len+1) * (sizeof *buffer));\r
- for( i=0; i<=len; ++i)\r
- buffer[i] = msg[i];\r
- OutputDebugStringW(L"Fatal Python error: ");\r
- OutputDebugStringW(buffer);\r
- OutputDebugStringW(L"\n");\r
- }\r
-#ifdef _DEBUG\r
- DebugBreak();\r
-#endif\r
-#endif /* MS_WINDOWS */\r
- abort();\r
-}\r
-\r
-/* Clean up and exit */\r
-\r
-#ifdef WITH_THREAD\r
-#include "pythread.h"\r
-#endif\r
-\r
-/* Wait until threading._shutdown completes, provided\r
- the threading module was imported in the first place.\r
- The shutdown routine will wait until all non-daemon\r
- "threading" threads have completed. */\r
-static void\r
-wait_for_thread_shutdown(void)\r
-{\r
-#ifdef WITH_THREAD\r
- PyObject *result;\r
- PyThreadState *tstate = PyThreadState_GET();\r
- PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,\r
- "threading");\r
- if (threading == NULL) {\r
- /* threading not imported */\r
- PyErr_Clear();\r
- return;\r
- }\r
- result = PyObject_CallMethod(threading, "_shutdown", "");\r
- if (result == NULL)\r
- PyErr_WriteUnraisable(threading);\r
- else\r
- Py_DECREF(result);\r
- Py_DECREF(threading);\r
-#endif\r
-}\r
-\r
-#define NEXITFUNCS 32\r
-static void (*exitfuncs[NEXITFUNCS])(void);\r
-static int nexitfuncs = 0;\r
-\r
-int Py_AtExit(void (*func)(void))\r
-{\r
- if (nexitfuncs >= NEXITFUNCS)\r
- return -1;\r
- exitfuncs[nexitfuncs++] = func;\r
- return 0;\r
-}\r
-\r
-static void\r
-call_sys_exitfunc(void)\r
-{\r
- PyObject *exitfunc = PySys_GetObject("exitfunc");\r
-\r
- if (exitfunc) {\r
- PyObject *res;\r
- Py_INCREF(exitfunc);\r
- PySys_SetObject("exitfunc", (PyObject *)NULL);\r
- res = PyEval_CallObject(exitfunc, (PyObject *)NULL);\r
- if (res == NULL) {\r
- if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {\r
- PySys_WriteStderr("Error in sys.exitfunc:\n");\r
- }\r
- PyErr_Print();\r
- }\r
- Py_DECREF(exitfunc);\r
- }\r
-\r
- if (Py_FlushLine())\r
- PyErr_Clear();\r
-}\r
-\r
-static void\r
-call_ll_exitfuncs(void)\r
-{\r
- while (nexitfuncs > 0)\r
- (*exitfuncs[--nexitfuncs])();\r
-\r
- fflush(stdout);\r
- fflush(stderr);\r
-}\r
-\r
-void\r
-Py_Exit(int sts)\r
-{\r
- Py_Finalize();\r
-\r
- exit(sts);\r
-}\r
-\r
-static void\r
-initsigs(void)\r
-{\r
-#ifdef SIGPIPE\r
- PyOS_setsig(SIGPIPE, SIG_IGN);\r
-#endif\r
-#ifdef SIGXFZ\r
- PyOS_setsig(SIGXFZ, SIG_IGN);\r
-#endif\r
-#ifdef SIGXFSZ\r
- PyOS_setsig(SIGXFSZ, SIG_IGN);\r
-#endif\r
- PyOS_InitInterrupts(); /* May imply initsignal() */\r
-}\r
-\r
-\r
-/*\r
- * The file descriptor fd is considered ``interactive'' if either\r
- * a) isatty(fd) is TRUE, or\r
- * b) the -i flag was given, and the filename associated with\r
- * the descriptor is NULL or "<stdin>" or "???".\r
- */\r
-int\r
-Py_FdIsInteractive(FILE *fp, const char *filename)\r
-{\r
- if (isatty((int)fileno(fp)))\r
- return 1;\r
- if (!Py_InteractiveFlag)\r
- return 0;\r
- return (filename == NULL) ||\r
- (strcmp(filename, "<stdin>") == 0) ||\r
- (strcmp(filename, "???") == 0);\r
-}\r
-\r
-\r
-#if defined(USE_STACKCHECK)\r
-#if defined(WIN32) && defined(_MSC_VER)\r
-\r
-/* Stack checking for Microsoft C */\r
-\r
-#include <malloc.h>\r
-#include <excpt.h>\r
-\r
-/*\r
- * Return non-zero when we run out of memory on the stack; zero otherwise.\r
- */\r
-int\r
-PyOS_CheckStack(void)\r
-{\r
- __try {\r
- /* alloca throws a stack overflow exception if there's\r
- not enough space left on the stack */\r
- alloca(PYOS_STACK_MARGIN * sizeof(void*));\r
- return 0;\r
- } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?\r
- EXCEPTION_EXECUTE_HANDLER :\r
- EXCEPTION_CONTINUE_SEARCH) {\r
- int errcode = _resetstkoflw();\r
- if (errcode == 0)\r
- {\r
- Py_FatalError("Could not reset the stack!");\r
- }\r
- }\r
- return 1;\r
-}\r
-\r
-#endif /* WIN32 && _MSC_VER */\r
-\r
-/* Alternate implementations can be added here... */\r
-\r
-#endif /* USE_STACKCHECK */\r
-\r
-\r
-/* Wrappers around sigaction() or signal(). */\r
-\r
-PyOS_sighandler_t\r
-PyOS_getsig(int sig)\r
-{\r
-#ifdef HAVE_SIGACTION\r
- struct sigaction context;\r
- if (sigaction(sig, NULL, &context) == -1)\r
- return SIG_ERR;\r
- return context.sa_handler;\r
-#else\r
- PyOS_sighandler_t handler;\r
-/* Special signal handling for the secure CRT in Visual Studio 2005 */\r
-#if defined(_MSC_VER) && _MSC_VER >= 1400\r
- switch (sig) {\r
- /* Only these signals are valid */\r
- case SIGINT:\r
- case SIGILL:\r
- case SIGFPE:\r
- case SIGSEGV:\r
- case SIGTERM:\r
- case SIGBREAK:\r
- case SIGABRT:\r
- break;\r
- /* Don't call signal() with other values or it will assert */\r
- default:\r
- return SIG_ERR;\r
- }\r
-#endif /* _MSC_VER && _MSC_VER >= 1400 */\r
- handler = signal(sig, SIG_IGN);\r
- if (handler != SIG_ERR)\r
- signal(sig, handler);\r
- return handler;\r
-#endif\r
-}\r
-\r
-PyOS_sighandler_t\r
-PyOS_setsig(int sig, PyOS_sighandler_t handler)\r
-{\r
-#ifdef HAVE_SIGACTION\r
- /* Some code in Modules/signalmodule.c depends on sigaction() being\r
- * used here if HAVE_SIGACTION is defined. Fix that if this code\r
- * changes to invalidate that assumption.\r
- */\r
- struct sigaction context, ocontext;\r
- context.sa_handler = handler;\r
- sigemptyset(&context.sa_mask);\r
- context.sa_flags = 0;\r
- if (sigaction(sig, &context, &ocontext) == -1)\r
- return SIG_ERR;\r
- return ocontext.sa_handler;\r
-#else\r
- PyOS_sighandler_t oldhandler;\r
- oldhandler = signal(sig, handler);\r
-#ifdef HAVE_SIGINTERRUPT\r
- siginterrupt(sig, 1);\r
-#endif\r
- return oldhandler;\r
-#endif\r
-}\r
-\r
-/* Deprecated C API functions still provided for binary compatiblity */\r
-\r
-#undef PyParser_SimpleParseFile\r
-PyAPI_FUNC(node *)\r
-PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)\r
-{\r
- return PyParser_SimpleParseFileFlags(fp, filename, start, 0);\r
-}\r
-\r
-#undef PyParser_SimpleParseString\r
-PyAPI_FUNC(node *)\r
-PyParser_SimpleParseString(const char *str, int start)\r
-{\r
- return PyParser_SimpleParseStringFlags(str, start, 0);\r
-}\r
-\r
-#undef PyRun_AnyFile\r
-PyAPI_FUNC(int)\r
-PyRun_AnyFile(FILE *fp, const char *name)\r
-{\r
- return PyRun_AnyFileExFlags(fp, name, 0, NULL);\r
-}\r
-\r
-#undef PyRun_AnyFileEx\r
-PyAPI_FUNC(int)\r
-PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)\r
-{\r
- return PyRun_AnyFileExFlags(fp, name, closeit, NULL);\r
-}\r
-\r
-#undef PyRun_AnyFileFlags\r
-PyAPI_FUNC(int)\r
-PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)\r
-{\r
- return PyRun_AnyFileExFlags(fp, name, 0, flags);\r
-}\r
-\r
-#undef PyRun_File\r
-PyAPI_FUNC(PyObject *)\r
-PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)\r
-{\r
- return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);\r
-}\r
-\r
-#undef PyRun_FileEx\r
-PyAPI_FUNC(PyObject *)\r
-PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)\r
-{\r
- return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);\r
-}\r
-\r
-#undef PyRun_FileFlags\r
-PyAPI_FUNC(PyObject *)\r
-PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,\r
- PyCompilerFlags *flags)\r
-{\r
- return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);\r
-}\r
-\r
-#undef PyRun_SimpleFile\r
-PyAPI_FUNC(int)\r
-PyRun_SimpleFile(FILE *f, const char *p)\r
-{\r
- return PyRun_SimpleFileExFlags(f, p, 0, NULL);\r
-}\r
-\r
-#undef PyRun_SimpleFileEx\r
-PyAPI_FUNC(int)\r
-PyRun_SimpleFileEx(FILE *f, const char *p, int c)\r
-{\r
- return PyRun_SimpleFileExFlags(f, p, c, NULL);\r
-}\r
-\r
-\r
-#undef PyRun_String\r
-PyAPI_FUNC(PyObject *)\r
-PyRun_String(const char *str, int s, PyObject *g, PyObject *l)\r
-{\r
- return PyRun_StringFlags(str, s, g, l, NULL);\r
-}\r
-\r
-#undef PyRun_SimpleString\r
-PyAPI_FUNC(int)\r
-PyRun_SimpleString(const char *s)\r
-{\r
- return PyRun_SimpleStringFlags(s, NULL);\r
-}\r
-\r
-#undef Py_CompileString\r
-PyAPI_FUNC(PyObject *)\r
-Py_CompileString(const char *str, const char *p, int s)\r
-{\r
- return Py_CompileStringFlags(str, p, s, NULL);\r
-}\r
-\r
-#undef PyRun_InteractiveOne\r
-PyAPI_FUNC(int)\r
-PyRun_InteractiveOne(FILE *f, const char *p)\r
-{\r
- return PyRun_InteractiveOneFlags(f, p, NULL);\r
-}\r
-\r
-#undef PyRun_InteractiveLoop\r
-PyAPI_FUNC(int)\r
-PyRun_InteractiveLoop(FILE *f, const char *p)\r
-{\r
- return PyRun_InteractiveLoopFlags(f, p, NULL);\r
-}\r
-\r
-#ifdef __cplusplus\r
-}\r
-#endif\r
-\r