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.

2016 lines
55 KiB

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