You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2023 lines
55 KiB

Merged revisions 61750,61752,61754,61756,61760,61763,61768,61772,61775,61805,61809,61812,61819,61917,61920,61930,61933-61934 via svnmerge from svn+ssh://pythondev@svn.python.org/python/branches/trunk-bytearray ........ r61750 | christian.heimes | 2008-03-22 20:47:44 +0100 (Sat, 22 Mar 2008) | 1 line Copied files from py3k w/o modifications ........ r61752 | christian.heimes | 2008-03-22 20:53:20 +0100 (Sat, 22 Mar 2008) | 7 lines Take One * Added initialization code, warnings, flags etc. to the appropriate places * Added new buffer interface to string type * Modified tests * Modified Makefile.pre.in to compile the new files * Added bytesobject.c to Python.h ........ r61754 | christian.heimes | 2008-03-22 21:22:19 +0100 (Sat, 22 Mar 2008) | 2 lines Disabled bytearray.extend for now since it causes an infinite recursion Fixed serveral unit tests ........ r61756 | christian.heimes | 2008-03-22 21:43:38 +0100 (Sat, 22 Mar 2008) | 5 lines Added PyBytes support to several places: str + bytearray ord(bytearray) bytearray(str, encoding) ........ r61760 | christian.heimes | 2008-03-22 21:56:32 +0100 (Sat, 22 Mar 2008) | 1 line Fixed more unit tests related to type('') is not unicode ........ r61763 | christian.heimes | 2008-03-22 22:20:28 +0100 (Sat, 22 Mar 2008) | 2 lines Fixed more unit tests Fixed bytearray.extend ........ r61768 | christian.heimes | 2008-03-22 22:40:50 +0100 (Sat, 22 Mar 2008) | 1 line Implemented old buffer interface for bytearray ........ r61772 | christian.heimes | 2008-03-22 23:24:52 +0100 (Sat, 22 Mar 2008) | 1 line Added backport of the io module ........ r61775 | christian.heimes | 2008-03-23 03:50:49 +0100 (Sun, 23 Mar 2008) | 1 line Fix str assignement to bytearray. Assignment of a str of size 1 is interpreted as a single byte ........ r61805 | christian.heimes | 2008-03-23 19:33:48 +0100 (Sun, 23 Mar 2008) | 3 lines Fixed more tests Fixed bytearray() comparsion with unicode() Fixed iterator assignment of bytearray ........ r61809 | christian.heimes | 2008-03-23 21:02:21 +0100 (Sun, 23 Mar 2008) | 2 lines str(bytesarray()) now returns the bytes and not the representation of the bytearray object Enabled and fixed more unit tests ........ r61812 | christian.heimes | 2008-03-23 21:53:08 +0100 (Sun, 23 Mar 2008) | 3 lines Clear error PyNumber_AsSsize_t() fails Use CHARMASK for ob_svall access disabled a test with memoryview again ........ r61819 | christian.heimes | 2008-03-23 23:05:57 +0100 (Sun, 23 Mar 2008) | 1 line Untested updates to the PCBuild directory ........ r61917 | christian.heimes | 2008-03-26 00:57:06 +0100 (Wed, 26 Mar 2008) | 1 line The type system of Python 2.6 has subtle differences to 3.0's. I've removed the Py_TPFLAGS_BASETYPE flags from bytearray for now. bytearray can't be subclasses until the issues with bytearray subclasses are fixed. ........ r61920 | christian.heimes | 2008-03-26 01:44:08 +0100 (Wed, 26 Mar 2008) | 2 lines Disabled last failing test I don't understand what the test is testing and how it suppose to work. Ka-Ping, please check it out. ........ r61930 | christian.heimes | 2008-03-26 12:46:18 +0100 (Wed, 26 Mar 2008) | 1 line Re-enabled bytes warning code ........ r61933 | christian.heimes | 2008-03-26 13:20:46 +0100 (Wed, 26 Mar 2008) | 1 line Fixed a bug in the new buffer protocol. The buffer slots weren't copied into a subclass. ........ r61934 | christian.heimes | 2008-03-26 13:25:09 +0100 (Wed, 26 Mar 2008) | 1 line Re-enabled bytearray subclassing - all tests are passing. ........
18 years ago
Merged revisions 61750,61752,61754,61756,61760,61763,61768,61772,61775,61805,61809,61812,61819,61917,61920,61930,61933-61934 via svnmerge from svn+ssh://pythondev@svn.python.org/python/branches/trunk-bytearray ........ r61750 | christian.heimes | 2008-03-22 20:47:44 +0100 (Sat, 22 Mar 2008) | 1 line Copied files from py3k w/o modifications ........ r61752 | christian.heimes | 2008-03-22 20:53:20 +0100 (Sat, 22 Mar 2008) | 7 lines Take One * Added initialization code, warnings, flags etc. to the appropriate places * Added new buffer interface to string type * Modified tests * Modified Makefile.pre.in to compile the new files * Added bytesobject.c to Python.h ........ r61754 | christian.heimes | 2008-03-22 21:22:19 +0100 (Sat, 22 Mar 2008) | 2 lines Disabled bytearray.extend for now since it causes an infinite recursion Fixed serveral unit tests ........ r61756 | christian.heimes | 2008-03-22 21:43:38 +0100 (Sat, 22 Mar 2008) | 5 lines Added PyBytes support to several places: str + bytearray ord(bytearray) bytearray(str, encoding) ........ r61760 | christian.heimes | 2008-03-22 21:56:32 +0100 (Sat, 22 Mar 2008) | 1 line Fixed more unit tests related to type('') is not unicode ........ r61763 | christian.heimes | 2008-03-22 22:20:28 +0100 (Sat, 22 Mar 2008) | 2 lines Fixed more unit tests Fixed bytearray.extend ........ r61768 | christian.heimes | 2008-03-22 22:40:50 +0100 (Sat, 22 Mar 2008) | 1 line Implemented old buffer interface for bytearray ........ r61772 | christian.heimes | 2008-03-22 23:24:52 +0100 (Sat, 22 Mar 2008) | 1 line Added backport of the io module ........ r61775 | christian.heimes | 2008-03-23 03:50:49 +0100 (Sun, 23 Mar 2008) | 1 line Fix str assignement to bytearray. Assignment of a str of size 1 is interpreted as a single byte ........ r61805 | christian.heimes | 2008-03-23 19:33:48 +0100 (Sun, 23 Mar 2008) | 3 lines Fixed more tests Fixed bytearray() comparsion with unicode() Fixed iterator assignment of bytearray ........ r61809 | christian.heimes | 2008-03-23 21:02:21 +0100 (Sun, 23 Mar 2008) | 2 lines str(bytesarray()) now returns the bytes and not the representation of the bytearray object Enabled and fixed more unit tests ........ r61812 | christian.heimes | 2008-03-23 21:53:08 +0100 (Sun, 23 Mar 2008) | 3 lines Clear error PyNumber_AsSsize_t() fails Use CHARMASK for ob_svall access disabled a test with memoryview again ........ r61819 | christian.heimes | 2008-03-23 23:05:57 +0100 (Sun, 23 Mar 2008) | 1 line Untested updates to the PCBuild directory ........ r61917 | christian.heimes | 2008-03-26 00:57:06 +0100 (Wed, 26 Mar 2008) | 1 line The type system of Python 2.6 has subtle differences to 3.0's. I've removed the Py_TPFLAGS_BASETYPE flags from bytearray for now. bytearray can't be subclasses until the issues with bytearray subclasses are fixed. ........ r61920 | christian.heimes | 2008-03-26 01:44:08 +0100 (Wed, 26 Mar 2008) | 2 lines Disabled last failing test I don't understand what the test is testing and how it suppose to work. Ka-Ping, please check it out. ........ r61930 | christian.heimes | 2008-03-26 12:46:18 +0100 (Wed, 26 Mar 2008) | 1 line Re-enabled bytes warning code ........ r61933 | christian.heimes | 2008-03-26 13:20:46 +0100 (Wed, 26 Mar 2008) | 1 line Fixed a bug in the new buffer protocol. The buffer slots weren't copied into a subclass. ........ r61934 | christian.heimes | 2008-03-26 13:25:09 +0100 (Wed, 26 Mar 2008) | 1 line Re-enabled bytearray subclassing - all tests are passing. ........
18 years ago
Add warning mode for classic division, almost exactly as specified in PEP 238. Changes: - add a new flag variable Py_DivisionWarningFlag, declared in pydebug.h, defined in object.c, set in main.c, and used in {int,long,float,complex}object.c. When this flag is set, the classic division operator issues a DeprecationWarning message. - add a new API PyRun_SimpleStringFlags() to match PyRun_SimpleString(). The main() function calls this so that commands run with -c can also benefit from -Dnew. - While I was at it, I changed the usage message in main() somewhat: alphabetized the options, split it in *four* parts to fit in under 512 bytes (not that I still believe this is necessary -- doc strings elsewhere are much longer), and perhaps most visibly, don't display the full list of options on each command line error. Instead, the full list is only displayed when -h is used, and otherwise a brief reminder of -h is displayed. When -h is used, write to stdout so that you can do `python -h | more'. Notes: - I don't want to use the -W option to control whether the classic division warning is issued or not, because the machinery to decide whether to display the warning or not is very expensive (it involves calling into the warnings.py module). You can use -Werror to turn the warnings into exceptions though. - The -Dnew option doesn't select future division for all of the program -- only for the __main__ module. I don't know if I'll ever change this -- it would require changes to the .pyc file magic number to do it right, and a more global notion of compiler flags. - You can usefully combine -Dwarn and -Dnew: this gives the __main__ module new division, and warns about classic division everywhere else.
25 years ago
  1. /* Python interpreter top-level routines, including init/exit */
  2. #include "Python.h"
  3. #include "Python-ast.h"
  4. #undef Yield /* undefine macro conflicting with winbase.h */
  5. #include "grammar.h"
  6. #include "node.h"
  7. #include "token.h"
  8. #include "parsetok.h"
  9. #include "errcode.h"
  10. #include "code.h"
  11. #include "compile.h"
  12. #include "symtable.h"
  13. #include "pyarena.h"
  14. #include "ast.h"
  15. #include "eval.h"
  16. #include "marshal.h"
  17. #include "abstract.h"
  18. #ifdef HAVE_SIGNAL_H
  19. #include <signal.h>
  20. #endif
  21. #ifdef MS_WINDOWS
  22. #include "malloc.h" /* for alloca */
  23. #endif
  24. #ifdef HAVE_LANGINFO_H
  25. #include <locale.h>
  26. #include <langinfo.h>
  27. #endif
  28. #ifdef MS_WINDOWS
  29. #undef BYTE
  30. #include "windows.h"
  31. #endif
  32. #ifndef Py_REF_DEBUG
  33. #define PRINT_TOTAL_REFS()
  34. #else /* Py_REF_DEBUG */
  35. #define PRINT_TOTAL_REFS() fprintf(stderr, \
  36. "[%" PY_FORMAT_SIZE_T "d refs]\n", \
  37. _Py_GetRefTotal())
  38. #endif
  39. #ifdef __cplusplus
  40. extern "C" {
  41. #endif
  42. extern char *Py_GetPath(void);
  43. extern grammar _PyParser_Grammar; /* From graminit.c */
  44. /* Forward */
  45. static void initmain(void);
  46. static void initsite(void);
  47. static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
  48. PyCompilerFlags *, PyArena *);
  49. static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
  50. PyCompilerFlags *);
  51. static void err_input(perrdetail *);
  52. static void initsigs(void);
  53. static void wait_for_thread_shutdown(void);
  54. static void call_sys_exitfunc(void);
  55. static void call_ll_exitfuncs(void);
  56. extern void _PyUnicode_Init(void);
  57. extern void _PyUnicode_Fini(void);
  58. #ifdef WITH_THREAD
  59. extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
  60. extern void _PyGILState_Fini(void);
  61. #endif /* WITH_THREAD */
  62. int Py_DebugFlag; /* Needed by parser.c */
  63. int Py_VerboseFlag; /* Needed by import.c */
  64. int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
  65. int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
  66. int Py_NoSiteFlag; /* Suppress 'import site' */
  67. int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
  68. int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
  69. int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
  70. int Py_FrozenFlag; /* Needed by getpath.c */
  71. int Py_UnicodeFlag = 0; /* Needed by compile.c */
  72. int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
  73. /* _XXX Py_QnewFlag should go away in 2.3. It's true iff -Qnew is passed,
  74. on the command line, and is used in 2.2 by ceval.c to make all "/" divisions
  75. true divisions (which they will be in 2.3). */
  76. int _Py_QnewFlag = 0;
  77. int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
  78. int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
  79. /* PyModule_GetWarningsModule is no longer necessary as of 2.6
  80. since _warnings is builtin. This API should not be used. */
  81. PyObject *
  82. PyModule_GetWarningsModule(void)
  83. {
  84. return PyImport_ImportModule("warnings");
  85. }
  86. static int initialized = 0;
  87. /* API to access the initialized flag -- useful for esoteric use */
  88. int
  89. Py_IsInitialized(void)
  90. {
  91. return initialized;
  92. }
  93. /* Global initializations. Can be undone by Py_Finalize(). Don't
  94. call this twice without an intervening Py_Finalize() call. When
  95. initializations fail, a fatal error is issued and the function does
  96. not return. On return, the first thread and interpreter state have
  97. been created.
  98. Locking: you must hold the interpreter lock while calling this.
  99. (If the lock has not yet been initialized, that's equivalent to
  100. having the lock, but you cannot use multiple threads.)
  101. */
  102. static int
  103. add_flag(int flag, const char *envs)
  104. {
  105. int env = atoi(envs);
  106. if (flag < env)
  107. flag = env;
  108. if (flag < 1)
  109. flag = 1;
  110. return flag;
  111. }
  112. void
  113. Py_InitializeEx(int install_sigs)
  114. {
  115. PyInterpreterState *interp;
  116. PyThreadState *tstate;
  117. PyObject *bimod, *sysmod;
  118. char *p;
  119. char *icodeset = NULL; /* On Windows, input codeset may theoretically
  120. differ from output codeset. */
  121. char *codeset = NULL;
  122. char *errors = NULL;
  123. int free_codeset = 0;
  124. int overridden = 0;
  125. PyObject *sys_stream, *sys_isatty;
  126. #if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
  127. char *saved_locale, *loc_codeset;
  128. #endif
  129. #ifdef MS_WINDOWS
  130. char ibuf[128];
  131. char buf[128];
  132. #endif
  133. extern void _Py_ReadyTypes(void);
  134. if (initialized)
  135. return;
  136. initialized = 1;
  137. if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
  138. Py_DebugFlag = add_flag(Py_DebugFlag, p);
  139. if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
  140. Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
  141. if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
  142. Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
  143. if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
  144. Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
  145. /* The variable is only tested for existence here; _PyRandom_Init will
  146. check its value further. */
  147. if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
  148. Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
  149. _PyRandom_Init();
  150. interp = PyInterpreterState_New();
  151. if (interp == NULL)
  152. Py_FatalError("Py_Initialize: can't make first interpreter");
  153. tstate = PyThreadState_New(interp);
  154. if (tstate == NULL)
  155. Py_FatalError("Py_Initialize: can't make first thread");
  156. (void) PyThreadState_Swap(tstate);
  157. _Py_ReadyTypes();
  158. if (!_PyFrame_Init())
  159. Py_FatalError("Py_Initialize: can't init frames");
  160. if (!_PyInt_Init())
  161. Py_FatalError("Py_Initialize: can't init ints");
  162. if (!_PyLong_Init())
  163. Py_FatalError("Py_Initialize: can't init longs");
  164. if (!PyByteArray_Init())
  165. Py_FatalError("Py_Initialize: can't init bytearray");
  166. _PyFloat_Init();
  167. interp->modules = PyDict_New();
  168. if (interp->modules == NULL)
  169. Py_FatalError("Py_Initialize: can't make modules dictionary");
  170. interp->modules_reloading = PyDict_New();
  171. if (interp->modules_reloading == NULL)
  172. Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
  173. #ifdef Py_USING_UNICODE
  174. /* Init Unicode implementation; relies on the codec registry */
  175. _PyUnicode_Init();
  176. #endif
  177. bimod = _PyBuiltin_Init();
  178. if (bimod == NULL)
  179. Py_FatalError("Py_Initialize: can't initialize __builtin__");
  180. interp->builtins = PyModule_GetDict(bimod);
  181. if (interp->builtins == NULL)
  182. Py_FatalError("Py_Initialize: can't initialize builtins dict");
  183. Py_INCREF(interp->builtins);
  184. sysmod = _PySys_Init();
  185. if (sysmod == NULL)
  186. Py_FatalError("Py_Initialize: can't initialize sys");
  187. interp->sysdict = PyModule_GetDict(sysmod);
  188. if (interp->sysdict == NULL)
  189. Py_FatalError("Py_Initialize: can't initialize sys dict");
  190. Py_INCREF(interp->sysdict);
  191. _PyImport_FixupExtension("sys", "sys");
  192. PySys_SetPath(Py_GetPath());
  193. PyDict_SetItemString(interp->sysdict, "modules",
  194. interp->modules);
  195. _PyImport_Init();
  196. /* initialize builtin exceptions */
  197. _PyExc_Init();
  198. _PyImport_FixupExtension("exceptions", "exceptions");
  199. /* phase 2 of builtins */
  200. _PyImport_FixupExtension("__builtin__", "__builtin__");
  201. _PyImportHooks_Init();
  202. if (install_sigs)
  203. initsigs(); /* Signal handling stuff, including initintr() */
  204. /* Initialize warnings. */
  205. _PyWarnings_Init();
  206. if (PySys_HasWarnOptions()) {
  207. PyObject *warnings_module = PyImport_ImportModule("warnings");
  208. if (!warnings_module)
  209. PyErr_Clear();
  210. Py_XDECREF(warnings_module);
  211. }
  212. initmain(); /* Module __main__ */
  213. /* auto-thread-state API, if available */
  214. #ifdef WITH_THREAD
  215. _PyGILState_Init(interp, tstate);
  216. #endif /* WITH_THREAD */
  217. if (!Py_NoSiteFlag)
  218. initsite(); /* Module site */
  219. if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {
  220. p = icodeset = codeset = strdup(p);
  221. free_codeset = 1;
  222. errors = strchr(p, ':');
  223. if (errors) {
  224. *errors = '\0';
  225. errors++;
  226. }
  227. overridden = 1;
  228. }
  229. #if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
  230. /* On Unix, set the file system encoding according to the
  231. user's preference, if the CODESET names a well-known
  232. Python codec, and Py_FileSystemDefaultEncoding isn't
  233. initialized by other means. Also set the encoding of
  234. stdin and stdout if these are terminals, unless overridden. */
  235. if (!overridden || !Py_FileSystemDefaultEncoding) {
  236. saved_locale = strdup(setlocale(LC_CTYPE, NULL));
  237. setlocale(LC_CTYPE, "");
  238. loc_codeset = nl_langinfo(CODESET);
  239. if (loc_codeset && *loc_codeset) {
  240. PyObject *enc = PyCodec_Encoder(loc_codeset);
  241. if (enc) {
  242. loc_codeset = strdup(loc_codeset);
  243. Py_DECREF(enc);
  244. } else {
  245. if (PyErr_ExceptionMatches(PyExc_LookupError)) {
  246. PyErr_Clear();
  247. loc_codeset = NULL;
  248. } else {
  249. PyErr_Print();
  250. exit(1);
  251. }
  252. }
  253. } else
  254. loc_codeset = NULL;
  255. setlocale(LC_CTYPE, saved_locale);
  256. free(saved_locale);
  257. if (!overridden) {
  258. codeset = icodeset = loc_codeset;
  259. free_codeset = 1;
  260. }
  261. /* Initialize Py_FileSystemDefaultEncoding from
  262. locale even if PYTHONIOENCODING is set. */
  263. if (!Py_FileSystemDefaultEncoding) {
  264. Py_FileSystemDefaultEncoding = loc_codeset;
  265. if (!overridden)
  266. free_codeset = 0;
  267. }
  268. }
  269. #endif
  270. #ifdef MS_WINDOWS
  271. if (!overridden) {
  272. icodeset = ibuf;
  273. codeset = buf;
  274. sprintf(ibuf, "cp%d", GetConsoleCP());
  275. sprintf(buf, "cp%d", GetConsoleOutputCP());
  276. }
  277. #endif
  278. if (codeset) {
  279. sys_stream = PySys_GetObject("stdin");
  280. sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
  281. if (!sys_isatty)
  282. PyErr_Clear();
  283. if ((overridden ||
  284. (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
  285. PyFile_Check(sys_stream)) {
  286. if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))
  287. Py_FatalError("Cannot set codeset of stdin");
  288. }
  289. Py_XDECREF(sys_isatty);
  290. sys_stream = PySys_GetObject("stdout");
  291. sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
  292. if (!sys_isatty)
  293. PyErr_Clear();
  294. if ((overridden ||
  295. (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
  296. PyFile_Check(sys_stream)) {
  297. if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
  298. Py_FatalError("Cannot set codeset of stdout");
  299. }
  300. Py_XDECREF(sys_isatty);
  301. sys_stream = PySys_GetObject("stderr");
  302. sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
  303. if (!sys_isatty)
  304. PyErr_Clear();
  305. if((overridden ||
  306. (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
  307. PyFile_Check(sys_stream)) {
  308. if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
  309. Py_FatalError("Cannot set codeset of stderr");
  310. }
  311. Py_XDECREF(sys_isatty);
  312. if (free_codeset)
  313. free(codeset);
  314. }
  315. }
  316. void
  317. Py_Initialize(void)
  318. {
  319. Py_InitializeEx(1);
  320. }
  321. #ifdef COUNT_ALLOCS
  322. extern void dump_counts(FILE*);
  323. #endif
  324. /* Undo the effect of Py_Initialize().
  325. Beware: if multiple interpreter and/or thread states exist, these
  326. are not wiped out; only the current thread and interpreter state
  327. are deleted. But since everything else is deleted, those other
  328. interpreter and thread states should no longer be used.
  329. (XXX We should do better, e.g. wipe out all interpreters and
  330. threads.)
  331. Locking: as above.
  332. */
  333. void
  334. Py_Finalize(void)
  335. {
  336. PyInterpreterState *interp;
  337. PyThreadState *tstate;
  338. if (!initialized)
  339. return;
  340. wait_for_thread_shutdown();
  341. /* The interpreter is still entirely intact at this point, and the
  342. * exit funcs may be relying on that. In particular, if some thread
  343. * or exit func is still waiting to do an import, the import machinery
  344. * expects Py_IsInitialized() to return true. So don't say the
  345. * interpreter is uninitialized until after the exit funcs have run.
  346. * Note that Threading.py uses an exit func to do a join on all the
  347. * threads created thru it, so this also protects pending imports in
  348. * the threads created via Threading.
  349. */
  350. call_sys_exitfunc();
  351. initialized = 0;
  352. /* Get current thread state and interpreter pointer */
  353. tstate = PyThreadState_GET();
  354. interp = tstate->interp;
  355. /* Disable signal handling */
  356. PyOS_FiniInterrupts();
  357. /* Clear type lookup cache */
  358. PyType_ClearCache();
  359. /* Collect garbage. This may call finalizers; it's nice to call these
  360. * before all modules are destroyed.
  361. * XXX If a __del__ or weakref callback is triggered here, and tries to
  362. * XXX import a module, bad things can happen, because Python no
  363. * XXX longer believes it's initialized.
  364. * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
  365. * XXX is easy to provoke that way. I've also seen, e.g.,
  366. * XXX Exception exceptions.ImportError: 'No module named sha'
  367. * XXX in <function callback at 0x008F5718> ignored
  368. * XXX but I'm unclear on exactly how that one happens. In any case,
  369. * XXX I haven't seen a real-life report of either of these.
  370. */
  371. PyGC_Collect();
  372. #ifdef COUNT_ALLOCS
  373. /* With COUNT_ALLOCS, it helps to run GC multiple times:
  374. each collection might release some types from the type
  375. list, so they become garbage. */
  376. while (PyGC_Collect() > 0)
  377. /* nothing */;
  378. #endif
  379. /* Destroy all modules */
  380. PyImport_Cleanup();
  381. /* Collect final garbage. This disposes of cycles created by
  382. * new-style class definitions, for example.
  383. * XXX This is disabled because it caused too many problems. If
  384. * XXX a __del__ or weakref callback triggers here, Python code has
  385. * XXX a hard time running, because even the sys module has been
  386. * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
  387. * XXX One symptom is a sequence of information-free messages
  388. * XXX coming from threads (if a __del__ or callback is invoked,
  389. * XXX other threads can execute too, and any exception they encounter
  390. * XXX triggers a comedy of errors as subsystem after subsystem
  391. * XXX fails to find what it *expects* to find in sys to help report
  392. * XXX the exception and consequent unexpected failures). I've also
  393. * XXX seen segfaults then, after adding print statements to the
  394. * XXX Python code getting called.
  395. */
  396. #if 0
  397. PyGC_Collect();
  398. #endif
  399. /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
  400. _PyImport_Fini();
  401. /* Debugging stuff */
  402. #ifdef COUNT_ALLOCS
  403. dump_counts(stdout);
  404. #endif
  405. PRINT_TOTAL_REFS();
  406. #ifdef Py_TRACE_REFS
  407. /* Display all objects still alive -- this can invoke arbitrary
  408. * __repr__ overrides, so requires a mostly-intact interpreter.
  409. * Alas, a lot of stuff may still be alive now that will be cleaned
  410. * up later.
  411. */
  412. if (Py_GETENV("PYTHONDUMPREFS"))
  413. _Py_PrintReferences(stderr);
  414. #endif /* Py_TRACE_REFS */
  415. /* Clear interpreter state */
  416. PyInterpreterState_Clear(interp);
  417. /* Now we decref the exception classes. After this point nothing
  418. can raise an exception. That's okay, because each Fini() method
  419. below has been checked to make sure no exceptions are ever
  420. raised.
  421. */
  422. _PyExc_Fini();
  423. /* Cleanup auto-thread-state */
  424. #ifdef WITH_THREAD
  425. _PyGILState_Fini();
  426. #endif /* WITH_THREAD */
  427. /* Delete current thread */
  428. PyThreadState_Swap(NULL);
  429. PyInterpreterState_Delete(interp);
  430. /* Sundry finalizers */
  431. PyMethod_Fini();
  432. PyFrame_Fini();
  433. PyCFunction_Fini();
  434. PyTuple_Fini();
  435. PyList_Fini();
  436. PySet_Fini();
  437. PyString_Fini();
  438. PyByteArray_Fini();
  439. PyInt_Fini();
  440. PyFloat_Fini();
  441. PyDict_Fini();
  442. #ifdef Py_USING_UNICODE
  443. /* Cleanup Unicode implementation */
  444. _PyUnicode_Fini();
  445. #endif
  446. /* XXX Still allocated:
  447. - various static ad-hoc pointers to interned strings
  448. - int and float free list blocks
  449. - whatever various modules and libraries allocate
  450. */
  451. PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
  452. #ifdef Py_TRACE_REFS
  453. /* Display addresses (& refcnts) of all objects still alive.
  454. * An address can be used to find the repr of the object, printed
  455. * above by _Py_PrintReferences.
  456. */
  457. if (Py_GETENV("PYTHONDUMPREFS"))
  458. _Py_PrintReferenceAddresses(stderr);
  459. #endif /* Py_TRACE_REFS */
  460. #ifdef PYMALLOC_DEBUG
  461. if (Py_GETENV("PYTHONMALLOCSTATS"))
  462. _PyObject_DebugMallocStats();
  463. #endif
  464. call_ll_exitfuncs();
  465. }
  466. /* Create and initialize a new interpreter and thread, and return the
  467. new thread. This requires that Py_Initialize() has been called
  468. first.
  469. Unsuccessful initialization yields a NULL pointer. Note that *no*
  470. exception information is available even in this case -- the
  471. exception information is held in the thread, and there is no
  472. thread.
  473. Locking: as above.
  474. */
  475. PyThreadState *
  476. Py_NewInterpreter(void)
  477. {
  478. PyInterpreterState *interp;
  479. PyThreadState *tstate, *save_tstate;
  480. PyObject *bimod, *sysmod;
  481. if (!initialized)
  482. Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
  483. interp = PyInterpreterState_New();
  484. if (interp == NULL)
  485. return NULL;
  486. tstate = PyThreadState_New(interp);
  487. if (tstate == NULL) {
  488. PyInterpreterState_Delete(interp);
  489. return NULL;
  490. }
  491. save_tstate = PyThreadState_Swap(tstate);
  492. /* XXX The following is lax in error checking */
  493. interp->modules = PyDict_New();
  494. interp->modules_reloading = PyDict_New();
  495. bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
  496. if (bimod != NULL) {
  497. interp->builtins = PyModule_GetDict(bimod);
  498. if (interp->builtins == NULL)
  499. goto handle_error;
  500. Py_INCREF(interp->builtins);
  501. }
  502. sysmod = _PyImport_FindExtension("sys", "sys");
  503. if (bimod != NULL && sysmod != NULL) {
  504. interp->sysdict = PyModule_GetDict(sysmod);
  505. if (interp->sysdict == NULL)
  506. goto handle_error;
  507. Py_INCREF(interp->sysdict);
  508. PySys_SetPath(Py_GetPath());
  509. PyDict_SetItemString(interp->sysdict, "modules",
  510. interp->modules);
  511. _PyImportHooks_Init();
  512. initmain();
  513. if (!Py_NoSiteFlag)
  514. initsite();
  515. }
  516. if (!PyErr_Occurred())
  517. return tstate;
  518. handle_error:
  519. /* Oops, it didn't work. Undo it all. */
  520. PyErr_Print();
  521. PyThreadState_Clear(tstate);
  522. PyThreadState_Swap(save_tstate);
  523. PyThreadState_Delete(tstate);
  524. PyInterpreterState_Delete(interp);
  525. return NULL;
  526. }
  527. /* Delete an interpreter and its last thread. This requires that the
  528. given thread state is current, that the thread has no remaining
  529. frames, and that it is its interpreter's only remaining thread.
  530. It is a fatal error to violate these constraints.
  531. (Py_Finalize() doesn't have these constraints -- it zaps
  532. everything, regardless.)
  533. Locking: as above.
  534. */
  535. void
  536. Py_EndInterpreter(PyThreadState *tstate)
  537. {
  538. PyInterpreterState *interp = tstate->interp;
  539. if (tstate != PyThreadState_GET())
  540. Py_FatalError("Py_EndInterpreter: thread is not current");
  541. if (tstate->frame != NULL)
  542. Py_FatalError("Py_EndInterpreter: thread still has a frame");
  543. if (tstate != interp->tstate_head || tstate->next != NULL)
  544. Py_FatalError("Py_EndInterpreter: not the last thread");
  545. PyImport_Cleanup();
  546. PyInterpreterState_Clear(interp);
  547. PyThreadState_Swap(NULL);
  548. PyInterpreterState_Delete(interp);
  549. }
  550. static char *progname = "python";
  551. void
  552. Py_SetProgramName(char *pn)
  553. {
  554. if (pn && *pn)
  555. progname = pn;
  556. }
  557. char *
  558. Py_GetProgramName(void)
  559. {
  560. return progname;
  561. }
  562. static char *default_home = NULL;
  563. void
  564. Py_SetPythonHome(char *home)
  565. {
  566. default_home = home;
  567. }
  568. char *
  569. Py_GetPythonHome(void)
  570. {
  571. char *home = default_home;
  572. if (home == NULL && !Py_IgnoreEnvironmentFlag)
  573. home = Py_GETENV("PYTHONHOME");
  574. return home;
  575. }
  576. /* Create __main__ module */
  577. static void
  578. initmain(void)
  579. {
  580. PyObject *m, *d;
  581. m = PyImport_AddModule("__main__");
  582. if (m == NULL)
  583. Py_FatalError("can't create __main__ module");
  584. d = PyModule_GetDict(m);
  585. if (PyDict_GetItemString(d, "__builtins__") == NULL) {
  586. PyObject *bimod = PyImport_ImportModule("__builtin__");
  587. if (bimod == NULL ||
  588. PyDict_SetItemString(d, "__builtins__", bimod) != 0)
  589. Py_FatalError("can't add __builtins__ to __main__");
  590. Py_XDECREF(bimod);
  591. }
  592. }
  593. /* Import the site module (not into __main__ though) */
  594. static void
  595. initsite(void)
  596. {
  597. PyObject *m;
  598. m = PyImport_ImportModule("site");
  599. if (m == NULL) {
  600. PyErr_Print();
  601. Py_Finalize();
  602. exit(1);
  603. }
  604. else {
  605. Py_DECREF(m);
  606. }
  607. }
  608. /* Parse input from a file and execute it */
  609. int
  610. PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
  611. PyCompilerFlags *flags)
  612. {
  613. if (filename == NULL)
  614. filename = "???";
  615. if (Py_FdIsInteractive(fp, filename)) {
  616. int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
  617. if (closeit)
  618. fclose(fp);
  619. return err;
  620. }
  621. else
  622. return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
  623. }
  624. int
  625. PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
  626. {
  627. PyObject *v;
  628. int ret;
  629. PyCompilerFlags local_flags;
  630. if (flags == NULL) {
  631. flags = &local_flags;
  632. local_flags.cf_flags = 0;
  633. }
  634. v = PySys_GetObject("ps1");
  635. if (v == NULL) {
  636. PySys_SetObject("ps1", v = PyString_FromString(">>> "));
  637. Py_XDECREF(v);
  638. }
  639. v = PySys_GetObject("ps2");
  640. if (v == NULL) {
  641. PySys_SetObject("ps2", v = PyString_FromString("... "));
  642. Py_XDECREF(v);
  643. }
  644. for (;;) {
  645. ret = PyRun_InteractiveOneFlags(fp, filename, flags);
  646. PRINT_TOTAL_REFS();
  647. if (ret == E_EOF)
  648. return 0;
  649. /*
  650. if (ret == E_NOMEM)
  651. return -1;
  652. */
  653. }
  654. }
  655. #if 0
  656. /* compute parser flags based on compiler flags */
  657. #define PARSER_FLAGS(flags) \
  658. ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
  659. PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
  660. #endif
  661. #if 1
  662. /* Keep an example of flags with future keyword support. */
  663. #define PARSER_FLAGS(flags) \
  664. ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
  665. PyPARSE_DONT_IMPLY_DEDENT : 0) \
  666. | (((flags)->cf_flags & CO_FUTURE_PRINT_FUNCTION) ? \
  667. PyPARSE_PRINT_IS_FUNCTION : 0) \
  668. | (((flags)->cf_flags & CO_FUTURE_UNICODE_LITERALS) ? \
  669. PyPARSE_UNICODE_LITERALS : 0) \
  670. ) : 0)
  671. #endif
  672. int
  673. PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
  674. {
  675. PyObject *m, *d, *v, *w;
  676. mod_ty mod;
  677. PyArena *arena;
  678. char *ps1 = "", *ps2 = "";
  679. int errcode = 0;
  680. v = PySys_GetObject("ps1");
  681. if (v != NULL) {
  682. v = PyObject_Str(v);
  683. if (v == NULL)
  684. PyErr_Clear();
  685. else if (PyString_Check(v))
  686. ps1 = PyString_AsString(v);
  687. }
  688. w = PySys_GetObject("ps2");
  689. if (w != NULL) {
  690. w = PyObject_Str(w);
  691. if (w == NULL)
  692. PyErr_Clear();
  693. else if (PyString_Check(w))
  694. ps2 = PyString_AsString(w);
  695. }
  696. arena = PyArena_New();
  697. if (arena == NULL) {
  698. Py_XDECREF(v);
  699. Py_XDECREF(w);
  700. return -1;
  701. }
  702. mod = PyParser_ASTFromFile(fp, filename,
  703. Py_single_input, ps1, ps2,
  704. flags, &errcode, arena);
  705. Py_XDECREF(v);
  706. Py_XDECREF(w);
  707. if (mod == NULL) {
  708. PyArena_Free(arena);
  709. if (errcode == E_EOF) {
  710. PyErr_Clear();
  711. return E_EOF;
  712. }
  713. PyErr_Print();
  714. return -1;
  715. }
  716. m = PyImport_AddModule("__main__");
  717. if (m == NULL) {
  718. PyArena_Free(arena);
  719. return -1;
  720. }
  721. d = PyModule_GetDict(m);
  722. v = run_mod(mod, filename, d, d, flags, arena);
  723. PyArena_Free(arena);
  724. if (v == NULL) {
  725. PyErr_Print();
  726. return -1;
  727. }
  728. Py_DECREF(v);
  729. if (Py_FlushLine())
  730. PyErr_Clear();
  731. return 0;
  732. }
  733. /* Check whether a file maybe a pyc file: Look at the extension,
  734. the file type, and, if we may close it, at the first few bytes. */
  735. static int
  736. maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
  737. {
  738. if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
  739. return 1;
  740. /* Only look into the file if we are allowed to close it, since
  741. it then should also be seekable. */
  742. if (closeit) {
  743. /* Read only two bytes of the magic. If the file was opened in
  744. text mode, the bytes 3 and 4 of the magic (\r\n) might not
  745. be read as they are on disk. */
  746. unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
  747. unsigned char buf[2];
  748. /* Mess: In case of -x, the stream is NOT at its start now,
  749. and ungetc() was used to push back the first newline,
  750. which makes the current stream position formally undefined,
  751. and a x-platform nightmare.
  752. Unfortunately, we have no direct way to know whether -x
  753. was specified. So we use a terrible hack: if the current
  754. stream position is not 0, we assume -x was specified, and
  755. give up. Bug 132850 on SourceForge spells out the
  756. hopelessness of trying anything else (fseek and ftell
  757. don't work predictably x-platform for text-mode files).
  758. */
  759. int ispyc = 0;
  760. if (ftell(fp) == 0) {
  761. if (fread(buf, 1, 2, fp) == 2 &&
  762. ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
  763. ispyc = 1;
  764. rewind(fp);
  765. }
  766. return ispyc;
  767. }
  768. return 0;
  769. }
  770. int
  771. PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
  772. PyCompilerFlags *flags)
  773. {
  774. PyObject *m, *d, *v;
  775. const char *ext;
  776. int set_file_name = 0, len, ret = -1;
  777. m = PyImport_AddModule("__main__");
  778. if (m == NULL)
  779. return -1;
  780. Py_INCREF(m);
  781. d = PyModule_GetDict(m);
  782. if (PyDict_GetItemString(d, "__file__") == NULL) {
  783. PyObject *f = PyString_FromString(filename);
  784. if (f == NULL)
  785. goto done;
  786. if (PyDict_SetItemString(d, "__file__", f) < 0) {
  787. Py_DECREF(f);
  788. goto done;
  789. }
  790. set_file_name = 1;
  791. Py_DECREF(f);
  792. }
  793. len = strlen(filename);
  794. ext = filename + len - (len > 4 ? 4 : 0);
  795. if (maybe_pyc_file(fp, filename, ext, closeit)) {
  796. /* Try to run a pyc file. First, re-open in binary */
  797. if (closeit)
  798. fclose(fp);
  799. if ((fp = fopen(filename, "rb")) == NULL) {
  800. fprintf(stderr, "python: Can't reopen .pyc file\n");
  801. goto done;
  802. }
  803. /* Turn on optimization if a .pyo file is given */
  804. if (strcmp(ext, ".pyo") == 0)
  805. Py_OptimizeFlag = 1;
  806. v = run_pyc_file(fp, filename, d, d, flags);
  807. } else {
  808. v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
  809. closeit, flags);
  810. }
  811. if (v == NULL) {
  812. PyErr_Print();
  813. goto done;
  814. }
  815. Py_DECREF(v);
  816. if (Py_FlushLine())
  817. PyErr_Clear();
  818. ret = 0;
  819. done:
  820. if (set_file_name && PyDict_DelItemString(d, "__file__"))
  821. PyErr_Clear();
  822. Py_DECREF(m);
  823. return ret;
  824. }
  825. int
  826. PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
  827. {
  828. PyObject *m, *d, *v;
  829. m = PyImport_AddModule("__main__");
  830. if (m == NULL)
  831. return -1;
  832. d = PyModule_GetDict(m);
  833. v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
  834. if (v == NULL) {
  835. PyErr_Print();
  836. return -1;
  837. }
  838. Py_DECREF(v);
  839. if (Py_FlushLine())
  840. PyErr_Clear();
  841. return 0;
  842. }
  843. static int
  844. parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
  845. int *lineno, int *offset, const char **text)
  846. {
  847. long hold;
  848. PyObject *v;
  849. /* old style errors */
  850. if (PyTuple_Check(err))
  851. return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
  852. lineno, offset, text);
  853. *message = NULL;
  854. /* new style errors. `err' is an instance */
  855. *message = PyObject_GetAttrString(err, "msg");
  856. if (!*message)
  857. goto finally;
  858. v = PyObject_GetAttrString(err, "filename");
  859. if (!v)
  860. goto finally;
  861. if (v == Py_None) {
  862. Py_DECREF(v);
  863. *filename = NULL;
  864. }
  865. else {
  866. *filename = PyString_AsString(v);
  867. Py_DECREF(v);
  868. if (!*filename)
  869. goto finally;
  870. }
  871. v = PyObject_GetAttrString(err, "lineno");
  872. if (!v)
  873. goto finally;
  874. hold = PyInt_AsLong(v);
  875. Py_DECREF(v);
  876. if (hold < 0 && PyErr_Occurred())
  877. goto finally;
  878. *lineno = (int)hold;
  879. v = PyObject_GetAttrString(err, "offset");
  880. if (!v)
  881. goto finally;
  882. if (v == Py_None) {
  883. *offset = -1;
  884. Py_DECREF(v);
  885. } else {
  886. hold = PyInt_AsLong(v);
  887. Py_DECREF(v);
  888. if (hold < 0 && PyErr_Occurred())
  889. goto finally;
  890. *offset = (int)hold;
  891. }
  892. v = PyObject_GetAttrString(err, "text");
  893. if (!v)
  894. goto finally;
  895. if (v == Py_None) {
  896. Py_DECREF(v);
  897. *text = NULL;
  898. }
  899. else {
  900. *text = PyString_AsString(v);
  901. Py_DECREF(v);
  902. if (!*text)
  903. goto finally;
  904. }
  905. return 1;
  906. finally:
  907. Py_XDECREF(*message);
  908. return 0;
  909. }
  910. void
  911. PyErr_Print(void)
  912. {
  913. PyErr_PrintEx(1);
  914. }
  915. static void
  916. print_error_text(PyObject *f, int offset, const char *text)
  917. {
  918. char *nl;
  919. if (offset >= 0) {
  920. if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
  921. offset--;
  922. for (;;) {
  923. nl = strchr(text, '\n');
  924. if (nl == NULL || nl-text >= offset)
  925. break;
  926. offset -= (int)(nl+1-text);
  927. text = nl+1;
  928. }
  929. while (*text == ' ' || *text == '\t') {
  930. text++;
  931. offset--;
  932. }
  933. }
  934. PyFile_WriteString(" ", f);
  935. PyFile_WriteString(text, f);
  936. if (*text == '\0' || text[strlen(text)-1] != '\n')
  937. PyFile_WriteString("\n", f);
  938. if (offset == -1)
  939. return;
  940. PyFile_WriteString(" ", f);
  941. offset--;
  942. while (offset > 0) {
  943. PyFile_WriteString(" ", f);
  944. offset--;
  945. }
  946. PyFile_WriteString("^\n", f);
  947. }
  948. static void
  949. handle_system_exit(void)
  950. {
  951. PyObject *exception, *value, *tb;
  952. int exitcode = 0;
  953. if (Py_InspectFlag)
  954. /* Don't exit if -i flag was given. This flag is set to 0
  955. * when entering interactive mode for inspecting. */
  956. return;
  957. PyErr_Fetch(&exception, &value, &tb);
  958. if (Py_FlushLine())
  959. PyErr_Clear();
  960. fflush(stdout);
  961. if (value == NULL || value == Py_None)
  962. goto done;
  963. if (PyExceptionInstance_Check(value)) {
  964. /* The error code should be in the `code' attribute. */
  965. PyObject *code = PyObject_GetAttrString(value, "code");
  966. if (code) {
  967. Py_DECREF(value);
  968. value = code;
  969. if (value == Py_None)
  970. goto done;
  971. }
  972. /* If we failed to dig out the 'code' attribute,
  973. just let the else clause below print the error. */
  974. }
  975. if (PyInt_Check(value))
  976. exitcode = (int)PyInt_AsLong(value);
  977. else {
  978. PyObject *sys_stderr = PySys_GetObject("stderr");
  979. if (sys_stderr != NULL && sys_stderr != Py_None) {
  980. PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
  981. } else {
  982. PyObject_Print(value, stderr, Py_PRINT_RAW);
  983. fflush(stderr);
  984. }
  985. PySys_WriteStderr("\n");
  986. exitcode = 1;
  987. }
  988. done:
  989. /* Restore and clear the exception info, in order to properly decref
  990. * the exception, value, and traceback. If we just exit instead,
  991. * these leak, which confuses PYTHONDUMPREFS output, and may prevent
  992. * some finalizers from running.
  993. */
  994. PyErr_Restore(exception, value, tb);
  995. PyErr_Clear();
  996. Py_Exit(exitcode);
  997. /* NOTREACHED */
  998. }
  999. void
  1000. PyErr_PrintEx(int set_sys_last_vars)
  1001. {
  1002. PyObject *exception, *v, *tb, *hook;
  1003. if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
  1004. handle_system_exit();
  1005. }
  1006. PyErr_Fetch(&exception, &v, &tb);
  1007. if (exception == NULL)
  1008. return;
  1009. PyErr_NormalizeException(&exception, &v, &tb);
  1010. if (exception == NULL)
  1011. return;
  1012. /* Now we know v != NULL too */
  1013. if (set_sys_last_vars) {
  1014. PySys_SetObject("last_type", exception);
  1015. PySys_SetObject("last_value", v);
  1016. PySys_SetObject("last_traceback", tb);
  1017. }
  1018. hook = PySys_GetObject("excepthook");
  1019. if (hook && hook != Py_None) {
  1020. PyObject *args = PyTuple_Pack(3,
  1021. exception, v, tb ? tb : Py_None);
  1022. PyObject *result = PyEval_CallObject(hook, args);
  1023. if (result == NULL) {
  1024. PyObject *exception2, *v2, *tb2;
  1025. if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
  1026. handle_system_exit();
  1027. }
  1028. PyErr_Fetch(&exception2, &v2, &tb2);
  1029. PyErr_NormalizeException(&exception2, &v2, &tb2);
  1030. /* It should not be possible for exception2 or v2
  1031. to be NULL. However PyErr_Display() can't
  1032. tolerate NULLs, so just be safe. */
  1033. if (exception2 == NULL) {
  1034. exception2 = Py_None;
  1035. Py_INCREF(exception2);
  1036. }
  1037. if (v2 == NULL) {
  1038. v2 = Py_None;
  1039. Py_INCREF(v2);
  1040. }
  1041. if (Py_FlushLine())
  1042. PyErr_Clear();
  1043. fflush(stdout);
  1044. PySys_WriteStderr("Error in sys.excepthook:\n");
  1045. PyErr_Display(exception2, v2, tb2);
  1046. PySys_WriteStderr("\nOriginal exception was:\n");
  1047. PyErr_Display(exception, v, tb);
  1048. Py_DECREF(exception2);
  1049. Py_DECREF(v2);
  1050. Py_XDECREF(tb2);
  1051. }
  1052. Py_XDECREF(result);
  1053. Py_XDECREF(args);
  1054. } else {
  1055. PySys_WriteStderr("sys.excepthook is missing\n");
  1056. PyErr_Display(exception, v, tb);
  1057. }
  1058. Py_XDECREF(exception);
  1059. Py_XDECREF(v);
  1060. Py_XDECREF(tb);
  1061. }
  1062. void
  1063. PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
  1064. {
  1065. int err = 0;
  1066. PyObject *f = PySys_GetObject("stderr");
  1067. Py_INCREF(value);
  1068. if (f == NULL || f == Py_None)
  1069. fprintf(stderr, "lost sys.stderr\n");
  1070. else {
  1071. if (Py_FlushLine())
  1072. PyErr_Clear();
  1073. fflush(stdout);
  1074. if (tb && tb != Py_None)
  1075. err = PyTraceBack_Print(tb, f);
  1076. if (err == 0 &&
  1077. PyObject_HasAttrString(value, "print_file_and_line"))
  1078. {
  1079. PyObject *message;
  1080. const char *filename, *text;
  1081. int lineno, offset;
  1082. if (!parse_syntax_error(value, &message, &filename,
  1083. &lineno, &offset, &text))
  1084. PyErr_Clear();
  1085. else {
  1086. char buf[10];
  1087. PyFile_WriteString(" File \"", f);
  1088. if (filename == NULL)
  1089. PyFile_WriteString("<string>", f);
  1090. else
  1091. PyFile_WriteString(filename, f);
  1092. PyFile_WriteString("\", line ", f);
  1093. PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
  1094. PyFile_WriteString(buf, f);
  1095. PyFile_WriteString("\n", f);
  1096. if (text != NULL)
  1097. print_error_text(f, offset, text);
  1098. Py_DECREF(value);
  1099. value = message;
  1100. /* Can't be bothered to check all those
  1101. PyFile_WriteString() calls */
  1102. if (PyErr_Occurred())
  1103. err = -1;
  1104. }
  1105. }
  1106. if (err) {
  1107. /* Don't do anything else */
  1108. }
  1109. else if (PyExceptionClass_Check(exception)) {
  1110. PyObject* moduleName;
  1111. char* className = PyExceptionClass_Name(exception);
  1112. if (className != NULL) {
  1113. char *dot = strrchr(className, '.');
  1114. if (dot != NULL)
  1115. className = dot+1;
  1116. }
  1117. moduleName = PyObject_GetAttrString(exception, "__module__");
  1118. if (moduleName == NULL)
  1119. err = PyFile_WriteString("<unknown>", f);
  1120. else {
  1121. char* modstr = PyString_AsString(moduleName);
  1122. if (modstr && strcmp(modstr, "exceptions"))
  1123. {
  1124. err = PyFile_WriteString(modstr, f);
  1125. err += PyFile_WriteString(".", f);
  1126. }
  1127. Py_DECREF(moduleName);
  1128. }
  1129. if (err == 0) {
  1130. if (className == NULL)
  1131. err = PyFile_WriteString("<unknown>", f);
  1132. else
  1133. err = PyFile_WriteString(className, f);
  1134. }
  1135. }
  1136. else
  1137. err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
  1138. if (err == 0 && (value != Py_None)) {
  1139. PyObject *s = PyObject_Str(value);
  1140. /* only print colon if the str() of the
  1141. object is not the empty string
  1142. */
  1143. if (s == NULL)
  1144. err = -1;
  1145. else if (!PyString_Check(s) ||
  1146. PyString_GET_SIZE(s) != 0)
  1147. err = PyFile_WriteString(": ", f);
  1148. if (err == 0)
  1149. err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
  1150. Py_XDECREF(s);
  1151. }
  1152. /* try to write a newline in any case */
  1153. err += PyFile_WriteString("\n", f);
  1154. }
  1155. Py_DECREF(value);
  1156. /* If an error happened here, don't show it.
  1157. XXX This is wrong, but too many callers rely on this behavior. */
  1158. if (err != 0)
  1159. PyErr_Clear();
  1160. }
  1161. PyObject *
  1162. PyRun_StringFlags(const char *str, int start, PyObject *globals,
  1163. PyObject *locals, PyCompilerFlags *flags)
  1164. {
  1165. PyObject *ret = NULL;
  1166. mod_ty mod;
  1167. PyArena *arena = PyArena_New();
  1168. if (arena == NULL)
  1169. return NULL;
  1170. mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
  1171. if (mod != NULL)
  1172. ret = run_mod(mod, "<string>", globals, locals, flags, arena);
  1173. PyArena_Free(arena);
  1174. return ret;
  1175. }
  1176. PyObject *
  1177. PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
  1178. PyObject *locals, int closeit, PyCompilerFlags *flags)
  1179. {
  1180. PyObject *ret;
  1181. mod_ty mod;
  1182. PyArena *arena = PyArena_New();
  1183. if (arena == NULL)
  1184. return NULL;
  1185. mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
  1186. flags, NULL, arena);
  1187. if (closeit)
  1188. fclose(fp);
  1189. if (mod == NULL) {
  1190. PyArena_Free(arena);
  1191. return NULL;
  1192. }
  1193. ret = run_mod(mod, filename, globals, locals, flags, arena);
  1194. PyArena_Free(arena);
  1195. return ret;
  1196. }
  1197. static PyObject *
  1198. run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
  1199. PyCompilerFlags *flags, PyArena *arena)
  1200. {
  1201. PyCodeObject *co;
  1202. PyObject *v;
  1203. co = PyAST_Compile(mod, filename, flags, arena);
  1204. if (co == NULL)
  1205. return NULL;
  1206. v = PyEval_EvalCode(co, globals, locals);
  1207. Py_DECREF(co);
  1208. return v;
  1209. }
  1210. static PyObject *
  1211. run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
  1212. PyObject *locals, PyCompilerFlags *flags)
  1213. {
  1214. PyCodeObject *co;
  1215. PyObject *v;
  1216. long magic;
  1217. long PyImport_GetMagicNumber(void);
  1218. magic = PyMarshal_ReadLongFromFile(fp);
  1219. if (magic != PyImport_GetMagicNumber()) {
  1220. PyErr_SetString(PyExc_RuntimeError,
  1221. "Bad magic number in .pyc file");
  1222. return NULL;
  1223. }
  1224. (void) PyMarshal_ReadLongFromFile(fp);
  1225. v = PyMarshal_ReadLastObjectFromFile(fp);
  1226. fclose(fp);
  1227. if (v == NULL || !PyCode_Check(v)) {
  1228. Py_XDECREF(v);
  1229. PyErr_SetString(PyExc_RuntimeError,
  1230. "Bad code object in .pyc file");
  1231. return NULL;
  1232. }
  1233. co = (PyCodeObject *)v;
  1234. v = PyEval_EvalCode(co, globals, locals);
  1235. if (v && flags)
  1236. flags->cf_flags |= (co->co_flags & PyCF_MASK);
  1237. Py_DECREF(co);
  1238. return v;
  1239. }
  1240. PyObject *
  1241. Py_CompileStringFlags(const char *str, const char *filename, int start,
  1242. PyCompilerFlags *flags)
  1243. {
  1244. PyCodeObject *co;
  1245. mod_ty mod;
  1246. PyArena *arena = PyArena_New();
  1247. if (arena == NULL)
  1248. return NULL;
  1249. mod = PyParser_ASTFromString(str, filename, start, flags, arena);
  1250. if (mod == NULL) {
  1251. PyArena_Free(arena);
  1252. return NULL;
  1253. }
  1254. if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
  1255. PyObject *result = PyAST_mod2obj(mod);
  1256. PyArena_Free(arena);
  1257. return result;
  1258. }
  1259. co = PyAST_Compile(mod, filename, flags, arena);
  1260. PyArena_Free(arena);
  1261. return (PyObject *)co;
  1262. }
  1263. struct symtable *
  1264. Py_SymtableString(const char *str, const char *filename, int start)
  1265. {
  1266. struct symtable *st;
  1267. mod_ty mod;
  1268. PyCompilerFlags flags;
  1269. PyArena *arena = PyArena_New();
  1270. if (arena == NULL)
  1271. return NULL;
  1272. flags.cf_flags = 0;
  1273. mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
  1274. if (mod == NULL) {
  1275. PyArena_Free(arena);
  1276. return NULL;
  1277. }
  1278. st = PySymtable_Build(mod, filename, 0);
  1279. PyArena_Free(arena);
  1280. return st;
  1281. }
  1282. /* Preferred access to parser is through AST. */
  1283. mod_ty
  1284. PyParser_ASTFromString(const char *s, const char *filename, int start,
  1285. PyCompilerFlags *flags, PyArena *arena)
  1286. {
  1287. mod_ty mod;
  1288. PyCompilerFlags localflags;
  1289. perrdetail err;
  1290. int iflags = PARSER_FLAGS(flags);
  1291. node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
  1292. &_PyParser_Grammar, start, &err,
  1293. &iflags);
  1294. if (flags == NULL) {
  1295. localflags.cf_flags = 0;
  1296. flags = &localflags;
  1297. }
  1298. if (n) {
  1299. flags->cf_flags |= iflags & PyCF_MASK;
  1300. mod = PyAST_FromNode(n, flags, filename, arena);
  1301. PyNode_Free(n);
  1302. return mod;
  1303. }
  1304. else {
  1305. err_input(&err);
  1306. return NULL;
  1307. }
  1308. }
  1309. mod_ty
  1310. PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
  1311. char *ps2, PyCompilerFlags *flags, int *errcode,
  1312. PyArena *arena)
  1313. {
  1314. mod_ty mod;
  1315. PyCompilerFlags localflags;
  1316. perrdetail err;
  1317. int iflags = PARSER_FLAGS(flags);
  1318. node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,
  1319. start, ps1, ps2, &err, &iflags);
  1320. if (flags == NULL) {
  1321. localflags.cf_flags = 0;
  1322. flags = &localflags;
  1323. }
  1324. if (n) {
  1325. flags->cf_flags |= iflags & PyCF_MASK;
  1326. mod = PyAST_FromNode(n, flags, filename, arena);
  1327. PyNode_Free(n);
  1328. return mod;
  1329. }
  1330. else {
  1331. err_input(&err);
  1332. if (errcode)
  1333. *errcode = err.error;
  1334. return NULL;
  1335. }
  1336. }
  1337. /* Simplified interface to parsefile -- return node or set exception */
  1338. node *
  1339. PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
  1340. {
  1341. perrdetail err;
  1342. node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
  1343. start, NULL, NULL, &err, flags);
  1344. if (n == NULL)
  1345. err_input(&err);
  1346. return n;
  1347. }
  1348. /* Simplified interface to parsestring -- return node or set exception */
  1349. node *
  1350. PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
  1351. {
  1352. perrdetail err;
  1353. node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
  1354. start, &err, flags);
  1355. if (n == NULL)
  1356. err_input(&err);
  1357. return n;
  1358. }
  1359. node *
  1360. PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
  1361. int start, int flags)
  1362. {
  1363. perrdetail err;
  1364. node *n = PyParser_ParseStringFlagsFilename(str, filename,
  1365. &_PyParser_Grammar, start, &err, flags);
  1366. if (n == NULL)
  1367. err_input(&err);
  1368. return n;
  1369. }
  1370. node *
  1371. PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
  1372. {
  1373. return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
  1374. }
  1375. /* May want to move a more generalized form of this to parsetok.c or
  1376. even parser modules. */
  1377. void
  1378. PyParser_SetError(perrdetail *err)
  1379. {
  1380. err_input(err);
  1381. }
  1382. /* Set the error appropriate to the given input error code (see errcode.h) */
  1383. static void
  1384. err_input(perrdetail *err)
  1385. {
  1386. PyObject *v, *w, *errtype;
  1387. PyObject* u = NULL;
  1388. char *msg = NULL;
  1389. errtype = PyExc_SyntaxError;
  1390. switch (err->error) {
  1391. case E_ERROR:
  1392. return;
  1393. case E_SYNTAX:
  1394. errtype = PyExc_IndentationError;
  1395. if (err->expected == INDENT)
  1396. msg = "expected an indented block";
  1397. else if (err->token == INDENT)
  1398. msg = "unexpected indent";
  1399. else if (err->token == DEDENT)
  1400. msg = "unexpected unindent";
  1401. else {
  1402. errtype = PyExc_SyntaxError;
  1403. msg = "invalid syntax";
  1404. }
  1405. break;
  1406. case E_TOKEN:
  1407. msg = "invalid token";
  1408. break;
  1409. case E_EOFS:
  1410. msg = "EOF while scanning triple-quoted string literal";
  1411. break;
  1412. case E_EOLS:
  1413. msg = "EOL while scanning string literal";
  1414. break;
  1415. case E_INTR:
  1416. if (!PyErr_Occurred())
  1417. PyErr_SetNone(PyExc_KeyboardInterrupt);
  1418. goto cleanup;
  1419. case E_NOMEM:
  1420. PyErr_NoMemory();
  1421. goto cleanup;
  1422. case E_EOF:
  1423. msg = "unexpected EOF while parsing";
  1424. break;
  1425. case E_TABSPACE:
  1426. errtype = PyExc_TabError;
  1427. msg = "inconsistent use of tabs and spaces in indentation";
  1428. break;
  1429. case E_OVERFLOW:
  1430. msg = "expression too long";
  1431. break;
  1432. case E_DEDENT:
  1433. errtype = PyExc_IndentationError;
  1434. msg = "unindent does not match any outer indentation level";
  1435. break;
  1436. case E_TOODEEP:
  1437. errtype = PyExc_IndentationError;
  1438. msg = "too many levels of indentation";
  1439. break;
  1440. case E_DECODE: {
  1441. PyObject *type, *value, *tb;
  1442. PyErr_Fetch(&type, &value, &tb);
  1443. if (value != NULL) {
  1444. u = PyObject_Str(value);
  1445. if (u != NULL) {
  1446. msg = PyString_AsString(u);
  1447. }
  1448. }
  1449. if (msg == NULL)
  1450. msg = "unknown decode error";
  1451. Py_XDECREF(type);
  1452. Py_XDECREF(value);
  1453. Py_XDECREF(tb);
  1454. break;
  1455. }
  1456. case E_LINECONT:
  1457. msg = "unexpected character after line continuation character";
  1458. break;
  1459. default:
  1460. fprintf(stderr, "error=%d\n", err->error);
  1461. msg = "unknown parsing error";
  1462. break;
  1463. }
  1464. v = Py_BuildValue("(ziiz)", err->filename,
  1465. err->lineno, err->offset, err->text);
  1466. w = NULL;
  1467. if (v != NULL)
  1468. w = Py_BuildValue("(sO)", msg, v);
  1469. Py_XDECREF(u);
  1470. Py_XDECREF(v);
  1471. PyErr_SetObject(errtype, w);
  1472. Py_XDECREF(w);
  1473. cleanup:
  1474. if (err->text != NULL) {
  1475. PyObject_FREE(err->text);
  1476. err->text = NULL;
  1477. }
  1478. }
  1479. /* Print fatal error message and abort */
  1480. void
  1481. Py_FatalError(const char *msg)
  1482. {
  1483. fprintf(stderr, "Fatal Python error: %s\n", msg);
  1484. fflush(stderr); /* it helps in Windows debug build */
  1485. #ifdef MS_WINDOWS
  1486. {
  1487. size_t len = strlen(msg);
  1488. WCHAR* buffer;
  1489. size_t i;
  1490. /* Convert the message to wchar_t. This uses a simple one-to-one
  1491. conversion, assuming that the this error message actually uses ASCII
  1492. only. If this ceases to be true, we will have to convert. */
  1493. buffer = alloca( (len+1) * (sizeof *buffer));
  1494. for( i=0; i<=len; ++i)
  1495. buffer[i] = msg[i];
  1496. OutputDebugStringW(L"Fatal Python error: ");
  1497. OutputDebugStringW(buffer);
  1498. OutputDebugStringW(L"\n");
  1499. }
  1500. #ifdef _DEBUG
  1501. DebugBreak();
  1502. #endif
  1503. #endif /* MS_WINDOWS */
  1504. abort();
  1505. }
  1506. /* Clean up and exit */
  1507. #ifdef WITH_THREAD
  1508. #include "pythread.h"
  1509. #endif
  1510. /* Wait until threading._shutdown completes, provided
  1511. the threading module was imported in the first place.
  1512. The shutdown routine will wait until all non-daemon
  1513. "threading" threads have completed. */
  1514. static void
  1515. wait_for_thread_shutdown(void)
  1516. {
  1517. #ifdef WITH_THREAD
  1518. PyObject *result;
  1519. PyThreadState *tstate = PyThreadState_GET();
  1520. PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
  1521. "threading");
  1522. if (threading == NULL) {
  1523. /* threading not imported */
  1524. PyErr_Clear();
  1525. return;
  1526. }
  1527. result = PyObject_CallMethod(threading, "_shutdown", "");
  1528. if (result == NULL)
  1529. PyErr_WriteUnraisable(threading);
  1530. else
  1531. Py_DECREF(result);
  1532. Py_DECREF(threading);
  1533. #endif
  1534. }
  1535. #define NEXITFUNCS 32
  1536. static void (*exitfuncs[NEXITFUNCS])(void);
  1537. static int nexitfuncs = 0;
  1538. int Py_AtExit(void (*func)(void))
  1539. {
  1540. if (nexitfuncs >= NEXITFUNCS)
  1541. return -1;
  1542. exitfuncs[nexitfuncs++] = func;
  1543. return 0;
  1544. }
  1545. static void
  1546. call_sys_exitfunc(void)
  1547. {
  1548. PyObject *exitfunc = PySys_GetObject("exitfunc");
  1549. if (exitfunc) {
  1550. PyObject *res;
  1551. Py_INCREF(exitfunc);
  1552. PySys_SetObject("exitfunc", (PyObject *)NULL);
  1553. res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
  1554. if (res == NULL) {
  1555. if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
  1556. PySys_WriteStderr("Error in sys.exitfunc:\n");
  1557. }
  1558. PyErr_Print();
  1559. }
  1560. Py_DECREF(exitfunc);
  1561. }
  1562. if (Py_FlushLine())
  1563. PyErr_Clear();
  1564. }
  1565. static void
  1566. call_ll_exitfuncs(void)
  1567. {
  1568. while (nexitfuncs > 0)
  1569. (*exitfuncs[--nexitfuncs])();
  1570. fflush(stdout);
  1571. fflush(stderr);
  1572. }
  1573. void
  1574. Py_Exit(int sts)
  1575. {
  1576. Py_Finalize();
  1577. exit(sts);
  1578. }
  1579. static void
  1580. initsigs(void)
  1581. {
  1582. #ifdef SIGPIPE
  1583. PyOS_setsig(SIGPIPE, SIG_IGN);
  1584. #endif
  1585. #ifdef SIGXFZ
  1586. PyOS_setsig(SIGXFZ, SIG_IGN);
  1587. #endif
  1588. #ifdef SIGXFSZ
  1589. PyOS_setsig(SIGXFSZ, SIG_IGN);
  1590. #endif
  1591. PyOS_InitInterrupts(); /* May imply initsignal() */
  1592. }
  1593. /*
  1594. * The file descriptor fd is considered ``interactive'' if either
  1595. * a) isatty(fd) is TRUE, or
  1596. * b) the -i flag was given, and the filename associated with
  1597. * the descriptor is NULL or "<stdin>" or "???".
  1598. */
  1599. int
  1600. Py_FdIsInteractive(FILE *fp, const char *filename)
  1601. {
  1602. if (isatty((int)fileno(fp)))
  1603. return 1;
  1604. if (!Py_InteractiveFlag)
  1605. return 0;
  1606. return (filename == NULL) ||
  1607. (strcmp(filename, "<stdin>") == 0) ||
  1608. (strcmp(filename, "???") == 0);
  1609. }
  1610. #if defined(USE_STACKCHECK)
  1611. #if defined(WIN32) && defined(_MSC_VER)
  1612. /* Stack checking for Microsoft C */
  1613. #include <malloc.h>
  1614. #include <excpt.h>
  1615. /*
  1616. * Return non-zero when we run out of memory on the stack; zero otherwise.
  1617. */
  1618. int
  1619. PyOS_CheckStack(void)
  1620. {
  1621. __try {
  1622. /* alloca throws a stack overflow exception if there's
  1623. not enough space left on the stack */
  1624. alloca(PYOS_STACK_MARGIN * sizeof(void*));
  1625. return 0;
  1626. } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
  1627. EXCEPTION_EXECUTE_HANDLER :
  1628. EXCEPTION_CONTINUE_SEARCH) {
  1629. int errcode = _resetstkoflw();
  1630. if (errcode == 0)
  1631. {
  1632. Py_FatalError("Could not reset the stack!");
  1633. }
  1634. }
  1635. return 1;
  1636. }
  1637. #endif /* WIN32 && _MSC_VER */
  1638. /* Alternate implementations can be added here... */
  1639. #endif /* USE_STACKCHECK */
  1640. /* Wrappers around sigaction() or signal(). */
  1641. PyOS_sighandler_t
  1642. PyOS_getsig(int sig)
  1643. {
  1644. #ifdef HAVE_SIGACTION
  1645. struct sigaction context;
  1646. if (sigaction(sig, NULL, &context) == -1)
  1647. return SIG_ERR;
  1648. return context.sa_handler;
  1649. #else
  1650. PyOS_sighandler_t handler;
  1651. /* Special signal handling for the secure CRT in Visual Studio 2005 */
  1652. #if defined(_MSC_VER) && _MSC_VER >= 1400
  1653. switch (sig) {
  1654. /* Only these signals are valid */
  1655. case SIGINT:
  1656. case SIGILL:
  1657. case SIGFPE:
  1658. case SIGSEGV:
  1659. case SIGTERM:
  1660. case SIGBREAK:
  1661. case SIGABRT:
  1662. break;
  1663. /* Don't call signal() with other values or it will assert */
  1664. default:
  1665. return SIG_ERR;
  1666. }
  1667. #endif /* _MSC_VER && _MSC_VER >= 1400 */
  1668. handler = signal(sig, SIG_IGN);
  1669. if (handler != SIG_ERR)
  1670. signal(sig, handler);
  1671. return handler;
  1672. #endif
  1673. }
  1674. PyOS_sighandler_t
  1675. PyOS_setsig(int sig, PyOS_sighandler_t handler)
  1676. {
  1677. #ifdef HAVE_SIGACTION
  1678. /* Some code in Modules/signalmodule.c depends on sigaction() being
  1679. * used here if HAVE_SIGACTION is defined. Fix that if this code
  1680. * changes to invalidate that assumption.
  1681. */
  1682. struct sigaction context, ocontext;
  1683. context.sa_handler = handler;
  1684. sigemptyset(&context.sa_mask);
  1685. context.sa_flags = 0;
  1686. if (sigaction(sig, &context, &ocontext) == -1)
  1687. return SIG_ERR;
  1688. return ocontext.sa_handler;
  1689. #else
  1690. PyOS_sighandler_t oldhandler;
  1691. oldhandler = signal(sig, handler);
  1692. #ifdef HAVE_SIGINTERRUPT
  1693. siginterrupt(sig, 1);
  1694. #endif
  1695. return oldhandler;
  1696. #endif
  1697. }
  1698. /* Deprecated C API functions still provided for binary compatiblity */
  1699. #undef PyParser_SimpleParseFile
  1700. PyAPI_FUNC(node *)
  1701. PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
  1702. {
  1703. return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
  1704. }
  1705. #undef PyParser_SimpleParseString
  1706. PyAPI_FUNC(node *)
  1707. PyParser_SimpleParseString(const char *str, int start)
  1708. {
  1709. return PyParser_SimpleParseStringFlags(str, start, 0);
  1710. }
  1711. #undef PyRun_AnyFile
  1712. PyAPI_FUNC(int)
  1713. PyRun_AnyFile(FILE *fp, const char *name)
  1714. {
  1715. return PyRun_AnyFileExFlags(fp, name, 0, NULL);
  1716. }
  1717. #undef PyRun_AnyFileEx
  1718. PyAPI_FUNC(int)
  1719. PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
  1720. {
  1721. return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
  1722. }
  1723. #undef PyRun_AnyFileFlags
  1724. PyAPI_FUNC(int)
  1725. PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
  1726. {
  1727. return PyRun_AnyFileExFlags(fp, name, 0, flags);
  1728. }
  1729. #undef PyRun_File
  1730. PyAPI_FUNC(PyObject *)
  1731. PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
  1732. {
  1733. return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
  1734. }
  1735. #undef PyRun_FileEx
  1736. PyAPI_FUNC(PyObject *)
  1737. PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
  1738. {
  1739. return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
  1740. }
  1741. #undef PyRun_FileFlags
  1742. PyAPI_FUNC(PyObject *)
  1743. PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
  1744. PyCompilerFlags *flags)
  1745. {
  1746. return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
  1747. }
  1748. #undef PyRun_SimpleFile
  1749. PyAPI_FUNC(int)
  1750. PyRun_SimpleFile(FILE *f, const char *p)
  1751. {
  1752. return PyRun_SimpleFileExFlags(f, p, 0, NULL);
  1753. }
  1754. #undef PyRun_SimpleFileEx
  1755. PyAPI_FUNC(int)
  1756. PyRun_SimpleFileEx(FILE *f, const char *p, int c)
  1757. {
  1758. return PyRun_SimpleFileExFlags(f, p, c, NULL);
  1759. }
  1760. #undef PyRun_String
  1761. PyAPI_FUNC(PyObject *)
  1762. PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
  1763. {
  1764. return PyRun_StringFlags(str, s, g, l, NULL);
  1765. }
  1766. #undef PyRun_SimpleString
  1767. PyAPI_FUNC(int)
  1768. PyRun_SimpleString(const char *s)
  1769. {
  1770. return PyRun_SimpleStringFlags(s, NULL);
  1771. }
  1772. #undef Py_CompileString
  1773. PyAPI_FUNC(PyObject *)
  1774. Py_CompileString(const char *str, const char *p, int s)
  1775. {
  1776. return Py_CompileStringFlags(str, p, s, NULL);
  1777. }
  1778. #undef PyRun_InteractiveOne
  1779. PyAPI_FUNC(int)
  1780. PyRun_InteractiveOne(FILE *f, const char *p)
  1781. {
  1782. return PyRun_InteractiveOneFlags(f, p, NULL);
  1783. }
  1784. #undef PyRun_InteractiveLoop
  1785. PyAPI_FUNC(int)
  1786. PyRun_InteractiveLoop(FILE *f, const char *p)
  1787. {
  1788. return PyRun_InteractiveLoopFlags(f, p, NULL);
  1789. }
  1790. #ifdef __cplusplus
  1791. }
  1792. #endif