blob: e7a051288df2fbe2f7e0d7c6ed11ae2f9e32bfaf [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"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000014#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000015#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000016#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000018#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000019#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000020#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000021
Thomas Wouters0e3f5912006-08-11 14:57:12 +000022#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000023#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000024#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000025
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000026#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000027#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000028#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000029
Martin v. Löwis73d538b2003-03-05 15:13:47 +000030#ifdef HAVE_LANGINFO_H
31#include <locale.h>
32#include <langinfo.h>
33#endif
34
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000035#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#undef BYTE
37#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000038#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000039#endif
40
Neal Norwitz4281cef2006-03-04 19:58:13 +000041#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000042#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000043#else /* Py_REF_DEBUG */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000044#define PRINT_TOTAL_REFS() fprintf(stderr, \
45 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
46 _Py_GetRefTotal())
47#endif
48
49#ifdef __cplusplus
50extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000051#endif
52
Martin v. Löwis790465f2008-04-05 20:41:37 +000053extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000054
Guido van Rossum82598051997-03-05 00:20:32 +000055extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000056
Guido van Rossumb73cc041993-11-01 16:28:59 +000057/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000058static void initmain(void);
59static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000060static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000061static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000062static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Neal Norwitzadb69fc2005-12-17 20:54:49 +000063 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000064static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000065 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000066static void err_input(perrdetail *);
67static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000068static void call_py_exitfuncs(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000069static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000070extern void _PyUnicode_Init(void);
71extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000072extern int _PyLong_Init(void);
73extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000074
Mark Hammond8d98d2c2003-04-19 15:41:53 +000075#ifdef WITH_THREAD
76extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
77extern void _PyGILState_Fini(void);
78#endif /* WITH_THREAD */
79
Guido van Rossum82598051997-03-05 00:20:32 +000080int Py_DebugFlag; /* Needed by parser.c */
81int Py_VerboseFlag; /* Needed by import.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{
Christian Heimes33fe8092008-04-13 13:53:33 +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{
108 return initialized;
109}
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{
126 int env = atoi(envs);
127 if (flag < env)
128 flag = env;
129 if (flag < 1)
130 flag = 1;
131 return flag;
132}
133
Christian Heimes5833a2f2008-10-30 21:40:04 +0000134#if defined(HAVE_LANGINFO_H) && defined(CODESET)
135static char*
136get_codeset(void)
137{
138 char* codeset;
139 PyObject *codec, *name;
140
141 codeset = nl_langinfo(CODESET);
142 if (!codeset || codeset[0] == '\0')
143 return NULL;
144
145 codec = _PyCodec_Lookup(codeset);
146 if (!codec)
147 goto error;
148
149 name = PyObject_GetAttrString(codec, "name");
150 Py_CLEAR(codec);
151 if (!name)
152 goto error;
153
154 codeset = strdup(_PyUnicode_AsString(name));
155 Py_DECREF(name);
156 return codeset;
157
158error:
159 Py_XDECREF(codec);
160 PyErr_Clear();
161 return NULL;
162}
163#endif
164
Guido van Rossuma027efa1997-05-05 20:56:21 +0000165void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000166Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000167{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000168 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000169 PyThreadState *tstate;
Guido van Rossum826d8972007-10-30 18:34:07 +0000170 PyObject *bimod, *sysmod, *pstderr;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000171 char *p;
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000172#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000173 char *codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000174#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +0000175 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000176
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000177 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000178 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000179 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000180
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000181#ifdef HAVE_SETLOCALE
182 /* Set up the LC_CTYPE locale, so we can obtain
183 the locale's charset without having to switch
184 locales. */
185 setlocale(LC_CTYPE, "");
186#endif
187
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000188 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000189 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000190 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000191 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000192 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000193 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Christian Heimes790c8232008-01-07 21:14:23 +0000194 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
195 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000196
Guido van Rossuma027efa1997-05-05 20:56:21 +0000197 interp = PyInterpreterState_New();
198 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000199 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000200
Guido van Rossuma027efa1997-05-05 20:56:21 +0000201 tstate = PyThreadState_New(interp);
202 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000203 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000204 (void) PyThreadState_Swap(tstate);
205
Guido van Rossum70d893a2001-08-16 08:21:42 +0000206 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000207
Neal Norwitzb2501f42002-12-31 03:42:13 +0000208 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000209 Py_FatalError("Py_Initialize: can't init frames");
210
Guido van Rossumddefaf32007-01-14 03:31:43 +0000211 if (!_PyLong_Init())
212 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000213
Christian Heimes9c4756e2008-05-26 13:22:05 +0000214 if (!PyByteArray_Init())
Benjamin Petersoncc3b8d62009-05-10 23:43:14 +0000215 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000216
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000217 _PyFloat_Init();
218
Guido van Rossum25ce5661997-08-02 03:10:38 +0000219 interp->modules = PyDict_New();
220 if (interp->modules == NULL)
221 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222 interp->modules_reloading = PyDict_New();
223 if (interp->modules_reloading == NULL)
224 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000225
Guido van Rossumc94044c2000-03-10 23:03:54 +0000226 /* Init Unicode implementation; relies on the codec registry */
227 _PyUnicode_Init();
228
Barry Warsawf242aa02000-05-25 23:09:49 +0000229 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000230 if (bimod == NULL)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000231 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Martin v. Löwis1a214512008-06-11 05:26:20 +0000232 _PyImport_FixupExtension(bimod, "builtins", "builtins");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000233 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000234 if (interp->builtins == NULL)
235 Py_FatalError("Py_Initialize: can't initialize builtins dict");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000236 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000237
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000238 /* initialize builtin exceptions */
239 _PyExc_Init();
240
Guido van Rossum25ce5661997-08-02 03:10:38 +0000241 sysmod = _PySys_Init();
242 if (sysmod == NULL)
243 Py_FatalError("Py_Initialize: can't initialize sys");
244 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000245 if (interp->sysdict == NULL)
246 Py_FatalError("Py_Initialize: can't initialize sys dict");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000247 Py_INCREF(interp->sysdict);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000248 _PyImport_FixupExtension(sysmod, "sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000249 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000250 PyDict_SetItemString(interp->sysdict, "modules",
251 interp->modules);
252
Guido van Rossum826d8972007-10-30 18:34:07 +0000253 /* Set up a preliminary stderr printer until we have enough
254 infrastructure for the io module in place. */
255 pstderr = PyFile_NewStdPrinter(fileno(stderr));
256 if (pstderr == NULL)
257 Py_FatalError("Py_Initialize: can't set preliminary stderr");
258 PySys_SetObject("stderr", pstderr);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000259 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000260
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000261 _PyImport_Init();
262
Just van Rossum52e14d62002-12-30 22:08:05 +0000263 _PyImportHooks_Init();
264
Martin v. Löwis011e8422009-05-05 04:43:17 +0000265#if defined(HAVE_LANGINFO_H) && defined(CODESET)
266 /* On Unix, set the file system encoding according to the
267 user's preference, if the CODESET names a well-known
268 Python codec, and Py_FileSystemDefaultEncoding isn't
269 initialized by other means. Also set the encoding of
270 stdin and stdout if these are terminals. */
271
272 codeset = get_codeset();
273 if (codeset) {
274 if (!Py_FileSystemDefaultEncoding)
275 Py_FileSystemDefaultEncoding = codeset;
276 else
277 free(codeset);
278 }
279#endif
280
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000281 if (install_sigs)
282 initsigs(); /* Signal handling stuff, including initintr() */
Christian Heimes33fe8092008-04-13 13:53:33 +0000283
Georg Brandl86b2fb92008-07-16 03:43:04 +0000284 /* Initialize warnings. */
285 _PyWarnings_Init();
286 if (PySys_HasWarnOptions()) {
287 PyObject *warnings_module = PyImport_ImportModule("warnings");
288 if (!warnings_module)
289 PyErr_Clear();
290 Py_XDECREF(warnings_module);
291 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000292
293 initmain(); /* Module __main__ */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000294 if (initstdio() < 0)
295 Py_FatalError(
296 "Py_Initialize: can't initialize sys standard streams");
Benjamin Peterson791dc2f2008-09-05 23:27:15 +0000297 if (!Py_NoSiteFlag)
298 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000299
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000300 /* auto-thread-state API, if available */
301#ifdef WITH_THREAD
302 _PyGILState_Init(interp, tstate);
303#endif /* WITH_THREAD */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000304}
305
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000306void
307Py_Initialize(void)
308{
309 Py_InitializeEx(1);
310}
311
312
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000313#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000314extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000315#endif
316
Guido van Rossume8432ac2007-07-09 15:04:50 +0000317/* Flush stdout and stderr */
318
Neal Norwitz2bad9702007-08-27 06:19:22 +0000319static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000320flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000321{
322 PyObject *fout = PySys_GetObject("stdout");
323 PyObject *ferr = PySys_GetObject("stderr");
324 PyObject *tmp;
325
Christian Heimes2be03732007-11-15 02:26:46 +0000326 if (fout != NULL && fout != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000327 tmp = PyObject_CallMethod(fout, "flush", "");
328 if (tmp == NULL)
329 PyErr_Clear();
330 else
331 Py_DECREF(tmp);
332 }
333
Christian Heimes2be03732007-11-15 02:26:46 +0000334 if (ferr != NULL || ferr != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000335 tmp = PyObject_CallMethod(ferr, "flush", "");
336 if (tmp == NULL)
337 PyErr_Clear();
338 else
339 Py_DECREF(tmp);
340 }
341}
342
Guido van Rossum25ce5661997-08-02 03:10:38 +0000343/* Undo the effect of Py_Initialize().
344
345 Beware: if multiple interpreter and/or thread states exist, these
346 are not wiped out; only the current thread and interpreter state
347 are deleted. But since everything else is deleted, those other
348 interpreter and thread states should no longer be used.
349
350 (XXX We should do better, e.g. wipe out all interpreters and
351 threads.)
352
353 Locking: as above.
354
355*/
356
357void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000358Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000359{
360 PyInterpreterState *interp;
361 PyThreadState *tstate;
362
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000363 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000364 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000365
Tim Peters384fd102001-01-21 03:40:37 +0000366 /* The interpreter is still entirely intact at this point, and the
367 * exit funcs may be relying on that. In particular, if some thread
368 * or exit func is still waiting to do an import, the import machinery
369 * expects Py_IsInitialized() to return true. So don't say the
370 * interpreter is uninitialized until after the exit funcs have run.
371 * Note that Threading.py uses an exit func to do a join on all the
372 * threads created thru it, so this also protects pending imports in
373 * the threads created via Threading.
374 */
Collin Winter670e6922007-03-21 02:57:17 +0000375 call_py_exitfuncs();
Tim Peters384fd102001-01-21 03:40:37 +0000376 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000377
Guido van Rossume8432ac2007-07-09 15:04:50 +0000378 /* Flush stdout+stderr */
379 flush_std_files();
380
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000381 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000382 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000383 interp = tstate->interp;
384
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000385 /* Disable signal handling */
386 PyOS_FiniInterrupts();
387
Christian Heimes26855632008-01-27 23:50:43 +0000388 /* Clear type lookup cache */
389 PyType_ClearCache();
390
Guido van Rossume13ddc92003-04-17 17:29:22 +0000391 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000392 * before all modules are destroyed.
393 * XXX If a __del__ or weakref callback is triggered here, and tries to
394 * XXX import a module, bad things can happen, because Python no
395 * XXX longer believes it's initialized.
396 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
397 * XXX is easy to provoke that way. I've also seen, e.g.,
398 * XXX Exception exceptions.ImportError: 'No module named sha'
399 * XXX in <function callback at 0x008F5718> ignored
400 * XXX but I'm unclear on exactly how that one happens. In any case,
401 * XXX I haven't seen a real-life report of either of these.
Neal Norwitz9589ee22006-03-04 19:01:22 +0000402 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000403 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000404#ifdef COUNT_ALLOCS
405 /* With COUNT_ALLOCS, it helps to run GC multiple times:
406 each collection might release some types from the type
407 list, so they become garbage. */
408 while (PyGC_Collect() > 0)
409 /* nothing */;
410#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000411
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000412 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000413 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000414
Guido van Rossume8432ac2007-07-09 15:04:50 +0000415 /* Flush stdout+stderr (again, in case more was printed) */
416 flush_std_files();
417
Guido van Rossume13ddc92003-04-17 17:29:22 +0000418 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000419 * new-style class definitions, for example.
420 * XXX This is disabled because it caused too many problems. If
421 * XXX a __del__ or weakref callback triggers here, Python code has
422 * XXX a hard time running, because even the sys module has been
423 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
424 * XXX One symptom is a sequence of information-free messages
425 * XXX coming from threads (if a __del__ or callback is invoked,
426 * XXX other threads can execute too, and any exception they encounter
427 * XXX triggers a comedy of errors as subsystem after subsystem
428 * XXX fails to find what it *expects* to find in sys to help report
429 * XXX the exception and consequent unexpected failures). I've also
430 * XXX seen segfaults then, after adding print statements to the
431 * XXX Python code getting called.
432 */
433#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000434 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000435#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000436
Guido van Rossum1707aad1997-12-08 23:43:45 +0000437 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
438 _PyImport_Fini();
439
440 /* Debugging stuff */
441#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000442 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000443#endif
444
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000445 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000446
Tim Peters9cf25ce2003-04-17 15:21:01 +0000447#ifdef Py_TRACE_REFS
448 /* Display all objects still alive -- this can invoke arbitrary
449 * __repr__ overrides, so requires a mostly-intact interpreter.
450 * Alas, a lot of stuff may still be alive now that will be cleaned
451 * up later.
452 */
Tim Peters269b2a62003-04-17 19:52:29 +0000453 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000454 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000455#endif /* Py_TRACE_REFS */
456
Guido van Rossumd922fa42003-04-15 14:10:09 +0000457 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000458 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000459
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000460 /* Now we decref the exception classes. After this point nothing
461 can raise an exception. That's okay, because each Fini() method
462 below has been checked to make sure no exceptions are ever
463 raised.
464 */
465
466 _PyExc_Fini();
467
Christian Heimes7d2ff882007-11-30 14:35:04 +0000468 /* Cleanup auto-thread-state */
469#ifdef WITH_THREAD
470 _PyGILState_Fini();
471#endif /* WITH_THREAD */
472
Guido van Rossumd922fa42003-04-15 14:10:09 +0000473 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000474 PyThreadState_Swap(NULL);
475 PyInterpreterState_Delete(interp);
476
Guido van Rossumd922fa42003-04-15 14:10:09 +0000477 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000478 PyMethod_Fini();
479 PyFrame_Fini();
480 PyCFunction_Fini();
481 PyTuple_Fini();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000482 PyList_Fini();
Raymond Hettingerd7946662005-08-01 21:39:29 +0000483 PySet_Fini();
Christian Heimes72b710a2008-05-26 13:28:38 +0000484 PyBytes_Fini();
Christian Heimes9c4756e2008-05-26 13:22:05 +0000485 PyByteArray_Fini();
Guido van Rossumddefaf32007-01-14 03:31:43 +0000486 PyLong_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000487 PyFloat_Fini();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000488 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000489
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000490 /* Cleanup Unicode implementation */
491 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000492
Christian Heimesc8967002007-11-30 10:18:26 +0000493 /* reset file system default encoding */
494 if (!Py_HasFileSystemDefaultEncoding) {
495 free((char*)Py_FileSystemDefaultEncoding);
Trent Nelson39e307e2008-03-19 06:45:48 +0000496 Py_FileSystemDefaultEncoding = NULL;
Christian Heimesc8967002007-11-30 10:18:26 +0000497 }
498
Guido van Rossumcc283f51997-08-05 02:22:03 +0000499 /* XXX Still allocated:
500 - various static ad-hoc pointers to interned strings
501 - int and float free list blocks
502 - whatever various modules and libraries allocate
503 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000504
505 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000506
Tim Peters269b2a62003-04-17 19:52:29 +0000507#ifdef Py_TRACE_REFS
508 /* Display addresses (& refcnts) of all objects still alive.
509 * An address can be used to find the repr of the object, printed
510 * above by _Py_PrintReferences.
511 */
512 if (Py_GETENV("PYTHONDUMPREFS"))
513 _Py_PrintReferenceAddresses(stderr);
514#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000515#ifdef PYMALLOC_DEBUG
516 if (Py_GETENV("PYTHONMALLOCSTATS"))
517 _PyObject_DebugMallocStats();
518#endif
519
Guido van Rossumcc283f51997-08-05 02:22:03 +0000520 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000521}
522
523/* Create and initialize a new interpreter and thread, and return the
524 new thread. This requires that Py_Initialize() has been called
525 first.
526
527 Unsuccessful initialization yields a NULL pointer. Note that *no*
528 exception information is available even in this case -- the
529 exception information is held in the thread, and there is no
530 thread.
531
532 Locking: as above.
533
534*/
535
536PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000537Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000538{
539 PyInterpreterState *interp;
540 PyThreadState *tstate, *save_tstate;
541 PyObject *bimod, *sysmod;
542
543 if (!initialized)
544 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
545
546 interp = PyInterpreterState_New();
547 if (interp == NULL)
548 return NULL;
549
550 tstate = PyThreadState_New(interp);
551 if (tstate == NULL) {
552 PyInterpreterState_Delete(interp);
553 return NULL;
554 }
555
556 save_tstate = PyThreadState_Swap(tstate);
557
558 /* XXX The following is lax in error checking */
559
560 interp->modules = PyDict_New();
Guido van Rossumd8faa362007-04-27 19:54:29 +0000561 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562
Georg Brandl1a3284e2007-12-02 09:40:06 +0000563 bimod = _PyImport_FindExtension("builtins", "builtins");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000565 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000566 if (interp->builtins == NULL)
567 goto handle_error;
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000568 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000570
571 /* initialize builtin exceptions */
572 _PyExc_Init();
573
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574 sysmod = _PyImport_FindExtension("sys", "sys");
575 if (bimod != NULL && sysmod != NULL) {
Christian Heimes6a27efa2008-10-30 21:48:26 +0000576 PyObject *pstderr;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000577 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000578 if (interp->sysdict == NULL)
579 goto handle_error;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000580 Py_INCREF(interp->sysdict);
581 PySys_SetPath(Py_GetPath());
582 PyDict_SetItemString(interp->sysdict, "modules",
583 interp->modules);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000584 /* Set up a preliminary stderr printer until we have enough
585 infrastructure for the io module in place. */
586 pstderr = PyFile_NewStdPrinter(fileno(stderr));
587 if (pstderr == NULL)
588 Py_FatalError("Py_Initialize: can't set preliminary stderr");
589 PySys_SetObject("stderr", pstderr);
590 PySys_SetObject("__stderr__", pstderr);
591
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000592 _PyImportHooks_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000593 if (initstdio() < 0)
594 Py_FatalError(
595 "Py_Initialize: can't initialize sys standard streams");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000596 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000597 if (!Py_NoSiteFlag)
598 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000599 }
600
601 if (!PyErr_Occurred())
602 return tstate;
603
Thomas Wouters89f507f2006-12-13 04:49:30 +0000604handle_error:
Guido van Rossum25ce5661997-08-02 03:10:38 +0000605 /* Oops, it didn't work. Undo it all. */
606
607 PyErr_Print();
608 PyThreadState_Clear(tstate);
609 PyThreadState_Swap(save_tstate);
610 PyThreadState_Delete(tstate);
611 PyInterpreterState_Delete(interp);
612
613 return NULL;
614}
615
616/* Delete an interpreter and its last thread. This requires that the
617 given thread state is current, that the thread has no remaining
618 frames, and that it is its interpreter's only remaining thread.
619 It is a fatal error to violate these constraints.
620
621 (Py_Finalize() doesn't have these constraints -- it zaps
622 everything, regardless.)
623
624 Locking: as above.
625
626*/
627
628void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000629Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000630{
631 PyInterpreterState *interp = tstate->interp;
632
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000633 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000634 Py_FatalError("Py_EndInterpreter: thread is not current");
635 if (tstate->frame != NULL)
636 Py_FatalError("Py_EndInterpreter: thread still has a frame");
637 if (tstate != interp->tstate_head || tstate->next != NULL)
638 Py_FatalError("Py_EndInterpreter: not the last thread");
639
640 PyImport_Cleanup();
641 PyInterpreterState_Clear(interp);
642 PyThreadState_Swap(NULL);
643 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000644}
645
Martin v. Löwis790465f2008-04-05 20:41:37 +0000646static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000647
648void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000649Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000650{
651 if (pn && *pn)
652 progname = pn;
653}
654
Martin v. Löwis790465f2008-04-05 20:41:37 +0000655wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000656Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000657{
658 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000659}
660
Martin v. Löwis790465f2008-04-05 20:41:37 +0000661static wchar_t *default_home = NULL;
662static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000663
664void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000665Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000666{
667 default_home = home;
668}
669
Martin v. Löwis790465f2008-04-05 20:41:37 +0000670wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000671Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000672{
Martin v. Löwis790465f2008-04-05 20:41:37 +0000673 wchar_t *home = default_home;
674 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
675 char* chome = Py_GETENV("PYTHONHOME");
676 if (chome) {
677 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
678 if (r != (size_t)-1 && r <= PATH_MAX)
679 home = env_home;
680 }
681
682 }
Guido van Rossuma61691e1998-02-06 22:27:24 +0000683 return home;
684}
685
Guido van Rossum6135a871995-01-09 17:53:26 +0000686/* Create __main__ module */
687
688static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000689initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000690{
Guido van Rossum82598051997-03-05 00:20:32 +0000691 PyObject *m, *d;
692 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000693 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000694 Py_FatalError("can't create __main__ module");
695 d = PyModule_GetDict(m);
696 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Georg Brandl1a3284e2007-12-02 09:40:06 +0000697 PyObject *bimod = PyImport_ImportModule("builtins");
Guido van Rossum858cb731997-11-19 16:15:37 +0000698 if (bimod == NULL ||
699 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000700 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000701 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000702 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000703}
704
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000705/* Import the site module (not into __main__ though) */
706
707static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000708initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000709{
710 PyObject *m, *f;
711 m = PyImport_ImportModule("site");
712 if (m == NULL) {
713 f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +0000714 if (f == NULL || f == Py_None)
715 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000716 if (Py_VerboseFlag) {
717 PyFile_WriteString(
718 "'import site' failed; traceback:\n", f);
719 PyErr_Print();
720 }
721 else {
722 PyFile_WriteString(
723 "'import site' failed; use -v for traceback\n", f);
724 PyErr_Clear();
725 }
726 }
727 else {
728 Py_DECREF(m);
729 }
730}
731
Antoine Pitrou05608432009-01-09 18:53:14 +0000732static PyObject*
733create_stdio(PyObject* io,
734 int fd, int write_mode, char* name,
735 char* encoding, char* errors)
736{
Antoine Pitrou91696412009-01-09 22:12:30 +0000737 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
Antoine Pitrou05608432009-01-09 18:53:14 +0000738 const char* mode;
Antoine Pitrou91696412009-01-09 22:12:30 +0000739 PyObject *line_buffering;
740 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000741
Antoine Pitrou27fe9fc2009-01-26 21:48:00 +0000742 /* stdin is always opened in buffered mode, first because it shouldn't
743 make a difference in common use cases, second because TextIOWrapper
744 depends on the presence of a read1() method which only exists on
745 buffered streams.
746 */
747 if (Py_UnbufferedStdioFlag && write_mode)
Antoine Pitrou05608432009-01-09 18:53:14 +0000748 buffering = 0;
749 else
750 buffering = -1;
751 if (write_mode)
752 mode = "wb";
753 else
754 mode = "rb";
755 buf = PyObject_CallMethod(io, "open", "isiOOOi",
756 fd, mode, buffering,
757 Py_None, Py_None, Py_None, 0);
758 if (buf == NULL)
759 goto error;
760
Antoine Pitrou27fe9fc2009-01-26 21:48:00 +0000761 if (buffering) {
Antoine Pitrou05608432009-01-09 18:53:14 +0000762 raw = PyObject_GetAttrString(buf, "raw");
763 if (raw == NULL)
764 goto error;
765 }
766 else {
767 raw = buf;
768 Py_INCREF(raw);
769 }
770
771 text = PyUnicode_FromString(name);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000772 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
Antoine Pitrou05608432009-01-09 18:53:14 +0000773 goto error;
Antoine Pitrou91696412009-01-09 22:12:30 +0000774 res = PyObject_CallMethod(raw, "isatty", "");
775 if (res == NULL)
776 goto error;
777 isatty = PyObject_IsTrue(res);
778 Py_DECREF(res);
779 if (isatty == -1)
780 goto error;
781 if (isatty || Py_UnbufferedStdioFlag)
Antoine Pitrou05608432009-01-09 18:53:14 +0000782 line_buffering = Py_True;
783 else
784 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000785
786 Py_CLEAR(raw);
787 Py_CLEAR(text);
788
Antoine Pitrou05608432009-01-09 18:53:14 +0000789 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
790 buf, encoding, errors,
791 "\n", line_buffering);
792 Py_CLEAR(buf);
793 if (stream == NULL)
794 goto error;
795
796 if (write_mode)
797 mode = "w";
798 else
799 mode = "r";
800 text = PyUnicode_FromString(mode);
801 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
802 goto error;
803 Py_CLEAR(text);
804 return stream;
805
806error:
807 Py_XDECREF(buf);
808 Py_XDECREF(stream);
809 Py_XDECREF(text);
810 Py_XDECREF(raw);
811 return NULL;
812}
813
Georg Brandl1a3284e2007-12-02 09:40:06 +0000814/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000815static int
816initstdio(void)
817{
818 PyObject *iomod = NULL, *wrapper;
819 PyObject *bimod = NULL;
820 PyObject *m;
821 PyObject *std = NULL;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000822 int status = 0, fd;
Trent Nelson39e307e2008-03-19 06:45:48 +0000823 PyObject * encoding_attr;
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +0000824 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000825
826 /* Hack to avoid a nasty recursion issue when Python is invoked
827 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
828 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
829 goto error;
830 }
831 Py_DECREF(m);
832
833 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
834 goto error;
835 }
836 Py_DECREF(m);
837
Georg Brandl1a3284e2007-12-02 09:40:06 +0000838 if (!(bimod = PyImport_ImportModule("builtins"))) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000839 goto error;
840 }
841
842 if (!(iomod = PyImport_ImportModule("io"))) {
843 goto error;
844 }
845 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
846 goto error;
847 }
848
Georg Brandl1a3284e2007-12-02 09:40:06 +0000849 /* Set builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000850 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
851 goto error;
852 }
853
Martin v. Löwis0f599892008-06-02 11:13:03 +0000854 encoding = Py_GETENV("PYTHONIOENCODING");
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000855 errors = NULL;
Martin v. Löwis0f599892008-06-02 11:13:03 +0000856 if (encoding) {
857 encoding = strdup(encoding);
858 errors = strchr(encoding, ':');
859 if (errors) {
860 *errors = '\0';
861 errors++;
862 }
863 }
864
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000865 /* Set sys.stdin */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000866 fd = fileno(stdin);
867 /* Under some conditions stdin, stdout and stderr may not be connected
868 * and fileno() may point to an invalid file descriptor. For example
869 * GUI apps don't have valid standard streams by default.
870 */
871 if (fd < 0) {
872#ifdef MS_WINDOWS
873 std = Py_None;
874 Py_INCREF(std);
875#else
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000876 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000877#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000878 }
Christian Heimes58cb1b82007-11-13 02:19:40 +0000879 else {
Antoine Pitrou05608432009-01-09 18:53:14 +0000880 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
881 if (std == NULL)
Christian Heimes58cb1b82007-11-13 02:19:40 +0000882 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000883 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000884 PySys_SetObject("__stdin__", std);
885 PySys_SetObject("stdin", std);
886 Py_DECREF(std);
887
888 /* Set sys.stdout */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000889 fd = fileno(stdout);
890 if (fd < 0) {
891#ifdef MS_WINDOWS
892 std = Py_None;
893 Py_INCREF(std);
894#else
895 goto error;
896#endif
897 }
898 else {
Antoine Pitrou05608432009-01-09 18:53:14 +0000899 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
900 if (std == NULL)
Christian Heimes58cb1b82007-11-13 02:19:40 +0000901 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000902 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000903 PySys_SetObject("__stdout__", std);
904 PySys_SetObject("stdout", std);
905 Py_DECREF(std);
906
Guido van Rossum98297ee2007-11-06 21:34:58 +0000907#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000908 /* Set sys.stderr, replaces the preliminary stderr */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000909 fd = fileno(stderr);
910 if (fd < 0) {
911#ifdef MS_WINDOWS
912 std = Py_None;
913 Py_INCREF(std);
914#else
915 goto error;
916#endif
917 }
918 else {
Antoine Pitrou05608432009-01-09 18:53:14 +0000919 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
920 if (std == NULL)
Christian Heimes58cb1b82007-11-13 02:19:40 +0000921 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000922 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000923
924 /* Same as hack above, pre-import stderr's codec to avoid recursion
925 when import.c tries to write to stderr in verbose mode. */
926 encoding_attr = PyObject_GetAttrString(std, "encoding");
927 if (encoding_attr != NULL) {
928 const char * encoding;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000929 encoding = _PyUnicode_AsString(encoding_attr);
Trent Nelson39e307e2008-03-19 06:45:48 +0000930 if (encoding != NULL) {
931 _PyCodec_Lookup(encoding);
932 }
933 }
934 PyErr_Clear(); /* Not a fatal error if codec isn't available */
935
Christian Heimesdb233082007-11-13 02:34:21 +0000936 PySys_SetObject("__stderr__", std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000937 PySys_SetObject("stderr", std);
938 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000939#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000940
Christian Heimes58cb1b82007-11-13 02:19:40 +0000941 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000942 error:
Christian Heimesdb233082007-11-13 02:34:21 +0000943 status = -1;
944 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000945
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000946 if (encoding)
947 free(encoding);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000948 Py_XDECREF(bimod);
949 Py_XDECREF(iomod);
950 return status;
951}
952
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000953/* Parse input from a file and execute it */
954
955int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000956PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000957 PyCompilerFlags *flags)
958{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000959 if (filename == NULL)
960 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000961 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000962 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000963 if (closeit)
964 fclose(fp);
965 return err;
966 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000967 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000968 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000969}
970
971int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000972PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000973{
Guido van Rossum82598051997-03-05 00:20:32 +0000974 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000975 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000976 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000977
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000978 if (flags == NULL) {
979 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000980 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000981 }
Guido van Rossum82598051997-03-05 00:20:32 +0000982 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000983 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000984 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
Guido van Rossum82598051997-03-05 00:20:32 +0000985 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000986 }
Guido van Rossum82598051997-03-05 00:20:32 +0000987 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000988 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000989 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
Guido van Rossum82598051997-03-05 00:20:32 +0000990 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000991 }
992 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000993 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000994 PRINT_TOTAL_REFS();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000995 if (ret == E_EOF)
996 return 0;
997 /*
998 if (ret == E_NOMEM)
999 return -1;
1000 */
1001 }
1002}
1003
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001004/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001005static int PARSER_FLAGS(PyCompilerFlags *flags)
1006{
1007 int parser_flags = 0;
1008 if (!flags)
1009 return 0;
1010 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1011 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1012 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1013 parser_flags |= PyPARSE_IGNORE_COOKIE;
Brett Cannone3944a52009-04-01 05:08:41 +00001014 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1015 parser_flags |= PyPARSE_BARRY_AS_BDFL;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001016 return parser_flags;
1017}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001018
Thomas Wouters89f507f2006-12-13 04:49:30 +00001019#if 0
1020/* Keep an example of flags with future keyword support. */
1021#define PARSER_FLAGS(flags) \
1022 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1023 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1024 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1025 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
1026#endif
1027
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001028int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001029PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001030{
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001031 PyObject *m, *d, *v, *w, *oenc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001032 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001033 PyArena *arena;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001034 char *ps1 = "", *ps2 = "", *enc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001035 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001036
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001037 if (fp == stdin) {
1038 /* Fetch encoding from sys.stdin */
1039 v = PySys_GetObject("stdin");
Christian Heimes2be03732007-11-15 02:26:46 +00001040 if (v == NULL || v == Py_None)
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001041 return -1;
1042 oenc = PyObject_GetAttrString(v, "encoding");
1043 if (!oenc)
1044 return -1;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001045 enc = _PyUnicode_AsString(oenc);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001046 }
Guido van Rossum82598051997-03-05 00:20:32 +00001047 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001048 if (v != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001049 v = PyObject_Str(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001050 if (v == NULL)
1051 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +00001052 else if (PyUnicode_Check(v))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001053 ps1 = _PyUnicode_AsString(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001054 }
Guido van Rossum82598051997-03-05 00:20:32 +00001055 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001056 if (w != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001057 w = PyObject_Str(w);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001058 if (w == NULL)
1059 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +00001060 else if (PyUnicode_Check(w))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001061 ps2 = _PyUnicode_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001062 }
Neal Norwitz9589ee22006-03-04 19:01:22 +00001063 arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001064 if (arena == NULL) {
1065 Py_XDECREF(v);
1066 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001067 Py_XDECREF(oenc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001068 return -1;
1069 }
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001070 mod = PyParser_ASTFromFile(fp, filename, enc,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001071 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001072 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001073 Py_XDECREF(v);
1074 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001075 Py_XDECREF(oenc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001076 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001077 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001078 if (errcode == E_EOF) {
1079 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001080 return E_EOF;
1081 }
Guido van Rossum82598051997-03-05 00:20:32 +00001082 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001083 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001084 }
Guido van Rossum82598051997-03-05 00:20:32 +00001085 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001086 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001087 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001088 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001089 }
Guido van Rossum82598051997-03-05 00:20:32 +00001090 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001091 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001092 PyArena_Free(arena);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001093 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001094 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001095 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001096 return -1;
1097 }
Guido van Rossum82598051997-03-05 00:20:32 +00001098 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001099 return 0;
1100}
1101
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001102/* Check whether a file maybe a pyc file: Look at the extension,
1103 the file type, and, if we may close it, at the first few bytes. */
1104
1105static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001106maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001107{
1108 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1109 return 1;
1110
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001111 /* Only look into the file if we are allowed to close it, since
1112 it then should also be seekable. */
1113 if (closeit) {
1114 /* Read only two bytes of the magic. If the file was opened in
1115 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1116 be read as they are on disk. */
1117 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1118 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +00001119 /* Mess: In case of -x, the stream is NOT at its start now,
1120 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001121 which makes the current stream position formally undefined,
1122 and a x-platform nightmare.
1123 Unfortunately, we have no direct way to know whether -x
1124 was specified. So we use a terrible hack: if the current
1125 stream position is not 0, we assume -x was specified, and
1126 give up. Bug 132850 on SourceForge spells out the
1127 hopelessness of trying anything else (fseek and ftell
1128 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +00001129 */
Tim Peters3e876562001-02-11 04:35:39 +00001130 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001131 if (ftell(fp) == 0) {
1132 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +00001133 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001134 ispyc = 1;
1135 rewind(fp);
1136 }
Tim Peters3e876562001-02-11 04:35:39 +00001137 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001138 }
1139 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001140}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001141
Guido van Rossum0df002c2000-08-27 19:21:52 +00001142int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001143PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001144 PyCompilerFlags *flags)
1145{
Guido van Rossum82598051997-03-05 00:20:32 +00001146 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001147 const char *ext;
Matthias Klose042f1332009-04-04 14:32:42 +00001148 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001149
Guido van Rossum82598051997-03-05 00:20:32 +00001150 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001151 if (m == NULL)
1152 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001153 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +00001154 if (PyDict_GetItemString(d, "__file__") == NULL) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001155 PyObject *f;
1156 f = PyUnicode_DecodeFSDefault(filename);
Fred Drake8ed02042002-10-17 21:24:58 +00001157 if (f == NULL)
1158 return -1;
1159 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1160 Py_DECREF(f);
1161 return -1;
1162 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001163 set_file_name = 1;
Fred Drake8ed02042002-10-17 21:24:58 +00001164 Py_DECREF(f);
1165 }
Matthias Klose042f1332009-04-04 14:32:42 +00001166 len = strlen(filename);
1167 ext = filename + len - (len > 4 ? 4 : 0);
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001168 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001169 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +00001170 if (closeit)
1171 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +00001172 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001173 fprintf(stderr, "python: Can't reopen .pyc file\n");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001174 ret = -1;
1175 goto done;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001176 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +00001177 /* Turn on optimization if a .pyo file is given */
1178 if (strcmp(ext, ".pyo") == 0)
1179 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001180 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001181 } else {
Tim Petersd08e3822003-04-17 15:24:21 +00001182 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001183 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001184 }
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001185 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001186 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001187 PyErr_Print();
Guido van Rossumd8faa362007-04-27 19:54:29 +00001188 ret = -1;
1189 goto done;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001190 }
Guido van Rossum82598051997-03-05 00:20:32 +00001191 Py_DECREF(v);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001192 ret = 0;
1193 done:
1194 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1195 PyErr_Clear();
1196 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001197}
1198
1199int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001200PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001201{
Guido van Rossum82598051997-03-05 00:20:32 +00001202 PyObject *m, *d, *v;
1203 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001204 if (m == NULL)
1205 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001206 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +00001207 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001208 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001209 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001210 return -1;
1211 }
Guido van Rossum82598051997-03-05 00:20:32 +00001212 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001213 return 0;
1214}
1215
Barry Warsaw035574d1997-08-29 22:07:17 +00001216static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001217parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1218 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001219{
1220 long hold;
1221 PyObject *v;
1222
1223 /* old style errors */
1224 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +00001225 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001226 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001227
1228 /* new style errors. `err' is an instance */
1229
1230 if (! (v = PyObject_GetAttrString(err, "msg")))
1231 goto finally;
1232 *message = v;
1233
1234 if (!(v = PyObject_GetAttrString(err, "filename")))
1235 goto finally;
1236 if (v == Py_None)
1237 *filename = NULL;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001238 else if (! (*filename = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001239 goto finally;
1240
1241 Py_DECREF(v);
1242 if (!(v = PyObject_GetAttrString(err, "lineno")))
1243 goto finally;
Christian Heimes217cfd12007-12-02 14:31:20 +00001244 hold = PyLong_AsLong(v);
Barry Warsaw035574d1997-08-29 22:07:17 +00001245 Py_DECREF(v);
1246 v = NULL;
1247 if (hold < 0 && PyErr_Occurred())
1248 goto finally;
1249 *lineno = (int)hold;
1250
1251 if (!(v = PyObject_GetAttrString(err, "offset")))
1252 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001253 if (v == Py_None) {
1254 *offset = -1;
1255 Py_DECREF(v);
1256 v = NULL;
1257 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001258 hold = PyLong_AsLong(v);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001259 Py_DECREF(v);
1260 v = NULL;
1261 if (hold < 0 && PyErr_Occurred())
1262 goto finally;
1263 *offset = (int)hold;
1264 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001265
1266 if (!(v = PyObject_GetAttrString(err, "text")))
1267 goto finally;
1268 if (v == Py_None)
1269 *text = NULL;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001270 else if (!PyUnicode_Check(v) ||
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001271 !(*text = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001272 goto finally;
1273 Py_DECREF(v);
1274 return 1;
1275
1276finally:
1277 Py_XDECREF(v);
1278 return 0;
1279}
1280
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001281void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001282PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001283{
Guido van Rossuma61691e1998-02-06 22:27:24 +00001284 PyErr_PrintEx(1);
1285}
1286
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001287static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001288print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001289{
1290 char *nl;
1291 if (offset >= 0) {
1292 if (offset > 0 && offset == (int)strlen(text))
1293 offset--;
1294 for (;;) {
1295 nl = strchr(text, '\n');
1296 if (nl == NULL || nl-text >= offset)
1297 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001298 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001299 text = nl+1;
1300 }
1301 while (*text == ' ' || *text == '\t') {
1302 text++;
1303 offset--;
1304 }
1305 }
1306 PyFile_WriteString(" ", f);
1307 PyFile_WriteString(text, f);
1308 if (*text == '\0' || text[strlen(text)-1] != '\n')
1309 PyFile_WriteString("\n", f);
1310 if (offset == -1)
1311 return;
1312 PyFile_WriteString(" ", f);
1313 offset--;
1314 while (offset > 0) {
1315 PyFile_WriteString(" ", f);
1316 offset--;
1317 }
1318 PyFile_WriteString("^\n", f);
1319}
1320
Guido van Rossum66e8e862001-03-23 17:54:43 +00001321static void
1322handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001323{
Neal Norwitz9589ee22006-03-04 19:01:22 +00001324 PyObject *exception, *value, *tb;
1325 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001326
Guido van Rossumd8faa362007-04-27 19:54:29 +00001327 if (Py_InspectFlag)
1328 /* Don't exit if -i flag was given. This flag is set to 0
1329 * when entering interactive mode for inspecting. */
1330 return;
1331
Guido van Rossum66e8e862001-03-23 17:54:43 +00001332 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001333 fflush(stdout);
1334 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001335 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001336 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001337 /* The error code should be in the `code' attribute. */
1338 PyObject *code = PyObject_GetAttrString(value, "code");
1339 if (code) {
1340 Py_DECREF(value);
1341 value = code;
1342 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001343 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001344 }
1345 /* If we failed to dig out the 'code' attribute,
1346 just let the else clause below print the error. */
1347 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001348 if (PyLong_Check(value))
1349 exitcode = (int)PyLong_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001350 else {
1351 PyObject_Print(value, stderr, Py_PRINT_RAW);
1352 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001353 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001354 }
Tim Peterscf615b52003-04-19 18:47:02 +00001355 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001356 /* Restore and clear the exception info, in order to properly decref
1357 * the exception, value, and traceback. If we just exit instead,
1358 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1359 * some finalizers from running.
1360 */
Tim Peterscf615b52003-04-19 18:47:02 +00001361 PyErr_Restore(exception, value, tb);
1362 PyErr_Clear();
1363 Py_Exit(exitcode);
1364 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001365}
1366
1367void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001368PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001369{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001370 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001371
1372 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1373 handle_system_exit();
1374 }
Guido van Rossum82598051997-03-05 00:20:32 +00001375 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001376 if (exception == NULL)
1377 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001378 PyErr_NormalizeException(&exception, &v, &tb);
Antoine Pitroue2dffc02008-08-26 22:02:58 +00001379 if (tb == NULL) {
1380 tb = Py_None;
1381 Py_INCREF(tb);
1382 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001383 PyException_SetTraceback(v, tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001384 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001385 return;
Georg Brandl86b2fb92008-07-16 03:43:04 +00001386 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001387 if (set_sys_last_vars) {
1388 PySys_SetObject("last_type", exception);
1389 PySys_SetObject("last_value", v);
Benjamin Petersone6528212008-07-15 15:32:09 +00001390 PySys_SetObject("last_traceback", tb);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001391 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001392 hook = PySys_GetObject("excepthook");
1393 if (hook) {
Benjamin Petersone6528212008-07-15 15:32:09 +00001394 PyObject *args = PyTuple_Pack(3, exception, v, tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001395 PyObject *result = PyEval_CallObject(hook, args);
1396 if (result == NULL) {
1397 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001398 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1399 handle_system_exit();
1400 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001401 PyErr_Fetch(&exception2, &v2, &tb2);
1402 PyErr_NormalizeException(&exception2, &v2, &tb2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001403 /* It should not be possible for exception2 or v2
1404 to be NULL. However PyErr_Display() can't
1405 tolerate NULLs, so just be safe. */
1406 if (exception2 == NULL) {
1407 exception2 = Py_None;
1408 Py_INCREF(exception2);
1409 }
1410 if (v2 == NULL) {
1411 v2 = Py_None;
1412 Py_INCREF(v2);
1413 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001414 fflush(stdout);
1415 PySys_WriteStderr("Error in sys.excepthook:\n");
1416 PyErr_Display(exception2, v2, tb2);
1417 PySys_WriteStderr("\nOriginal exception was:\n");
1418 PyErr_Display(exception, v, tb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001419 Py_DECREF(exception2);
1420 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001421 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001422 }
1423 Py_XDECREF(result);
1424 Py_XDECREF(args);
1425 } else {
1426 PySys_WriteStderr("sys.excepthook is missing\n");
1427 PyErr_Display(exception, v, tb);
1428 }
1429 Py_XDECREF(exception);
1430 Py_XDECREF(v);
1431 Py_XDECREF(tb);
1432}
1433
Benjamin Petersone6528212008-07-15 15:32:09 +00001434static void
1435print_exception(PyObject *f, PyObject *value)
1436{
1437 int err = 0;
1438 PyObject *type, *tb;
1439
Benjamin Peterson26582602008-08-23 20:08:07 +00001440 if (!PyExceptionInstance_Check(value)) {
1441 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1442 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1443 PyFile_WriteString(" found\n", f);
1444 return;
1445 }
1446
Benjamin Petersone6528212008-07-15 15:32:09 +00001447 Py_INCREF(value);
1448 fflush(stdout);
1449 type = (PyObject *) Py_TYPE(value);
1450 tb = PyException_GetTraceback(value);
1451 if (tb && tb != Py_None)
1452 err = PyTraceBack_Print(tb, f);
1453 if (err == 0 &&
1454 PyObject_HasAttrString(value, "print_file_and_line"))
1455 {
1456 PyObject *message;
1457 const char *filename, *text;
1458 int lineno, offset;
1459 if (!parse_syntax_error(value, &message, &filename,
1460 &lineno, &offset, &text))
1461 PyErr_Clear();
1462 else {
1463 char buf[10];
1464 PyFile_WriteString(" File \"", f);
1465 if (filename == NULL)
1466 PyFile_WriteString("<string>", f);
1467 else
1468 PyFile_WriteString(filename, f);
1469 PyFile_WriteString("\", line ", f);
1470 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1471 PyFile_WriteString(buf, f);
1472 PyFile_WriteString("\n", f);
1473 if (text != NULL)
1474 print_error_text(f, offset, text);
1475 Py_DECREF(value);
1476 value = message;
1477 /* Can't be bothered to check all those
1478 PyFile_WriteString() calls */
1479 if (PyErr_Occurred())
1480 err = -1;
1481 }
1482 }
1483 if (err) {
1484 /* Don't do anything else */
1485 }
1486 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001487 PyObject* moduleName;
Thomas Hellerd88ddfa2008-07-15 17:14:51 +00001488 char* className;
1489 assert(PyExceptionClass_Check(type));
1490 className = PyExceptionClass_Name(type);
Benjamin Petersone6528212008-07-15 15:32:09 +00001491 if (className != NULL) {
1492 char *dot = strrchr(className, '.');
1493 if (dot != NULL)
1494 className = dot+1;
1495 }
1496
1497 moduleName = PyObject_GetAttrString(type, "__module__");
1498 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1499 {
1500 Py_DECREF(moduleName);
1501 err = PyFile_WriteString("<unknown>", f);
1502 }
1503 else {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001504 char* modstr = _PyUnicode_AsString(moduleName);
Benjamin Petersone6528212008-07-15 15:32:09 +00001505 if (modstr && strcmp(modstr, "builtins"))
1506 {
1507 err = PyFile_WriteString(modstr, f);
1508 err += PyFile_WriteString(".", f);
1509 }
1510 Py_DECREF(moduleName);
1511 }
1512 if (err == 0) {
1513 if (className == NULL)
1514 err = PyFile_WriteString("<unknown>", f);
1515 else
1516 err = PyFile_WriteString(className, f);
1517 }
1518 }
1519 if (err == 0 && (value != Py_None)) {
1520 PyObject *s = PyObject_Str(value);
1521 /* only print colon if the str() of the
1522 object is not the empty string
1523 */
1524 if (s == NULL)
1525 err = -1;
1526 else if (!PyUnicode_Check(s) ||
1527 PyUnicode_GetSize(s) != 0)
1528 err = PyFile_WriteString(": ", f);
1529 if (err == 0)
1530 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1531 Py_XDECREF(s);
1532 }
1533 /* try to write a newline in any case */
1534 err += PyFile_WriteString("\n", f);
1535 Py_XDECREF(tb);
1536 Py_DECREF(value);
1537 /* If an error happened here, don't show it.
1538 XXX This is wrong, but too many callers rely on this behavior. */
1539 if (err != 0)
1540 PyErr_Clear();
1541}
1542
1543static const char *cause_message =
1544 "\nThe above exception was the direct cause "
1545 "of the following exception:\n\n";
1546
1547static const char *context_message =
1548 "\nDuring handling of the above exception, "
1549 "another exception occurred:\n\n";
1550
1551static void
1552print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1553{
1554 int err = 0, res;
1555 PyObject *cause, *context;
1556
1557 if (seen != NULL) {
1558 /* Exception chaining */
1559 if (PySet_Add(seen, value) == -1)
1560 PyErr_Clear();
1561 else if (PyExceptionInstance_Check(value)) {
1562 cause = PyException_GetCause(value);
1563 context = PyException_GetContext(value);
1564 if (cause) {
1565 res = PySet_Contains(seen, cause);
1566 if (res == -1)
1567 PyErr_Clear();
1568 if (res == 0) {
1569 print_exception_recursive(
1570 f, cause, seen);
1571 err |= PyFile_WriteString(
1572 cause_message, f);
1573 }
1574 }
1575 if (context) {
1576 res = PySet_Contains(seen, context);
1577 if (res == -1)
1578 PyErr_Clear();
1579 if (res == 0) {
1580 print_exception_recursive(
1581 f, context, seen);
1582 err |= PyFile_WriteString(
1583 context_message, f);
1584 }
1585 }
1586 Py_XDECREF(context);
1587 Py_XDECREF(cause);
1588 }
1589 }
1590 print_exception(f, value);
1591 if (err != 0)
1592 PyErr_Clear();
1593}
1594
Thomas Wouters477c8d52006-05-27 19:21:47 +00001595void
1596PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001597{
Benjamin Petersone6528212008-07-15 15:32:09 +00001598 PyObject *seen;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001599 PyObject *f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +00001600 if (f == Py_None) {
1601 /* pass */
1602 }
1603 else if (f == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001604 _PyObject_Dump(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001605 fprintf(stderr, "lost sys.stderr\n");
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001606 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001607 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001608 /* We choose to ignore seen being possibly NULL, and report
1609 at least the main exception (it could be a MemoryError).
1610 */
1611 seen = PySet_New(NULL);
1612 if (seen == NULL)
1613 PyErr_Clear();
1614 print_exception_recursive(f, value, seen);
1615 Py_XDECREF(seen);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001616 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001617}
1618
Guido van Rossum82598051997-03-05 00:20:32 +00001619PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001620PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001621 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001622{
Neal Norwitze92fba02006-03-04 18:52:26 +00001623 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001624 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001625 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001626 if (arena == NULL)
1627 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001628
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001629 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001630 if (mod != NULL)
1631 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001632 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001633 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001634}
1635
1636PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001637PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001638 PyObject *locals, int closeit, PyCompilerFlags *flags)
1639{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001640 PyObject *ret;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001641 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001642 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001643 if (arena == NULL)
1644 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001645
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001646 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001647 flags, NULL, arena);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001648 if (closeit)
1649 fclose(fp);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001650 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001651 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001652 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001653 }
Neal Norwitze92fba02006-03-04 18:52:26 +00001654 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001655 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001656 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001657}
1658
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001659static void
1660flush_io(void)
1661{
1662 PyObject *f, *r;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001663 PyObject *type, *value, *traceback;
1664
1665 /* Save the current exception */
1666 PyErr_Fetch(&type, &value, &traceback);
1667
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001668 f = PySys_GetObject("stderr");
1669 if (f != NULL) {
1670 r = PyObject_CallMethod(f, "flush", "");
1671 if (r)
1672 Py_DECREF(r);
1673 else
1674 PyErr_Clear();
1675 }
1676 f = PySys_GetObject("stdout");
1677 if (f != NULL) {
1678 r = PyObject_CallMethod(f, "flush", "");
1679 if (r)
1680 Py_DECREF(r);
1681 else
1682 PyErr_Clear();
1683 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001684
1685 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001686}
1687
Guido van Rossum82598051997-03-05 00:20:32 +00001688static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001689run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001690 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001691{
Guido van Rossum82598051997-03-05 00:20:32 +00001692 PyCodeObject *co;
1693 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001694 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001695 if (co == NULL)
1696 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001697 v = PyEval_EvalCode(co, globals, locals);
1698 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001699 return v;
1700}
1701
Guido van Rossum82598051997-03-05 00:20:32 +00001702static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001703run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001704 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001705{
Guido van Rossum82598051997-03-05 00:20:32 +00001706 PyCodeObject *co;
1707 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001708 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001709 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001710
Guido van Rossum82598051997-03-05 00:20:32 +00001711 magic = PyMarshal_ReadLongFromFile(fp);
1712 if (magic != PyImport_GetMagicNumber()) {
1713 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001714 "Bad magic number in .pyc file");
1715 return NULL;
1716 }
Guido van Rossum82598051997-03-05 00:20:32 +00001717 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001718 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001719 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001720 if (v == NULL || !PyCode_Check(v)) {
1721 Py_XDECREF(v);
1722 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001723 "Bad code object in .pyc file");
1724 return NULL;
1725 }
Guido van Rossum82598051997-03-05 00:20:32 +00001726 co = (PyCodeObject *)v;
1727 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001728 if (v && flags)
1729 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001730 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001731 return v;
1732}
1733
Guido van Rossum82598051997-03-05 00:20:32 +00001734PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001735Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001736 PyCompilerFlags *flags)
1737{
Guido van Rossum82598051997-03-05 00:20:32 +00001738 PyCodeObject *co;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001739 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001740 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001741 if (arena == NULL)
1742 return NULL;
1743
1744 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001745 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001746 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001747 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001748 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001749 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001750 PyObject *result = PyAST_mod2obj(mod);
1751 PyArena_Free(arena);
1752 return result;
1753 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001754 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001755 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001756 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001757}
1758
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001759struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001760Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001761{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001762 struct symtable *st;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001763 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001764 PyCompilerFlags flags;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001765 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001766 if (arena == NULL)
1767 return NULL;
1768
Christian Heimesb1b3efc2008-03-26 23:24:27 +00001769 flags.cf_flags = 0;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001770 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001771 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001772 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001773 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001774 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001775 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001776 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001777 return st;
1778}
1779
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001780/* Preferred access to parser is through AST. */
1781mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001782PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001783 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001784{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001785 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001786 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001787 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001788 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001789
1790 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001791 &_PyParser_Grammar, start, &err,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001792 &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001793 if (flags == NULL) {
1794 localflags.cf_flags = 0;
1795 flags = &localflags;
1796 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001797 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001798 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001799 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001800 PyNode_Free(n);
1801 return mod;
1802 }
1803 else {
1804 err_input(&err);
1805 return NULL;
1806 }
1807}
1808
1809mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001810PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1811 int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001812 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001813 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001814{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001815 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001816 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001817 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001818 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001819
Christian Heimes4d6ec852008-03-26 22:34:47 +00001820 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001821 &_PyParser_Grammar,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001822 start, ps1, ps2, &err, &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001823 if (flags == NULL) {
1824 localflags.cf_flags = 0;
1825 flags = &localflags;
1826 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001827 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001828 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001829 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001830 PyNode_Free(n);
1831 return mod;
1832 }
1833 else {
1834 err_input(&err);
1835 if (errcode)
1836 *errcode = err.error;
1837 return NULL;
1838 }
1839}
1840
Guido van Rossuma110aa61994-08-29 12:50:44 +00001841/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001842
Guido van Rossuma110aa61994-08-29 12:50:44 +00001843node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001844PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001845{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001846 perrdetail err;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001847 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1848 &_PyParser_Grammar,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001849 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001850 if (n == NULL)
1851 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001852
Guido van Rossuma110aa61994-08-29 12:50:44 +00001853 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001854}
1855
Guido van Rossuma110aa61994-08-29 12:50:44 +00001856/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001857
Guido van Rossuma110aa61994-08-29 12:50:44 +00001858node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001859PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001860{
Tim Petersfe2127d2001-07-16 05:37:24 +00001861 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001862 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1863 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001864 if (n == NULL)
1865 err_input(&err);
1866 return n;
1867}
1868
1869node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001870PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001871 int start, int flags)
1872{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001873 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001874 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1875 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001876 if (n == NULL)
1877 err_input(&err);
1878 return n;
1879}
1880
1881node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001882PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001883{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001884 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001885}
1886
Guido van Rossum66ebd912003-04-17 16:02:26 +00001887/* May want to move a more generalized form of this to parsetok.c or
1888 even parser modules. */
1889
1890void
1891PyParser_SetError(perrdetail *err)
1892{
1893 err_input(err);
1894}
1895
Guido van Rossuma110aa61994-08-29 12:50:44 +00001896/* Set the error appropriate to the given input error code (see errcode.h) */
1897
1898static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001899err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001900{
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001901 PyObject *v, *w, *errtype, *errtext;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001902 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001903 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001904 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001905 switch (err->error) {
1906 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001907 errtype = PyExc_IndentationError;
1908 if (err->expected == INDENT)
1909 msg = "expected an indented block";
1910 else if (err->token == INDENT)
1911 msg = "unexpected indent";
1912 else if (err->token == DEDENT)
1913 msg = "unexpected unindent";
1914 else {
1915 errtype = PyExc_SyntaxError;
1916 msg = "invalid syntax";
1917 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001918 break;
1919 case E_TOKEN:
1920 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001921 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001922 case E_EOFS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001923 msg = "EOF while scanning triple-quoted string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001924 break;
1925 case E_EOLS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001926 msg = "EOL while scanning string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001927 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001928 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001929 if (!PyErr_Occurred())
1930 PyErr_SetNone(PyExc_KeyboardInterrupt);
Georg Brandl3dbca812008-07-23 16:10:53 +00001931 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001932 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001933 PyErr_NoMemory();
Georg Brandl3dbca812008-07-23 16:10:53 +00001934 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001935 case E_EOF:
1936 msg = "unexpected EOF while parsing";
1937 break;
Fred Drake85f36392000-07-11 17:53:00 +00001938 case E_TABSPACE:
1939 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001940 msg = "inconsistent use of tabs and spaces in indentation";
1941 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001942 case E_OVERFLOW:
1943 msg = "expression too long";
1944 break;
Fred Drake85f36392000-07-11 17:53:00 +00001945 case E_DEDENT:
1946 errtype = PyExc_IndentationError;
1947 msg = "unindent does not match any outer indentation level";
1948 break;
1949 case E_TOODEEP:
1950 errtype = PyExc_IndentationError;
1951 msg = "too many levels of indentation";
1952 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001953 case E_DECODE: {
1954 PyObject *type, *value, *tb;
1955 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001956 if (value != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001957 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001958 if (u != NULL) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001959 msg = _PyUnicode_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001960 }
1961 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001962 if (msg == NULL)
1963 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001964 Py_XDECREF(type);
1965 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001966 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001967 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001968 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001969 case E_LINECONT:
1970 msg = "unexpected character after line continuation character";
1971 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001972
1973 case E_IDENTIFIER:
1974 msg = "invalid character in identifier";
1975 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001976 default:
1977 fprintf(stderr, "error=%d\n", err->error);
1978 msg = "unknown parsing error";
1979 break;
1980 }
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001981 /* err->text may not be UTF-8 in case of decoding errors.
1982 Explicitly convert to an object. */
1983 if (!err->text) {
1984 errtext = Py_None;
1985 Py_INCREF(Py_None);
1986 } else {
1987 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1988 "replace");
1989 }
1990 v = Py_BuildValue("(ziiN)", err->filename,
1991 err->lineno, err->offset, errtext);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001992 w = NULL;
1993 if (v != NULL)
1994 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001995 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001996 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001997 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001998 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00001999cleanup:
2000 if (err->text != NULL) {
2001 PyObject_FREE(err->text);
2002 err->text = NULL;
2003 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002004}
2005
2006/* Print fatal error message and abort */
2007
2008void
Tim Peters7c321a82002-07-09 02:57:01 +00002009Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002010{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00002011 fprintf(stderr, "Fatal Python error: %s\n", msg);
Jesse Nollera9314042009-03-31 22:36:44 +00002012 fflush(stderr); /* it helps in Windows debug build */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00002013 if (PyErr_Occurred()) {
2014 PyErr_Print();
2015 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002016#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002017 {
2018 size_t len = strlen(msg);
2019 WCHAR* buffer;
2020 size_t i;
2021
2022 /* Convert the message to wchar_t. This uses a simple one-to-one
2023 conversion, assuming that the this error message actually uses ASCII
2024 only. If this ceases to be true, we will have to convert. */
2025 buffer = alloca( (len+1) * (sizeof *buffer));
2026 for( i=0; i<=len; ++i)
2027 buffer[i] = msg[i];
2028 OutputDebugStringW(L"Fatal Python error: ");
2029 OutputDebugStringW(buffer);
2030 OutputDebugStringW(L"\n");
2031 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002032#ifdef _DEBUG
2033 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002034#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002035#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002036 abort();
2037}
2038
2039/* Clean up and exit */
2040
Guido van Rossuma110aa61994-08-29 12:50:44 +00002041#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002042#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002043#endif
2044
Collin Winter670e6922007-03-21 02:57:17 +00002045static void (*pyexitfunc)(void) = NULL;
2046/* For the atexit module. */
2047void _Py_PyAtExit(void (*func)(void))
2048{
2049 pyexitfunc = func;
2050}
2051
2052static void
2053call_py_exitfuncs(void)
2054{
Guido van Rossum98297ee2007-11-06 21:34:58 +00002055 if (pyexitfunc == NULL)
Collin Winter670e6922007-03-21 02:57:17 +00002056 return;
2057
2058 (*pyexitfunc)();
2059 PyErr_Clear();
2060}
2061
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002062#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002063static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002064static int nexitfuncs = 0;
2065
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002066int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002067{
2068 if (nexitfuncs >= NEXITFUNCS)
2069 return -1;
2070 exitfuncs[nexitfuncs++] = func;
2071 return 0;
2072}
2073
Guido van Rossumcc283f51997-08-05 02:22:03 +00002074static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002075call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002076{
Guido van Rossum1662dd51994-09-07 14:38:28 +00002077 while (nexitfuncs > 0)
2078 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002079
2080 fflush(stdout);
2081 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002082}
2083
2084void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002085Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002086{
Guido van Rossumcc283f51997-08-05 02:22:03 +00002087 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002088
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002089 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002090}
2091
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002092static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002093initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002094{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002095#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002096 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002097#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002098#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002099 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002100#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002101#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002102 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002103#endif
Guido van Rossum82598051997-03-05 00:20:32 +00002104 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002105}
2106
Guido van Rossum7433b121997-02-14 19:45:36 +00002107
2108/*
2109 * The file descriptor fd is considered ``interactive'' if either
2110 * a) isatty(fd) is TRUE, or
2111 * b) the -i flag was given, and the filename associated with
2112 * the descriptor is NULL or "<stdin>" or "???".
2113 */
2114int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002115Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002116{
2117 if (isatty((int)fileno(fp)))
2118 return 1;
2119 if (!Py_InteractiveFlag)
2120 return 0;
2121 return (filename == NULL) ||
2122 (strcmp(filename, "<stdin>") == 0) ||
2123 (strcmp(filename, "???") == 0);
2124}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002125
2126
Tim Petersd08e3822003-04-17 15:24:21 +00002127#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002128#if defined(WIN32) && defined(_MSC_VER)
2129
2130/* Stack checking for Microsoft C */
2131
2132#include <malloc.h>
2133#include <excpt.h>
2134
Fred Drakee8de31c2000-08-31 05:38:39 +00002135/*
2136 * Return non-zero when we run out of memory on the stack; zero otherwise.
2137 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002138int
Fred Drake399739f2000-08-31 05:52:44 +00002139PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002140{
2141 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00002142 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002143 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00002144 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002145 return 0;
Christian Heimes7131fd92008-02-19 14:21:46 +00002146 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
Trent Nelson39e307e2008-03-19 06:45:48 +00002147 EXCEPTION_EXECUTE_HANDLER :
2148 EXCEPTION_CONTINUE_SEARCH) {
Christian Heimes7131fd92008-02-19 14:21:46 +00002149 int errcode = _resetstkoflw();
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +00002150 if (errcode == 0)
Christian Heimes7131fd92008-02-19 14:21:46 +00002151 {
2152 Py_FatalError("Could not reset the stack!");
2153 }
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002154 }
2155 return 1;
2156}
2157
2158#endif /* WIN32 && _MSC_VER */
2159
2160/* Alternate implementations can be added here... */
2161
2162#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002163
2164
2165/* Wrappers around sigaction() or signal(). */
2166
2167PyOS_sighandler_t
2168PyOS_getsig(int sig)
2169{
2170#ifdef HAVE_SIGACTION
2171 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002172 if (sigaction(sig, NULL, &context) == -1)
2173 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00002174 return context.sa_handler;
2175#else
2176 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002177/* Special signal handling for the secure CRT in Visual Studio 2005 */
2178#if defined(_MSC_VER) && _MSC_VER >= 1400
2179 switch (sig) {
2180 /* Only these signals are valid */
2181 case SIGINT:
2182 case SIGILL:
2183 case SIGFPE:
2184 case SIGSEGV:
2185 case SIGTERM:
2186 case SIGBREAK:
2187 case SIGABRT:
2188 break;
2189 /* Don't call signal() with other values or it will assert */
2190 default:
2191 return SIG_ERR;
2192 }
2193#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002194 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002195 if (handler != SIG_ERR)
2196 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00002197 return handler;
2198#endif
2199}
2200
2201PyOS_sighandler_t
2202PyOS_setsig(int sig, PyOS_sighandler_t handler)
2203{
2204#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002205 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00002206 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002207 sigemptyset(&context.sa_mask);
2208 context.sa_flags = 0;
2209 if (sigaction(sig, &context, &ocontext) == -1)
2210 return SIG_ERR;
2211 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002212#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002213 PyOS_sighandler_t oldhandler;
2214 oldhandler = signal(sig, handler);
2215#ifdef HAVE_SIGINTERRUPT
2216 siginterrupt(sig, 1);
2217#endif
2218 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002219#endif
2220}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221
2222/* Deprecated C API functions still provided for binary compatiblity */
2223
2224#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002225PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002226PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2227{
2228 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2229}
2230
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002231#undef PyParser_SimpleParseString
2232PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002233PyParser_SimpleParseString(const char *str, int start)
2234{
2235 return PyParser_SimpleParseStringFlags(str, start, 0);
2236}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002237
2238#undef PyRun_AnyFile
2239PyAPI_FUNC(int)
2240PyRun_AnyFile(FILE *fp, const char *name)
2241{
2242 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
2243}
2244
2245#undef PyRun_AnyFileEx
2246PyAPI_FUNC(int)
2247PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2248{
2249 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
2250}
2251
2252#undef PyRun_AnyFileFlags
2253PyAPI_FUNC(int)
2254PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2255{
2256 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2257}
2258
2259#undef PyRun_File
2260PyAPI_FUNC(PyObject *)
2261PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2262{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002263 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002264}
2265
2266#undef PyRun_FileEx
2267PyAPI_FUNC(PyObject *)
2268PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2269{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002270 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002271}
2272
2273#undef PyRun_FileFlags
2274PyAPI_FUNC(PyObject *)
2275PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2276 PyCompilerFlags *flags)
2277{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002278 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002279}
2280
2281#undef PyRun_SimpleFile
2282PyAPI_FUNC(int)
2283PyRun_SimpleFile(FILE *f, const char *p)
2284{
2285 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
2286}
2287
2288#undef PyRun_SimpleFileEx
2289PyAPI_FUNC(int)
2290PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2291{
2292 return PyRun_SimpleFileExFlags(f, p, c, NULL);
2293}
2294
2295
2296#undef PyRun_String
2297PyAPI_FUNC(PyObject *)
2298PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2299{
2300 return PyRun_StringFlags(str, s, g, l, NULL);
2301}
2302
2303#undef PyRun_SimpleString
2304PyAPI_FUNC(int)
2305PyRun_SimpleString(const char *s)
2306{
2307 return PyRun_SimpleStringFlags(s, NULL);
2308}
2309
2310#undef Py_CompileString
2311PyAPI_FUNC(PyObject *)
2312Py_CompileString(const char *str, const char *p, int s)
2313{
2314 return Py_CompileStringFlags(str, p, s, NULL);
2315}
2316
2317#undef PyRun_InteractiveOne
2318PyAPI_FUNC(int)
2319PyRun_InteractiveOne(FILE *f, const char *p)
2320{
2321 return PyRun_InteractiveOneFlags(f, p, NULL);
2322}
2323
2324#undef PyRun_InteractiveLoop
2325PyAPI_FUNC(int)
2326PyRun_InteractiveLoop(FILE *f, const char *p)
2327{
2328 return PyRun_InteractiveLoopFlags(f, p, NULL);
2329}
2330
2331#ifdef __cplusplus
2332}
2333#endif