blob: 38b2ab84fbda34abdd17bfb7d928a81f7b185c60 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000016#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000017#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000023#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000024#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000025#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000026
Martin v. Löwis73d538b2003-03-05 15:13:47 +000027#ifdef HAVE_LANGINFO_H
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000033#undef BYTE
34#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000035#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#endif
37
Neal Norwitz4281cef2006-03-04 19:58:13 +000038#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000039#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000040#else /* Py_REF_DEBUG */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041#define PRINT_TOTAL_REFS() fprintf(stderr, \
42 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
43 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000044#endif
45
46#ifdef __cplusplus
47extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000048#endif
49
Martin v. Löwis790465f2008-04-05 20:41:37 +000050extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000051
Guido van Rossum82598051997-03-05 00:20:32 +000052extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000053
Guido van Rossumb73cc041993-11-01 16:28:59 +000054/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000055static void initmain(void);
Victor Stinnerb744ba12010-05-15 12:27:16 +000056static void initfsencoding(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000058static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000059static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000062static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000064static void err_input(perrdetail *);
65static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000066static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000067static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000068static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000069extern void _PyUnicode_Init(void);
70extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000071extern int _PyLong_Init(void);
72extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000073
Mark Hammond8d98d2c2003-04-19 15:41:53 +000074#ifdef WITH_THREAD
75extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
76extern void _PyGILState_Fini(void);
77#endif /* WITH_THREAD */
78
Guido van Rossum82598051997-03-05 00:20:32 +000079int Py_DebugFlag; /* Needed by parser.c */
80int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +000081int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000082int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000083int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000084int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000085int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000086int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000087int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000088int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000089int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000090int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000091int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000092
Christian Heimes33fe8092008-04-13 13:53:33 +000093/* PyModule_GetWarningsModule is no longer necessary as of 2.6
94since _warnings is builtin. This API should not be used. */
95PyObject *
96PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +000099}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000100
Guido van Rossum25ce5661997-08-02 03:10:38 +0000101static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000102
Thomas Wouters7e474022000-07-16 12:04:32 +0000103/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000104
105int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000106Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109}
110
Guido van Rossum25ce5661997-08-02 03:10:38 +0000111/* Global initializations. Can be undone by Py_Finalize(). Don't
112 call this twice without an intervening Py_Finalize() call. When
113 initializations fail, a fatal error is issued and the function does
114 not return. On return, the first thread and interpreter state have
115 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000116
Guido van Rossum25ce5661997-08-02 03:10:38 +0000117 Locking: you must hold the interpreter lock while calling this.
118 (If the lock has not yet been initialized, that's equivalent to
119 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000120
Guido van Rossum25ce5661997-08-02 03:10:38 +0000121*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000122
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000123static int
124add_flag(int flag, const char *envs)
125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 int env = atoi(envs);
127 if (flag < env)
128 flag = env;
129 if (flag < 1)
130 flag = 1;
131 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000132}
133
Christian Heimes5833a2f2008-10-30 21:40:04 +0000134static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000135get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000136{
Victor Stinner94908bb2010-08-18 21:23:25 +0000137 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000138 PyObject *codec, *name = NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000139
Victor Stinner94908bb2010-08-18 21:23:25 +0000140 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000141 if (!codec)
142 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 name = PyObject_GetAttrString(codec, "name");
145 Py_CLEAR(codec);
146 if (!name)
147 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000148
Victor Stinner94908bb2010-08-18 21:23:25 +0000149 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100150 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000151 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000152 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000154 if (name_str == NULL) {
155 PyErr_NoMemory();
156 return NULL;
157 }
158 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000159
160error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000162 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000164}
Victor Stinner94908bb2010-08-18 21:23:25 +0000165
166#if defined(HAVE_LANGINFO_H) && defined(CODESET)
167static char*
168get_codeset(void)
169{
170 char* codeset = nl_langinfo(CODESET);
171 if (!codeset || codeset[0] == '\0') {
172 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
173 return NULL;
174 }
175 return get_codec_name(codeset);
176}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000177#endif
178
Guido van Rossuma027efa1997-05-05 20:56:21 +0000179void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000180Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 PyInterpreterState *interp;
183 PyThreadState *tstate;
184 PyObject *bimod, *sysmod, *pstderr;
185 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 if (initialized)
189 return;
190 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000191
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000192#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 /* Set up the LC_CTYPE locale, so we can obtain
194 the locale's charset without having to switch
195 locales. */
196 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000197#endif
198
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
200 Py_DebugFlag = add_flag(Py_DebugFlag, p);
201 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
202 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
203 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
204 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
205 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
206 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 interp = PyInterpreterState_New();
209 if (interp == NULL)
210 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 tstate = PyThreadState_New(interp);
213 if (tstate == NULL)
214 Py_FatalError("Py_Initialize: can't make first thread");
215 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000216
Victor Stinner6961bd62010-08-17 22:26:51 +0000217#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000218 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
219 destroying the GIL might fail when it is being referenced from
220 another running thread (see issue #9901).
221 Instead we destroy the previously created GIL here, which ensures
222 that we can call Py_Initialize / Py_Finalize multiple times. */
223 _PyEval_FiniThreads();
224
225 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000226 _PyGILState_Init(interp, tstate);
227#endif /* WITH_THREAD */
228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 if (!_PyFrame_Init())
232 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 if (!_PyLong_Init())
235 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000237 if (!PyByteArray_Init())
238 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 interp->modules = PyDict_New();
243 if (interp->modules == NULL)
244 Py_FatalError("Py_Initialize: can't make modules dictionary");
245 interp->modules_reloading = PyDict_New();
246 if (interp->modules_reloading == NULL)
247 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 /* Init Unicode implementation; relies on the codec registry */
250 _PyUnicode_Init();
Guido van Rossumc94044c2000-03-10 23:03:54 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 bimod = _PyBuiltin_Init();
253 if (bimod == NULL)
254 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000255 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 interp->builtins = PyModule_GetDict(bimod);
257 if (interp->builtins == NULL)
258 Py_FatalError("Py_Initialize: can't initialize builtins dict");
259 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 /* initialize builtin exceptions */
262 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 sysmod = _PySys_Init();
265 if (sysmod == NULL)
266 Py_FatalError("Py_Initialize: can't initialize sys");
267 interp->sysdict = PyModule_GetDict(sysmod);
268 if (interp->sysdict == NULL)
269 Py_FatalError("Py_Initialize: can't initialize sys dict");
270 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000271 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 PySys_SetPath(Py_GetPath());
273 PyDict_SetItemString(interp->sysdict, "modules",
274 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 /* Set up a preliminary stderr printer until we have enough
277 infrastructure for the io module in place. */
278 pstderr = PyFile_NewStdPrinter(fileno(stderr));
279 if (pstderr == NULL)
280 Py_FatalError("Py_Initialize: can't set preliminary stderr");
281 PySys_SetObject("stderr", pstderr);
282 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000283 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000284
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000288
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000289 /* Initialize _warnings. */
290 _PyWarnings_Init();
291
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000292 _PyTime_Init();
293
Victor Stinnerb744ba12010-05-15 12:27:16 +0000294 initfsencoding();
Martin v. Löwis011e8422009-05-05 04:43:17 +0000295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 if (install_sigs)
297 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 initmain(); /* Module __main__ */
300 if (initstdio() < 0)
301 Py_FatalError(
302 "Py_Initialize: can't initialize sys standard streams");
303
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000304 /* Initialize warnings. */
305 if (PySys_HasWarnOptions()) {
306 PyObject *warnings_module = PyImport_ImportModule("warnings");
307 if (warnings_module == NULL) {
308 fprintf(stderr, "'import warnings' failed; traceback:\n");
309 PyErr_Print();
310 }
311 Py_XDECREF(warnings_module);
312 }
313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 if (!Py_NoSiteFlag)
315 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000316}
317
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000318void
319Py_Initialize(void)
320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000322}
323
324
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000325#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000326extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000327#endif
328
Guido van Rossume8432ac2007-07-09 15:04:50 +0000329/* Flush stdout and stderr */
330
Neal Norwitz2bad9702007-08-27 06:19:22 +0000331static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000332flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 PyObject *fout = PySys_GetObject("stdout");
335 PyObject *ferr = PySys_GetObject("stderr");
336 PyObject *tmp;
Guido van Rossume8432ac2007-07-09 15:04:50 +0000337
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000338 if (fout != NULL && fout != Py_None) {
339 tmp = PyObject_CallMethod(fout, "flush", "");
340 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000341 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 else
343 Py_DECREF(tmp);
344 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000345
Victor Stinner9467b212010-05-14 00:59:09 +0000346 if (ferr != NULL && ferr != Py_None) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 tmp = PyObject_CallMethod(ferr, "flush", "");
348 if (tmp == NULL)
349 PyErr_Clear();
350 else
351 Py_DECREF(tmp);
352 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000353}
354
Guido van Rossum25ce5661997-08-02 03:10:38 +0000355/* Undo the effect of Py_Initialize().
356
357 Beware: if multiple interpreter and/or thread states exist, these
358 are not wiped out; only the current thread and interpreter state
359 are deleted. But since everything else is deleted, those other
360 interpreter and thread states should no longer be used.
361
362 (XXX We should do better, e.g. wipe out all interpreters and
363 threads.)
364
365 Locking: as above.
366
367*/
368
369void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000370Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000371{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000372 PyInterpreterState *interp;
373 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 if (!initialized)
376 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 /* The interpreter is still entirely intact at this point, and the
381 * exit funcs may be relying on that. In particular, if some thread
382 * or exit func is still waiting to do an import, the import machinery
383 * expects Py_IsInitialized() to return true. So don't say the
384 * interpreter is uninitialized until after the exit funcs have run.
385 * Note that Threading.py uses an exit func to do a join on all the
386 * threads created thru it, so this also protects pending imports in
387 * the threads created via Threading.
388 */
389 call_py_exitfuncs();
390 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 /* Flush stdout+stderr */
393 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* Get current thread state and interpreter pointer */
396 tstate = PyThreadState_GET();
397 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 /* Disable signal handling */
400 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 /* Clear type lookup cache */
403 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 /* Collect garbage. This may call finalizers; it's nice to call these
406 * before all modules are destroyed.
407 * XXX If a __del__ or weakref callback is triggered here, and tries to
408 * XXX import a module, bad things can happen, because Python no
409 * XXX longer believes it's initialized.
410 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
411 * XXX is easy to provoke that way. I've also seen, e.g.,
412 * XXX Exception exceptions.ImportError: 'No module named sha'
413 * XXX in <function callback at 0x008F5718> ignored
414 * XXX but I'm unclear on exactly how that one happens. In any case,
415 * XXX I haven't seen a real-life report of either of these.
416 */
417 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000418#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 /* With COUNT_ALLOCS, it helps to run GC multiple times:
420 each collection might release some types from the type
421 list, so they become garbage. */
422 while (PyGC_Collect() > 0)
423 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000424#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000425 /* We run this while most interpreter state is still alive, so that
426 debug information can be printed out */
427 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 /* Destroy all modules */
430 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 /* Flush stdout+stderr (again, in case more was printed) */
433 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 /* Collect final garbage. This disposes of cycles created by
436 * new-style class definitions, for example.
437 * XXX This is disabled because it caused too many problems. If
438 * XXX a __del__ or weakref callback triggers here, Python code has
439 * XXX a hard time running, because even the sys module has been
440 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
441 * XXX One symptom is a sequence of information-free messages
442 * XXX coming from threads (if a __del__ or callback is invoked,
443 * XXX other threads can execute too, and any exception they encounter
444 * XXX triggers a comedy of errors as subsystem after subsystem
445 * XXX fails to find what it *expects* to find in sys to help report
446 * XXX the exception and consequent unexpected failures). I've also
447 * XXX seen segfaults then, after adding print statements to the
448 * XXX Python code getting called.
449 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000450#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000452#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000453
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
455 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000458#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000460#endif
461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000463
Tim Peters9cf25ce2003-04-17 15:21:01 +0000464#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 /* Display all objects still alive -- this can invoke arbitrary
466 * __repr__ overrides, so requires a mostly-intact interpreter.
467 * Alas, a lot of stuff may still be alive now that will be cleaned
468 * up later.
469 */
470 if (Py_GETENV("PYTHONDUMPREFS"))
471 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000472#endif /* Py_TRACE_REFS */
473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 /* Clear interpreter state */
475 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 /* Now we decref the exception classes. After this point nothing
478 can raise an exception. That's okay, because each Fini() method
479 below has been checked to make sure no exceptions are ever
480 raised.
481 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000484
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000486#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000488#endif /* WITH_THREAD */
489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 /* Delete current thread */
491 PyThreadState_Swap(NULL);
492 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 /* Sundry finalizers */
495 PyMethod_Fini();
496 PyFrame_Fini();
497 PyCFunction_Fini();
498 PyTuple_Fini();
499 PyList_Fini();
500 PySet_Fini();
501 PyBytes_Fini();
502 PyByteArray_Fini();
503 PyLong_Fini();
504 PyFloat_Fini();
505 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 /* Cleanup Unicode implementation */
508 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000511 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 free((char*)Py_FileSystemDefaultEncoding);
513 Py_FileSystemDefaultEncoding = NULL;
514 }
Christian Heimesc8967002007-11-30 10:18:26 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 /* XXX Still allocated:
517 - various static ad-hoc pointers to interned strings
518 - int and float free list blocks
519 - whatever various modules and libraries allocate
520 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000523
Tim Peters269b2a62003-04-17 19:52:29 +0000524#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 /* Display addresses (& refcnts) of all objects still alive.
526 * An address can be used to find the repr of the object, printed
527 * above by _Py_PrintReferences.
528 */
529 if (Py_GETENV("PYTHONDUMPREFS"))
530 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000531#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000532#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (Py_GETENV("PYTHONMALLOCSTATS"))
534 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000535#endif
536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000538}
539
540/* Create and initialize a new interpreter and thread, and return the
541 new thread. This requires that Py_Initialize() has been called
542 first.
543
544 Unsuccessful initialization yields a NULL pointer. Note that *no*
545 exception information is available even in this case -- the
546 exception information is held in the thread, and there is no
547 thread.
548
549 Locking: as above.
550
551*/
552
553PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000554Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 PyInterpreterState *interp;
557 PyThreadState *tstate, *save_tstate;
558 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 if (!initialized)
561 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 interp = PyInterpreterState_New();
564 if (interp == NULL)
565 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 tstate = PyThreadState_New(interp);
568 if (tstate == NULL) {
569 PyInterpreterState_Delete(interp);
570 return NULL;
571 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 interp->modules = PyDict_New();
578 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579
Victor Stinner49d3f252010-10-17 01:24:53 +0000580 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 if (bimod != NULL) {
582 interp->builtins = PyModule_GetDict(bimod);
583 if (interp->builtins == NULL)
584 goto handle_error;
585 Py_INCREF(interp->builtins);
586 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 /* initialize builtin exceptions */
589 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000590
Victor Stinner49d3f252010-10-17 01:24:53 +0000591 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (bimod != NULL && sysmod != NULL) {
593 PyObject *pstderr;
594 interp->sysdict = PyModule_GetDict(sysmod);
595 if (interp->sysdict == NULL)
596 goto handle_error;
597 Py_INCREF(interp->sysdict);
598 PySys_SetPath(Py_GetPath());
599 PyDict_SetItemString(interp->sysdict, "modules",
600 interp->modules);
601 /* Set up a preliminary stderr printer until we have enough
602 infrastructure for the io module in place. */
603 pstderr = PyFile_NewStdPrinter(fileno(stderr));
604 if (pstderr == NULL)
605 Py_FatalError("Py_Initialize: can't set preliminary stderr");
606 PySys_SetObject("stderr", pstderr);
607 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000608 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 _PyImportHooks_Init();
611 if (initstdio() < 0)
612 Py_FatalError(
613 "Py_Initialize: can't initialize sys standard streams");
614 initmain();
615 if (!Py_NoSiteFlag)
616 initsite();
617 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (!PyErr_Occurred())
620 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000621
Thomas Wouters89f507f2006-12-13 04:49:30 +0000622handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 PyErr_Print();
626 PyThreadState_Clear(tstate);
627 PyThreadState_Swap(save_tstate);
628 PyThreadState_Delete(tstate);
629 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000632}
633
634/* Delete an interpreter and its last thread. This requires that the
635 given thread state is current, that the thread has no remaining
636 frames, and that it is its interpreter's only remaining thread.
637 It is a fatal error to violate these constraints.
638
639 (Py_Finalize() doesn't have these constraints -- it zaps
640 everything, regardless.)
641
642 Locking: as above.
643
644*/
645
646void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000647Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 if (tstate != PyThreadState_GET())
652 Py_FatalError("Py_EndInterpreter: thread is not current");
653 if (tstate->frame != NULL)
654 Py_FatalError("Py_EndInterpreter: thread still has a frame");
655 if (tstate != interp->tstate_head || tstate->next != NULL)
656 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000657
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 PyImport_Cleanup();
659 PyInterpreterState_Clear(interp);
660 PyThreadState_Swap(NULL);
661 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000662}
663
Martin v. Löwis790465f2008-04-05 20:41:37 +0000664static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000665
666void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000667Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if (pn && *pn)
670 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000671}
672
Martin v. Löwis790465f2008-04-05 20:41:37 +0000673wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000674Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000675{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000676 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000677}
678
Martin v. Löwis790465f2008-04-05 20:41:37 +0000679static wchar_t *default_home = NULL;
680static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000681
682void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000683Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000686}
687
Martin v. Löwis790465f2008-04-05 20:41:37 +0000688wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000689Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 wchar_t *home = default_home;
692 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
693 char* chome = Py_GETENV("PYTHONHOME");
694 if (chome) {
695 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
696 if (r != (size_t)-1 && r <= PATH_MAX)
697 home = env_home;
698 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 }
701 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000702}
703
Guido van Rossum6135a871995-01-09 17:53:26 +0000704/* Create __main__ module */
705
706static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000707initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 PyObject *m, *d;
710 m = PyImport_AddModule("__main__");
711 if (m == NULL)
712 Py_FatalError("can't create __main__ module");
713 d = PyModule_GetDict(m);
714 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
715 PyObject *bimod = PyImport_ImportModule("builtins");
716 if (bimod == NULL ||
717 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
718 Py_FatalError("can't add __builtins__ to __main__");
719 Py_DECREF(bimod);
720 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000721}
722
Victor Stinnerb744ba12010-05-15 12:27:16 +0000723static void
724initfsencoding(void)
725{
726 PyObject *codec;
727#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000728 char *codeset = NULL;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000729
Victor Stinner7f84ab52010-06-11 00:36:33 +0000730 if (Py_FileSystemDefaultEncoding == NULL) {
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000731 /* On Unix, set the file system encoding according to the
732 user's preference, if the CODESET names a well-known
733 Python codec, and Py_FileSystemDefaultEncoding isn't
Victor Stinnere4743092010-10-19 00:05:51 +0000734 initialized by other means. */
Victor Stinner8f6b6b02010-10-13 22:02:27 +0000735 codeset = get_codeset();
Victor Stinnere4743092010-10-19 00:05:51 +0000736 if (codeset == NULL)
737 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000738
Victor Stinnere4743092010-10-19 00:05:51 +0000739 Py_FileSystemDefaultEncoding = codeset;
740 Py_HasFileSystemDefaultEncoding = 0;
741 return;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000742 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000743#endif
744
745 /* the encoding is mbcs, utf-8 or ascii */
746 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
747 if (!codec) {
748 /* Such error can only occurs in critical situations: no more
749 * memory, import a module of the standard library failed,
750 * etc. */
751 Py_FatalError("Py_Initialize: unable to load the file system codec");
752 } else {
753 Py_DECREF(codec);
754 }
755}
756
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000757/* Import the site module (not into __main__ though) */
758
759static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000760initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000762 PyObject *m;
763 m = PyImport_ImportModule("site");
764 if (m == NULL) {
765 PyErr_Print();
766 Py_Finalize();
767 exit(1);
768 }
769 else {
770 Py_DECREF(m);
771 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000772}
773
Antoine Pitrou05608432009-01-09 18:53:14 +0000774static PyObject*
775create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 int fd, int write_mode, char* name,
777 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
780 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000781 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 PyObject *line_buffering;
783 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 /* stdin is always opened in buffered mode, first because it shouldn't
786 make a difference in common use cases, second because TextIOWrapper
787 depends on the presence of a read1() method which only exists on
788 buffered streams.
789 */
790 if (Py_UnbufferedStdioFlag && write_mode)
791 buffering = 0;
792 else
793 buffering = -1;
794 if (write_mode)
795 mode = "wb";
796 else
797 mode = "rb";
798 buf = PyObject_CallMethod(io, "open", "isiOOOi",
799 fd, mode, buffering,
800 Py_None, Py_None, Py_None, 0);
801 if (buf == NULL)
802 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 if (buffering) {
805 raw = PyObject_GetAttrString(buf, "raw");
806 if (raw == NULL)
807 goto error;
808 }
809 else {
810 raw = buf;
811 Py_INCREF(raw);
812 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 text = PyUnicode_FromString(name);
815 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
816 goto error;
817 res = PyObject_CallMethod(raw, "isatty", "");
818 if (res == NULL)
819 goto error;
820 isatty = PyObject_IsTrue(res);
821 Py_DECREF(res);
822 if (isatty == -1)
823 goto error;
824 if (isatty || Py_UnbufferedStdioFlag)
825 line_buffering = Py_True;
826 else
827 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 Py_CLEAR(raw);
830 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000831
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000832 newline = "\n";
833#ifdef MS_WINDOWS
834 if (!write_mode) {
835 /* translate \r\n to \n for sys.stdin on Windows */
836 newline = NULL;
837 }
838#endif
839
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
841 buf, encoding, errors,
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000842 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 Py_CLEAR(buf);
844 if (stream == NULL)
845 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 if (write_mode)
848 mode = "w";
849 else
850 mode = "r";
851 text = PyUnicode_FromString(mode);
852 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
853 goto error;
854 Py_CLEAR(text);
855 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000856
857error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 Py_XDECREF(buf);
859 Py_XDECREF(stream);
860 Py_XDECREF(text);
861 Py_XDECREF(raw);
862 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000863}
864
Georg Brandl1a3284e2007-12-02 09:40:06 +0000865/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000866static int
867initstdio(void)
868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 PyObject *iomod = NULL, *wrapper;
870 PyObject *bimod = NULL;
871 PyObject *m;
872 PyObject *std = NULL;
873 int status = 0, fd;
874 PyObject * encoding_attr;
875 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000876
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 /* Hack to avoid a nasty recursion issue when Python is invoked
878 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
879 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
880 goto error;
881 }
882 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000883
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000884 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
885 goto error;
886 }
887 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 if (!(bimod = PyImport_ImportModule("builtins"))) {
890 goto error;
891 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000892
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 if (!(iomod = PyImport_ImportModule("io"))) {
894 goto error;
895 }
896 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
897 goto error;
898 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 /* Set builtins.open */
901 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000902 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 goto error;
904 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000905 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000906
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 encoding = Py_GETENV("PYTHONIOENCODING");
908 errors = NULL;
909 if (encoding) {
910 encoding = strdup(encoding);
911 errors = strchr(encoding, ':');
912 if (errors) {
913 *errors = '\0';
914 errors++;
915 }
916 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000917
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 /* Set sys.stdin */
919 fd = fileno(stdin);
920 /* Under some conditions stdin, stdout and stderr may not be connected
921 * and fileno() may point to an invalid file descriptor. For example
922 * GUI apps don't have valid standard streams by default.
923 */
924 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000925#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 std = Py_None;
927 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000928#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000929 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000930#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 }
932 else {
933 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
934 if (std == NULL)
935 goto error;
936 } /* if (fd < 0) */
937 PySys_SetObject("__stdin__", std);
938 PySys_SetObject("stdin", std);
939 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 /* Set sys.stdout */
942 fd = fileno(stdout);
943 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000944#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 std = Py_None;
946 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000947#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000948 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000949#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 }
951 else {
952 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
953 if (std == NULL)
954 goto error;
955 } /* if (fd < 0) */
956 PySys_SetObject("__stdout__", std);
957 PySys_SetObject("stdout", std);
958 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000959
Guido van Rossum98297ee2007-11-06 21:34:58 +0000960#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 /* Set sys.stderr, replaces the preliminary stderr */
962 fd = fileno(stderr);
963 if (fd < 0) {
Christian Heimes58cb1b82007-11-13 02:19:40 +0000964#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 std = Py_None;
966 Py_INCREF(std);
Christian Heimes58cb1b82007-11-13 02:19:40 +0000967#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000969#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 }
971 else {
972 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
973 if (std == NULL)
974 goto error;
975 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 /* Same as hack above, pre-import stderr's codec to avoid recursion
978 when import.c tries to write to stderr in verbose mode. */
979 encoding_attr = PyObject_GetAttrString(std, "encoding");
980 if (encoding_attr != NULL) {
981 const char * encoding;
982 encoding = _PyUnicode_AsString(encoding_attr);
983 if (encoding != NULL) {
984 _PyCodec_Lookup(encoding);
985 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000986 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 }
988 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +0000989
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 PySys_SetObject("__stderr__", std);
991 PySys_SetObject("stderr", std);
992 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000993#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000994
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000996 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 status = -1;
998 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 if (encoding)
1001 free(encoding);
1002 Py_XDECREF(bimod);
1003 Py_XDECREF(iomod);
1004 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001005}
1006
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001007/* Parse input from a file and execute it */
1008
1009int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001010PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 if (filename == NULL)
1014 filename = "???";
1015 if (Py_FdIsInteractive(fp, filename)) {
1016 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1017 if (closeit)
1018 fclose(fp);
1019 return err;
1020 }
1021 else
1022 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001023}
1024
1025int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001026PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 PyObject *v;
1029 int ret;
1030 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 if (flags == NULL) {
1033 flags = &local_flags;
1034 local_flags.cf_flags = 0;
1035 }
1036 v = PySys_GetObject("ps1");
1037 if (v == NULL) {
1038 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1039 Py_XDECREF(v);
1040 }
1041 v = PySys_GetObject("ps2");
1042 if (v == NULL) {
1043 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1044 Py_XDECREF(v);
1045 }
1046 for (;;) {
1047 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1048 PRINT_TOTAL_REFS();
1049 if (ret == E_EOF)
1050 return 0;
1051 /*
1052 if (ret == E_NOMEM)
1053 return -1;
1054 */
1055 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001056}
1057
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001058/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001059static int PARSER_FLAGS(PyCompilerFlags *flags)
1060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 int parser_flags = 0;
1062 if (!flags)
1063 return 0;
1064 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1065 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1066 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1067 parser_flags |= PyPARSE_IGNORE_COOKIE;
1068 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1069 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1070 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001071}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001072
Thomas Wouters89f507f2006-12-13 04:49:30 +00001073#if 0
1074/* Keep an example of flags with future keyword support. */
1075#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1077 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1078 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1079 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001080#endif
1081
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001082int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001083PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 PyObject *m, *d, *v, *w, *oenc = NULL;
1086 mod_ty mod;
1087 PyArena *arena;
1088 char *ps1 = "", *ps2 = "", *enc = NULL;
1089 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 if (fp == stdin) {
1092 /* Fetch encoding from sys.stdin */
1093 v = PySys_GetObject("stdin");
1094 if (v == NULL || v == Py_None)
1095 return -1;
1096 oenc = PyObject_GetAttrString(v, "encoding");
1097 if (!oenc)
1098 return -1;
1099 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001100 if (enc == NULL)
1101 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 }
1103 v = PySys_GetObject("ps1");
1104 if (v != NULL) {
1105 v = PyObject_Str(v);
1106 if (v == NULL)
1107 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001108 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001110 if (ps1 == NULL) {
1111 PyErr_Clear();
1112 ps1 = "";
1113 }
1114 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 }
1116 w = PySys_GetObject("ps2");
1117 if (w != NULL) {
1118 w = PyObject_Str(w);
1119 if (w == NULL)
1120 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001121 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001123 if (ps2 == NULL) {
1124 PyErr_Clear();
1125 ps2 = "";
1126 }
1127 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 }
1129 arena = PyArena_New();
1130 if (arena == NULL) {
1131 Py_XDECREF(v);
1132 Py_XDECREF(w);
1133 Py_XDECREF(oenc);
1134 return -1;
1135 }
1136 mod = PyParser_ASTFromFile(fp, filename, enc,
1137 Py_single_input, ps1, ps2,
1138 flags, &errcode, arena);
1139 Py_XDECREF(v);
1140 Py_XDECREF(w);
1141 Py_XDECREF(oenc);
1142 if (mod == NULL) {
1143 PyArena_Free(arena);
1144 if (errcode == E_EOF) {
1145 PyErr_Clear();
1146 return E_EOF;
1147 }
1148 PyErr_Print();
1149 return -1;
1150 }
1151 m = PyImport_AddModule("__main__");
1152 if (m == NULL) {
1153 PyArena_Free(arena);
1154 return -1;
1155 }
1156 d = PyModule_GetDict(m);
1157 v = run_mod(mod, filename, d, d, flags, arena);
1158 PyArena_Free(arena);
1159 flush_io();
1160 if (v == NULL) {
1161 PyErr_Print();
1162 return -1;
1163 }
1164 Py_DECREF(v);
1165 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001166}
1167
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001168/* Check whether a file maybe a pyc file: Look at the extension,
1169 the file type, and, if we may close it, at the first few bytes. */
1170
1171static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001172maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001173{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1175 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 /* Only look into the file if we are allowed to close it, since
1178 it then should also be seekable. */
1179 if (closeit) {
1180 /* Read only two bytes of the magic. If the file was opened in
1181 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1182 be read as they are on disk. */
1183 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1184 unsigned char buf[2];
1185 /* Mess: In case of -x, the stream is NOT at its start now,
1186 and ungetc() was used to push back the first newline,
1187 which makes the current stream position formally undefined,
1188 and a x-platform nightmare.
1189 Unfortunately, we have no direct way to know whether -x
1190 was specified. So we use a terrible hack: if the current
1191 stream position is not 0, we assume -x was specified, and
1192 give up. Bug 132850 on SourceForge spells out the
1193 hopelessness of trying anything else (fseek and ftell
1194 don't work predictably x-platform for text-mode files).
1195 */
1196 int ispyc = 0;
1197 if (ftell(fp) == 0) {
1198 if (fread(buf, 1, 2, fp) == 2 &&
1199 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1200 ispyc = 1;
1201 rewind(fp);
1202 }
1203 return ispyc;
1204 }
1205 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001206}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001207
Guido van Rossum0df002c2000-08-27 19:21:52 +00001208int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001209PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001211{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 PyObject *m, *d, *v;
1213 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001214 int set_file_name = 0, ret;
1215 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 m = PyImport_AddModule("__main__");
1218 if (m == NULL)
1219 return -1;
1220 d = PyModule_GetDict(m);
1221 if (PyDict_GetItemString(d, "__file__") == NULL) {
1222 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001223 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 if (f == NULL)
1225 return -1;
1226 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1227 Py_DECREF(f);
1228 return -1;
1229 }
1230 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1231 return -1;
1232 set_file_name = 1;
1233 Py_DECREF(f);
1234 }
1235 len = strlen(filename);
1236 ext = filename + len - (len > 4 ? 4 : 0);
1237 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1238 /* Try to run a pyc file. First, re-open in binary */
1239 if (closeit)
1240 fclose(fp);
1241 if ((fp = fopen(filename, "rb")) == NULL) {
1242 fprintf(stderr, "python: Can't reopen .pyc file\n");
1243 ret = -1;
1244 goto done;
1245 }
1246 /* Turn on optimization if a .pyo file is given */
1247 if (strcmp(ext, ".pyo") == 0)
1248 Py_OptimizeFlag = 1;
1249 v = run_pyc_file(fp, filename, d, d, flags);
1250 } else {
1251 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1252 closeit, flags);
1253 }
1254 flush_io();
1255 if (v == NULL) {
1256 PyErr_Print();
1257 ret = -1;
1258 goto done;
1259 }
1260 Py_DECREF(v);
1261 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001262 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1264 PyErr_Clear();
1265 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001266}
1267
1268int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001269PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 PyObject *m, *d, *v;
1272 m = PyImport_AddModule("__main__");
1273 if (m == NULL)
1274 return -1;
1275 d = PyModule_GetDict(m);
1276 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1277 if (v == NULL) {
1278 PyErr_Print();
1279 return -1;
1280 }
1281 Py_DECREF(v);
1282 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001283}
1284
Barry Warsaw035574d1997-08-29 22:07:17 +00001285static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001286parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 long hold;
1290 PyObject *v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 /* old style errors */
1293 if (PyTuple_Check(err))
1294 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
1295 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 if (! (v = PyObject_GetAttrString(err, "msg")))
1300 goto finally;
1301 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 if (!(v = PyObject_GetAttrString(err, "filename")))
1304 goto finally;
1305 if (v == Py_None)
1306 *filename = NULL;
1307 else if (! (*filename = _PyUnicode_AsString(v)))
1308 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 Py_DECREF(v);
1311 if (!(v = PyObject_GetAttrString(err, "lineno")))
1312 goto finally;
1313 hold = PyLong_AsLong(v);
1314 Py_DECREF(v);
1315 v = NULL;
1316 if (hold < 0 && PyErr_Occurred())
1317 goto finally;
1318 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001319
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 if (!(v = PyObject_GetAttrString(err, "offset")))
1321 goto finally;
1322 if (v == Py_None) {
1323 *offset = -1;
1324 Py_DECREF(v);
1325 v = NULL;
1326 } else {
1327 hold = PyLong_AsLong(v);
1328 Py_DECREF(v);
1329 v = NULL;
1330 if (hold < 0 && PyErr_Occurred())
1331 goto finally;
1332 *offset = (int)hold;
1333 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 if (!(v = PyObject_GetAttrString(err, "text")))
1336 goto finally;
1337 if (v == Py_None)
1338 *text = NULL;
1339 else if (!PyUnicode_Check(v) ||
1340 !(*text = _PyUnicode_AsString(v)))
1341 goto finally;
1342 Py_DECREF(v);
1343 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001344
1345finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 Py_XDECREF(v);
1347 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001348}
1349
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001350void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001351PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001354}
1355
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001356static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001357print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 char *nl;
1360 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001361 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1362 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 for (;;) {
1364 nl = strchr(text, '\n');
1365 if (nl == NULL || nl-text >= offset)
1366 break;
1367 offset -= (int)(nl+1-text);
1368 text = nl+1;
1369 }
1370 while (*text == ' ' || *text == '\t') {
1371 text++;
1372 offset--;
1373 }
1374 }
1375 PyFile_WriteString(" ", f);
1376 PyFile_WriteString(text, f);
1377 if (*text == '\0' || text[strlen(text)-1] != '\n')
1378 PyFile_WriteString("\n", f);
1379 if (offset == -1)
1380 return;
1381 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001382 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001385}
1386
Guido van Rossum66e8e862001-03-23 17:54:43 +00001387static void
1388handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 PyObject *exception, *value, *tb;
1391 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 if (Py_InspectFlag)
1394 /* Don't exit if -i flag was given. This flag is set to 0
1395 * when entering interactive mode for inspecting. */
1396 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 PyErr_Fetch(&exception, &value, &tb);
1399 fflush(stdout);
1400 if (value == NULL || value == Py_None)
1401 goto done;
1402 if (PyExceptionInstance_Check(value)) {
1403 /* The error code should be in the `code' attribute. */
1404 PyObject *code = PyObject_GetAttrString(value, "code");
1405 if (code) {
1406 Py_DECREF(value);
1407 value = code;
1408 if (value == Py_None)
1409 goto done;
1410 }
1411 /* If we failed to dig out the 'code' attribute,
1412 just let the else clause below print the error. */
1413 }
1414 if (PyLong_Check(value))
1415 exitcode = (int)PyLong_AsLong(value);
1416 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001417 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001418 if (sys_stderr != NULL && sys_stderr != Py_None) {
1419 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1420 } else {
1421 PyObject_Print(value, stderr, Py_PRINT_RAW);
1422 fflush(stderr);
1423 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 PySys_WriteStderr("\n");
1425 exitcode = 1;
1426 }
Tim Peterscf615b52003-04-19 18:47:02 +00001427 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 /* Restore and clear the exception info, in order to properly decref
1429 * the exception, value, and traceback. If we just exit instead,
1430 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1431 * some finalizers from running.
1432 */
1433 PyErr_Restore(exception, value, tb);
1434 PyErr_Clear();
1435 Py_Exit(exitcode);
1436 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001437}
1438
1439void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001440PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001443
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1445 handle_system_exit();
1446 }
1447 PyErr_Fetch(&exception, &v, &tb);
1448 if (exception == NULL)
1449 return;
1450 PyErr_NormalizeException(&exception, &v, &tb);
1451 if (tb == NULL) {
1452 tb = Py_None;
1453 Py_INCREF(tb);
1454 }
1455 PyException_SetTraceback(v, tb);
1456 if (exception == NULL)
1457 return;
1458 /* Now we know v != NULL too */
1459 if (set_sys_last_vars) {
1460 PySys_SetObject("last_type", exception);
1461 PySys_SetObject("last_value", v);
1462 PySys_SetObject("last_traceback", tb);
1463 }
1464 hook = PySys_GetObject("excepthook");
1465 if (hook) {
1466 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1467 PyObject *result = PyEval_CallObject(hook, args);
1468 if (result == NULL) {
1469 PyObject *exception2, *v2, *tb2;
1470 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1471 handle_system_exit();
1472 }
1473 PyErr_Fetch(&exception2, &v2, &tb2);
1474 PyErr_NormalizeException(&exception2, &v2, &tb2);
1475 /* It should not be possible for exception2 or v2
1476 to be NULL. However PyErr_Display() can't
1477 tolerate NULLs, so just be safe. */
1478 if (exception2 == NULL) {
1479 exception2 = Py_None;
1480 Py_INCREF(exception2);
1481 }
1482 if (v2 == NULL) {
1483 v2 = Py_None;
1484 Py_INCREF(v2);
1485 }
1486 fflush(stdout);
1487 PySys_WriteStderr("Error in sys.excepthook:\n");
1488 PyErr_Display(exception2, v2, tb2);
1489 PySys_WriteStderr("\nOriginal exception was:\n");
1490 PyErr_Display(exception, v, tb);
1491 Py_DECREF(exception2);
1492 Py_DECREF(v2);
1493 Py_XDECREF(tb2);
1494 }
1495 Py_XDECREF(result);
1496 Py_XDECREF(args);
1497 } else {
1498 PySys_WriteStderr("sys.excepthook is missing\n");
1499 PyErr_Display(exception, v, tb);
1500 }
1501 Py_XDECREF(exception);
1502 Py_XDECREF(v);
1503 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001504}
1505
Benjamin Petersone6528212008-07-15 15:32:09 +00001506static void
1507print_exception(PyObject *f, PyObject *value)
1508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 int err = 0;
1510 PyObject *type, *tb;
Benjamin Petersone6528212008-07-15 15:32:09 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 if (!PyExceptionInstance_Check(value)) {
1513 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1514 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1515 PyFile_WriteString(" found\n", f);
1516 return;
1517 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 Py_INCREF(value);
1520 fflush(stdout);
1521 type = (PyObject *) Py_TYPE(value);
1522 tb = PyException_GetTraceback(value);
1523 if (tb && tb != Py_None)
1524 err = PyTraceBack_Print(tb, f);
1525 if (err == 0 &&
1526 PyObject_HasAttrString(value, "print_file_and_line"))
1527 {
1528 PyObject *message;
1529 const char *filename, *text;
1530 int lineno, offset;
1531 if (!parse_syntax_error(value, &message, &filename,
1532 &lineno, &offset, &text))
1533 PyErr_Clear();
1534 else {
1535 char buf[10];
1536 PyFile_WriteString(" File \"", f);
1537 if (filename == NULL)
1538 PyFile_WriteString("<string>", f);
1539 else
1540 PyFile_WriteString(filename, f);
1541 PyFile_WriteString("\", line ", f);
1542 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1543 PyFile_WriteString(buf, f);
1544 PyFile_WriteString("\n", f);
1545 if (text != NULL)
1546 print_error_text(f, offset, text);
1547 Py_DECREF(value);
1548 value = message;
1549 /* Can't be bothered to check all those
1550 PyFile_WriteString() calls */
1551 if (PyErr_Occurred())
1552 err = -1;
1553 }
1554 }
1555 if (err) {
1556 /* Don't do anything else */
1557 }
1558 else {
1559 PyObject* moduleName;
1560 char* className;
1561 assert(PyExceptionClass_Check(type));
1562 className = PyExceptionClass_Name(type);
1563 if (className != NULL) {
1564 char *dot = strrchr(className, '.');
1565 if (dot != NULL)
1566 className = dot+1;
1567 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001568
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 moduleName = PyObject_GetAttrString(type, "__module__");
1570 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1571 {
1572 Py_DECREF(moduleName);
1573 err = PyFile_WriteString("<unknown>", f);
1574 }
1575 else {
1576 char* modstr = _PyUnicode_AsString(moduleName);
1577 if (modstr && strcmp(modstr, "builtins"))
1578 {
1579 err = PyFile_WriteString(modstr, f);
1580 err += PyFile_WriteString(".", f);
1581 }
1582 Py_DECREF(moduleName);
1583 }
1584 if (err == 0) {
1585 if (className == NULL)
1586 err = PyFile_WriteString("<unknown>", f);
1587 else
1588 err = PyFile_WriteString(className, f);
1589 }
1590 }
1591 if (err == 0 && (value != Py_None)) {
1592 PyObject *s = PyObject_Str(value);
1593 /* only print colon if the str() of the
1594 object is not the empty string
1595 */
1596 if (s == NULL)
1597 err = -1;
1598 else if (!PyUnicode_Check(s) ||
1599 PyUnicode_GetSize(s) != 0)
1600 err = PyFile_WriteString(": ", f);
1601 if (err == 0)
1602 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1603 Py_XDECREF(s);
1604 }
1605 /* try to write a newline in any case */
1606 err += PyFile_WriteString("\n", f);
1607 Py_XDECREF(tb);
1608 Py_DECREF(value);
1609 /* If an error happened here, don't show it.
1610 XXX This is wrong, but too many callers rely on this behavior. */
1611 if (err != 0)
1612 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001613}
1614
1615static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 "\nThe above exception was the direct cause "
1617 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001618
1619static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 "\nDuring handling of the above exception, "
1621 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001622
1623static void
1624print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 int err = 0, res;
1627 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 if (seen != NULL) {
1630 /* Exception chaining */
1631 if (PySet_Add(seen, value) == -1)
1632 PyErr_Clear();
1633 else if (PyExceptionInstance_Check(value)) {
1634 cause = PyException_GetCause(value);
1635 context = PyException_GetContext(value);
1636 if (cause) {
1637 res = PySet_Contains(seen, cause);
1638 if (res == -1)
1639 PyErr_Clear();
1640 if (res == 0) {
1641 print_exception_recursive(
1642 f, cause, seen);
1643 err |= PyFile_WriteString(
1644 cause_message, f);
1645 }
1646 }
1647 else if (context) {
1648 res = PySet_Contains(seen, context);
1649 if (res == -1)
1650 PyErr_Clear();
1651 if (res == 0) {
1652 print_exception_recursive(
1653 f, context, seen);
1654 err |= PyFile_WriteString(
1655 context_message, f);
1656 }
1657 }
1658 Py_XDECREF(context);
1659 Py_XDECREF(cause);
1660 }
1661 }
1662 print_exception(f, value);
1663 if (err != 0)
1664 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001665}
1666
Thomas Wouters477c8d52006-05-27 19:21:47 +00001667void
1668PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 PyObject *seen;
1671 PyObject *f = PySys_GetObject("stderr");
1672 if (f == Py_None) {
1673 /* pass */
1674 }
1675 else if (f == NULL) {
1676 _PyObject_Dump(value);
1677 fprintf(stderr, "lost sys.stderr\n");
1678 }
1679 else {
1680 /* We choose to ignore seen being possibly NULL, and report
1681 at least the main exception (it could be a MemoryError).
1682 */
1683 seen = PySet_New(NULL);
1684 if (seen == NULL)
1685 PyErr_Clear();
1686 print_exception_recursive(f, value, seen);
1687 Py_XDECREF(seen);
1688 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001689}
1690
Guido van Rossum82598051997-03-05 00:20:32 +00001691PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001692PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 PyObject *ret = NULL;
1696 mod_ty mod;
1697 PyArena *arena = PyArena_New();
1698 if (arena == NULL)
1699 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1702 if (mod != NULL)
1703 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1704 PyArena_Free(arena);
1705 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001706}
1707
1708PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001709PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 PyObject *ret;
1713 mod_ty mod;
1714 PyArena *arena = PyArena_New();
1715 if (arena == NULL)
1716 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1719 flags, NULL, arena);
1720 if (closeit)
1721 fclose(fp);
1722 if (mod == NULL) {
1723 PyArena_Free(arena);
1724 return NULL;
1725 }
1726 ret = run_mod(mod, filename, globals, locals, flags, arena);
1727 PyArena_Free(arena);
1728 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001729}
1730
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001731static void
1732flush_io(void)
1733{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 PyObject *f, *r;
1735 PyObject *type, *value, *traceback;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 /* Save the current exception */
1738 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 f = PySys_GetObject("stderr");
1741 if (f != NULL) {
1742 r = PyObject_CallMethod(f, "flush", "");
1743 if (r)
1744 Py_DECREF(r);
1745 else
1746 PyErr_Clear();
1747 }
1748 f = PySys_GetObject("stdout");
1749 if (f != NULL) {
1750 r = PyObject_CallMethod(f, "flush", "");
1751 if (r)
1752 Py_DECREF(r);
1753 else
1754 PyErr_Clear();
1755 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001758}
1759
Guido van Rossum82598051997-03-05 00:20:32 +00001760static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001761run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 PyCodeObject *co;
1765 PyObject *v;
1766 co = PyAST_Compile(mod, filename, flags, arena);
1767 if (co == NULL)
1768 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001769 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 Py_DECREF(co);
1771 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001772}
1773
Guido van Rossum82598051997-03-05 00:20:32 +00001774static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001775run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 PyCodeObject *co;
1779 PyObject *v;
1780 long magic;
1781 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 magic = PyMarshal_ReadLongFromFile(fp);
1784 if (magic != PyImport_GetMagicNumber()) {
1785 PyErr_SetString(PyExc_RuntimeError,
1786 "Bad magic number in .pyc file");
1787 return NULL;
1788 }
1789 (void) PyMarshal_ReadLongFromFile(fp);
1790 v = PyMarshal_ReadLastObjectFromFile(fp);
1791 fclose(fp);
1792 if (v == NULL || !PyCode_Check(v)) {
1793 Py_XDECREF(v);
1794 PyErr_SetString(PyExc_RuntimeError,
1795 "Bad code object in .pyc file");
1796 return NULL;
1797 }
1798 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001799 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 if (v && flags)
1801 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1802 Py_DECREF(co);
1803 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001804}
1805
Guido van Rossum82598051997-03-05 00:20:32 +00001806PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001807Py_CompileStringExFlags(const char *str, const char *filename, int start,
1808 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 PyCodeObject *co;
1811 mod_ty mod;
1812 PyArena *arena = PyArena_New();
1813 if (arena == NULL)
1814 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1817 if (mod == NULL) {
1818 PyArena_Free(arena);
1819 return NULL;
1820 }
1821 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1822 PyObject *result = PyAST_mod2obj(mod);
1823 PyArena_Free(arena);
1824 return result;
1825 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001826 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 PyArena_Free(arena);
1828 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001829}
1830
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001831/* For use in Py_LIMITED_API */
1832#undef Py_CompileString
1833PyObject *
1834PyCompileString(const char *str, const char *filename, int start)
1835{
1836 return Py_CompileStringFlags(str, filename, start, NULL);
1837}
1838
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001839struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001840Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 struct symtable *st;
1843 mod_ty mod;
1844 PyCompilerFlags flags;
1845 PyArena *arena = PyArena_New();
1846 if (arena == NULL)
1847 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 flags.cf_flags = 0;
1850 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1851 if (mod == NULL) {
1852 PyArena_Free(arena);
1853 return NULL;
1854 }
1855 st = PySymtable_Build(mod, filename, 0);
1856 PyArena_Free(arena);
1857 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001858}
1859
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001860/* Preferred access to parser is through AST. */
1861mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001862PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 mod_ty mod;
1866 PyCompilerFlags localflags;
1867 perrdetail err;
1868 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1871 &_PyParser_Grammar, start, &err,
1872 &iflags);
1873 if (flags == NULL) {
1874 localflags.cf_flags = 0;
1875 flags = &localflags;
1876 }
1877 if (n) {
1878 flags->cf_flags |= iflags & PyCF_MASK;
1879 mod = PyAST_FromNode(n, flags, filename, arena);
1880 PyNode_Free(n);
1881 return mod;
1882 }
1883 else {
1884 err_input(&err);
1885 return NULL;
1886 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001887}
1888
1889mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001890PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001891 int start, char *ps1,
1892 char *ps2, PyCompilerFlags *flags, int *errcode,
1893 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001894{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 mod_ty mod;
1896 PyCompilerFlags localflags;
1897 perrdetail err;
1898 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1901 &_PyParser_Grammar,
1902 start, ps1, ps2, &err, &iflags);
1903 if (flags == NULL) {
1904 localflags.cf_flags = 0;
1905 flags = &localflags;
1906 }
1907 if (n) {
1908 flags->cf_flags |= iflags & PyCF_MASK;
1909 mod = PyAST_FromNode(n, flags, filename, arena);
1910 PyNode_Free(n);
1911 return mod;
1912 }
1913 else {
1914 err_input(&err);
1915 if (errcode)
1916 *errcode = err.error;
1917 return NULL;
1918 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001919}
1920
Guido van Rossuma110aa61994-08-29 12:50:44 +00001921/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001922
Guido van Rossuma110aa61994-08-29 12:50:44 +00001923node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001924PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 perrdetail err;
1927 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1928 &_PyParser_Grammar,
1929 start, NULL, NULL, &err, flags);
1930 if (n == NULL)
1931 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001934}
1935
Guido van Rossuma110aa61994-08-29 12:50:44 +00001936/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001937
Guido van Rossuma110aa61994-08-29 12:50:44 +00001938node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001939PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001940{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 perrdetail err;
1942 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1943 start, &err, flags);
1944 if (n == NULL)
1945 err_input(&err);
1946 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00001947}
1948
1949node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001950PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 perrdetail err;
1954 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1955 &_PyParser_Grammar, start, &err, flags);
1956 if (n == NULL)
1957 err_input(&err);
1958 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00001959}
1960
1961node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001962PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001965}
1966
Guido van Rossum66ebd912003-04-17 16:02:26 +00001967/* May want to move a more generalized form of this to parsetok.c or
1968 even parser modules. */
1969
1970void
1971PyParser_SetError(perrdetail *err)
1972{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00001974}
1975
Guido van Rossuma110aa61994-08-29 12:50:44 +00001976/* Set the error appropriate to the given input error code (see errcode.h) */
1977
1978static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001979err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001980{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 PyObject *v, *w, *errtype, *errtext;
1982 PyObject *msg_obj = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001983 PyObject *filename;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 errtype = PyExc_SyntaxError;
1987 switch (err->error) {
1988 case E_ERROR:
1989 return;
1990 case E_SYNTAX:
1991 errtype = PyExc_IndentationError;
1992 if (err->expected == INDENT)
1993 msg = "expected an indented block";
1994 else if (err->token == INDENT)
1995 msg = "unexpected indent";
1996 else if (err->token == DEDENT)
1997 msg = "unexpected unindent";
1998 else {
1999 errtype = PyExc_SyntaxError;
2000 msg = "invalid syntax";
2001 }
2002 break;
2003 case E_TOKEN:
2004 msg = "invalid token";
2005 break;
2006 case E_EOFS:
2007 msg = "EOF while scanning triple-quoted string literal";
2008 break;
2009 case E_EOLS:
2010 msg = "EOL while scanning string literal";
2011 break;
2012 case E_INTR:
2013 if (!PyErr_Occurred())
2014 PyErr_SetNone(PyExc_KeyboardInterrupt);
2015 goto cleanup;
2016 case E_NOMEM:
2017 PyErr_NoMemory();
2018 goto cleanup;
2019 case E_EOF:
2020 msg = "unexpected EOF while parsing";
2021 break;
2022 case E_TABSPACE:
2023 errtype = PyExc_TabError;
2024 msg = "inconsistent use of tabs and spaces in indentation";
2025 break;
2026 case E_OVERFLOW:
2027 msg = "expression too long";
2028 break;
2029 case E_DEDENT:
2030 errtype = PyExc_IndentationError;
2031 msg = "unindent does not match any outer indentation level";
2032 break;
2033 case E_TOODEEP:
2034 errtype = PyExc_IndentationError;
2035 msg = "too many levels of indentation";
2036 break;
2037 case E_DECODE: {
2038 PyObject *type, *value, *tb;
2039 PyErr_Fetch(&type, &value, &tb);
2040 msg = "unknown decode error";
2041 if (value != NULL)
2042 msg_obj = PyObject_Str(value);
2043 Py_XDECREF(type);
2044 Py_XDECREF(value);
2045 Py_XDECREF(tb);
2046 break;
2047 }
2048 case E_LINECONT:
2049 msg = "unexpected character after line continuation character";
2050 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 case E_IDENTIFIER:
2053 msg = "invalid character in identifier";
2054 break;
2055 default:
2056 fprintf(stderr, "error=%d\n", err->error);
2057 msg = "unknown parsing error";
2058 break;
2059 }
2060 /* err->text may not be UTF-8 in case of decoding errors.
2061 Explicitly convert to an object. */
2062 if (!err->text) {
2063 errtext = Py_None;
2064 Py_INCREF(Py_None);
2065 } else {
2066 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2067 "replace");
2068 }
Victor Stinner2f2ed1f2010-10-16 13:42:53 +00002069 if (err->filename != NULL)
2070 filename = PyUnicode_DecodeFSDefault(err->filename);
2071 else {
2072 Py_INCREF(Py_None);
2073 filename = Py_None;
2074 }
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002075 if (filename != NULL)
2076 v = Py_BuildValue("(NiiN)", filename,
2077 err->lineno, err->offset, errtext);
2078 else
2079 v = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 if (v != NULL) {
2081 if (msg_obj)
2082 w = Py_BuildValue("(OO)", msg_obj, v);
2083 else
2084 w = Py_BuildValue("(sO)", msg, v);
2085 } else
2086 w = NULL;
2087 Py_XDECREF(v);
2088 PyErr_SetObject(errtype, w);
2089 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002090cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 Py_XDECREF(msg_obj);
2092 if (err->text != NULL) {
2093 PyObject_FREE(err->text);
2094 err->text = NULL;
2095 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002096}
2097
2098/* Print fatal error message and abort */
2099
2100void
Tim Peters7c321a82002-07-09 02:57:01 +00002101Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 fprintf(stderr, "Fatal Python error: %s\n", msg);
2104 fflush(stderr); /* it helps in Windows debug build */
2105 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002106 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002108#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 {
2110 size_t len = strlen(msg);
2111 WCHAR* buffer;
2112 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 /* Convert the message to wchar_t. This uses a simple one-to-one
2115 conversion, assuming that the this error message actually uses ASCII
2116 only. If this ceases to be true, we will have to convert. */
2117 buffer = alloca( (len+1) * (sizeof *buffer));
2118 for( i=0; i<=len; ++i)
2119 buffer[i] = msg[i];
2120 OutputDebugStringW(L"Fatal Python error: ");
2121 OutputDebugStringW(buffer);
2122 OutputDebugStringW(L"\n");
2123 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002124#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002126#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002127#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002129}
2130
2131/* Clean up and exit */
2132
Guido van Rossuma110aa61994-08-29 12:50:44 +00002133#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002134#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002135#endif
2136
Collin Winter670e6922007-03-21 02:57:17 +00002137static void (*pyexitfunc)(void) = NULL;
2138/* For the atexit module. */
2139void _Py_PyAtExit(void (*func)(void))
2140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002142}
2143
2144static void
2145call_py_exitfuncs(void)
2146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 if (pyexitfunc == NULL)
2148 return;
Collin Winter670e6922007-03-21 02:57:17 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 (*pyexitfunc)();
2151 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002152}
2153
Antoine Pitrou011bd622009-10-20 21:52:47 +00002154/* Wait until threading._shutdown completes, provided
2155 the threading module was imported in the first place.
2156 The shutdown routine will wait until all non-daemon
2157 "threading" threads have completed. */
2158static void
2159wait_for_thread_shutdown(void)
2160{
2161#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 PyObject *result;
2163 PyThreadState *tstate = PyThreadState_GET();
2164 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2165 "threading");
2166 if (threading == NULL) {
2167 /* threading not imported */
2168 PyErr_Clear();
2169 return;
2170 }
2171 result = PyObject_CallMethod(threading, "_shutdown", "");
2172 if (result == NULL) {
2173 PyErr_WriteUnraisable(threading);
2174 }
2175 else {
2176 Py_DECREF(result);
2177 }
2178 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002179#endif
2180}
2181
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002182#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002183static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002184static int nexitfuncs = 0;
2185
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002186int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 if (nexitfuncs >= NEXITFUNCS)
2189 return -1;
2190 exitfuncs[nexitfuncs++] = func;
2191 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002192}
2193
Guido van Rossumcc283f51997-08-05 02:22:03 +00002194static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002195call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 while (nexitfuncs > 0)
2198 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 fflush(stdout);
2201 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002202}
2203
2204void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002205Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002210}
2211
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002212static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002213initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002214{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002215#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002217#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002218#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002220#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002221#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002223#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002225}
2226
Guido van Rossum7433b121997-02-14 19:45:36 +00002227
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002228/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2229 *
2230 * All of the code in this function must only use async-signal-safe functions,
2231 * listed at `man 7 signal` or
2232 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2233 */
2234void
2235_Py_RestoreSignals(void)
2236{
2237#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002239#endif
2240#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002242#endif
2243#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002245#endif
2246}
2247
2248
Guido van Rossum7433b121997-02-14 19:45:36 +00002249/*
2250 * The file descriptor fd is considered ``interactive'' if either
2251 * a) isatty(fd) is TRUE, or
2252 * b) the -i flag was given, and the filename associated with
2253 * the descriptor is NULL or "<stdin>" or "???".
2254 */
2255int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002256Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 if (isatty((int)fileno(fp)))
2259 return 1;
2260 if (!Py_InteractiveFlag)
2261 return 0;
2262 return (filename == NULL) ||
2263 (strcmp(filename, "<stdin>") == 0) ||
2264 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002265}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002266
2267
Tim Petersd08e3822003-04-17 15:24:21 +00002268#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002269#if defined(WIN32) && defined(_MSC_VER)
2270
2271/* Stack checking for Microsoft C */
2272
2273#include <malloc.h>
2274#include <excpt.h>
2275
Fred Drakee8de31c2000-08-31 05:38:39 +00002276/*
2277 * Return non-zero when we run out of memory on the stack; zero otherwise.
2278 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002279int
Fred Drake399739f2000-08-31 05:52:44 +00002280PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 __try {
2283 /* alloca throws a stack overflow exception if there's
2284 not enough space left on the stack */
2285 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2286 return 0;
2287 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2288 EXCEPTION_EXECUTE_HANDLER :
2289 EXCEPTION_CONTINUE_SEARCH) {
2290 int errcode = _resetstkoflw();
2291 if (errcode == 0)
2292 {
2293 Py_FatalError("Could not reset the stack!");
2294 }
2295 }
2296 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002297}
2298
2299#endif /* WIN32 && _MSC_VER */
2300
2301/* Alternate implementations can be added here... */
2302
2303#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002304
2305
2306/* Wrappers around sigaction() or signal(). */
2307
2308PyOS_sighandler_t
2309PyOS_getsig(int sig)
2310{
2311#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 struct sigaction context;
2313 if (sigaction(sig, NULL, &context) == -1)
2314 return SIG_ERR;
2315 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002316#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002318/* Special signal handling for the secure CRT in Visual Studio 2005 */
2319#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 switch (sig) {
2321 /* Only these signals are valid */
2322 case SIGINT:
2323 case SIGILL:
2324 case SIGFPE:
2325 case SIGSEGV:
2326 case SIGTERM:
2327 case SIGBREAK:
2328 case SIGABRT:
2329 break;
2330 /* Don't call signal() with other values or it will assert */
2331 default:
2332 return SIG_ERR;
2333 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002334#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 handler = signal(sig, SIG_IGN);
2336 if (handler != SIG_ERR)
2337 signal(sig, handler);
2338 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002339#endif
2340}
2341
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002342/*
2343 * All of the code in this function must only use async-signal-safe functions,
2344 * listed at `man 7 signal` or
2345 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2346 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002347PyOS_sighandler_t
2348PyOS_setsig(int sig, PyOS_sighandler_t handler)
2349{
2350#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 /* Some code in Modules/signalmodule.c depends on sigaction() being
2352 * used here if HAVE_SIGACTION is defined. Fix that if this code
2353 * changes to invalidate that assumption.
2354 */
2355 struct sigaction context, ocontext;
2356 context.sa_handler = handler;
2357 sigemptyset(&context.sa_mask);
2358 context.sa_flags = 0;
2359 if (sigaction(sig, &context, &ocontext) == -1)
2360 return SIG_ERR;
2361 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002362#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 PyOS_sighandler_t oldhandler;
2364 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002365#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002367#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002369#endif
2370}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002371
2372/* Deprecated C API functions still provided for binary compatiblity */
2373
2374#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002375PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002376PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002379}
2380
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002381#undef PyParser_SimpleParseString
2382PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002383PyParser_SimpleParseString(const char *str, int start)
2384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002386}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002387
2388#undef PyRun_AnyFile
2389PyAPI_FUNC(int)
2390PyRun_AnyFile(FILE *fp, const char *name)
2391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002393}
2394
2395#undef PyRun_AnyFileEx
2396PyAPI_FUNC(int)
2397PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002400}
2401
2402#undef PyRun_AnyFileFlags
2403PyAPI_FUNC(int)
2404PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002407}
2408
2409#undef PyRun_File
2410PyAPI_FUNC(PyObject *)
2411PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002414}
2415
2416#undef PyRun_FileEx
2417PyAPI_FUNC(PyObject *)
2418PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002421}
2422
2423#undef PyRun_FileFlags
2424PyAPI_FUNC(PyObject *)
2425PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002429}
2430
2431#undef PyRun_SimpleFile
2432PyAPI_FUNC(int)
2433PyRun_SimpleFile(FILE *f, const char *p)
2434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002436}
2437
2438#undef PyRun_SimpleFileEx
2439PyAPI_FUNC(int)
2440PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002443}
2444
2445
2446#undef PyRun_String
2447PyAPI_FUNC(PyObject *)
2448PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002451}
2452
2453#undef PyRun_SimpleString
2454PyAPI_FUNC(int)
2455PyRun_SimpleString(const char *s)
2456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002458}
2459
2460#undef Py_CompileString
2461PyAPI_FUNC(PyObject *)
2462Py_CompileString(const char *str, const char *p, int s)
2463{
Georg Brandl8334fd92010-12-04 10:26:46 +00002464 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2465}
2466
2467#undef Py_CompileStringFlags
2468PyAPI_FUNC(PyObject *)
2469Py_CompileStringFlags(const char *str, const char *p, int s,
2470 PyCompilerFlags *flags)
2471{
2472 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002473}
2474
2475#undef PyRun_InteractiveOne
2476PyAPI_FUNC(int)
2477PyRun_InteractiveOne(FILE *f, const char *p)
2478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002480}
2481
2482#undef PyRun_InteractiveLoop
2483PyAPI_FUNC(int)
2484PyRun_InteractiveLoop(FILE *f, const char *p)
2485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002487}
2488
2489#ifdef __cplusplus
2490}
2491#endif