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.

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