blob: 2bdef981ad51a302cdf116e86f87f2f93e177d99 [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"
Antoine Pitrou011bd622009-10-20 21:52:47 +000021#include "abstract.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000022
Thomas Wouters0e3f5912006-08-11 14:57:12 +000023#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000024#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000025#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000026
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000027#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000028#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000029#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000030
Martin v. Löwis73d538b2003-03-05 15:13:47 +000031#ifdef HAVE_LANGINFO_H
32#include <locale.h>
33#include <langinfo.h>
34#endif
35
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000036#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000037#undef BYTE
38#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000039#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000040#endif
41
Neal Norwitz4281cef2006-03-04 19:58:13 +000042#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000043#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000044#else /* Py_REF_DEBUG */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000045#define PRINT_TOTAL_REFS() fprintf(stderr, \
46 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
47 _Py_GetRefTotal())
48#endif
49
50#ifdef __cplusplus
51extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000052#endif
53
Martin v. Löwis790465f2008-04-05 20:41:37 +000054extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000055
Guido van Rossum82598051997-03-05 00:20:32 +000056extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000057
Guido van Rossumb73cc041993-11-01 16:28:59 +000058/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000059static void initmain(void);
60static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000061static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000062static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000063static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Neal Norwitzadb69fc2005-12-17 20:54:49 +000064 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000065static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000066 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000067static void err_input(perrdetail *);
68static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000069static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000070static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000071static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000072extern void _PyUnicode_Init(void);
73extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000074extern int _PyLong_Init(void);
75extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000076
Mark Hammond8d98d2c2003-04-19 15:41:53 +000077#ifdef WITH_THREAD
78extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
79extern void _PyGILState_Fini(void);
80#endif /* WITH_THREAD */
81
Guido van Rossum82598051997-03-05 00:20:32 +000082int Py_DebugFlag; /* Needed by parser.c */
83int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000084int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000085int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000086int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000087int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000088int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000089int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000090int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000091int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000092int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000093int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000094
Christian Heimes33fe8092008-04-13 13:53:33 +000095/* PyModule_GetWarningsModule is no longer necessary as of 2.6
96since _warnings is builtin. This API should not be used. */
97PyObject *
98PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000099{
Christian Heimes33fe8092008-04-13 13:53:33 +0000100 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000101}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000102
Guido van Rossum25ce5661997-08-02 03:10:38 +0000103static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000104
Thomas Wouters7e474022000-07-16 12:04:32 +0000105/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000106
107int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000108Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000109{
110 return initialized;
111}
112
Guido van Rossum25ce5661997-08-02 03:10:38 +0000113/* Global initializations. Can be undone by Py_Finalize(). Don't
114 call this twice without an intervening Py_Finalize() call. When
115 initializations fail, a fatal error is issued and the function does
116 not return. On return, the first thread and interpreter state have
117 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000118
Guido van Rossum25ce5661997-08-02 03:10:38 +0000119 Locking: you must hold the interpreter lock while calling this.
120 (If the lock has not yet been initialized, that's equivalent to
121 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000122
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000124
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000125static int
126add_flag(int flag, const char *envs)
127{
128 int env = atoi(envs);
129 if (flag < env)
130 flag = env;
131 if (flag < 1)
132 flag = 1;
133 return flag;
134}
135
Christian Heimes5833a2f2008-10-30 21:40:04 +0000136#if defined(HAVE_LANGINFO_H) && defined(CODESET)
137static char*
138get_codeset(void)
139{
140 char* codeset;
141 PyObject *codec, *name;
142
143 codeset = nl_langinfo(CODESET);
144 if (!codeset || codeset[0] == '\0')
145 return NULL;
146
147 codec = _PyCodec_Lookup(codeset);
148 if (!codec)
149 goto error;
150
151 name = PyObject_GetAttrString(codec, "name");
152 Py_CLEAR(codec);
153 if (!name)
154 goto error;
155
156 codeset = strdup(_PyUnicode_AsString(name));
157 Py_DECREF(name);
158 return codeset;
159
160error:
161 Py_XDECREF(codec);
162 PyErr_Clear();
163 return NULL;
164}
165#endif
166
Guido van Rossuma027efa1997-05-05 20:56:21 +0000167void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000168Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000169{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000170 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000171 PyThreadState *tstate;
Guido van Rossum826d8972007-10-30 18:34:07 +0000172 PyObject *bimod, *sysmod, *pstderr;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000173 char *p;
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000174#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000175 char *codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000176#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +0000177 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000178
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000179 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000180 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000181 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000182
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000183#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000184 /* Set up the LC_CTYPE locale, so we can obtain
185 the locale's charset without having to switch
186 locales. */
187 setlocale(LC_CTYPE, "");
188#endif
189
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000190 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000191 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000192 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000193 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000194 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000195 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Christian Heimes790c8232008-01-07 21:14:23 +0000196 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
197 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000198
Guido van Rossuma027efa1997-05-05 20:56:21 +0000199 interp = PyInterpreterState_New();
200 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000201 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000202
Guido van Rossuma027efa1997-05-05 20:56:21 +0000203 tstate = PyThreadState_New(interp);
204 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000205 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000206 (void) PyThreadState_Swap(tstate);
207
Guido van Rossum70d893a2001-08-16 08:21:42 +0000208 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000209
Neal Norwitzb2501f42002-12-31 03:42:13 +0000210 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000211 Py_FatalError("Py_Initialize: can't init frames");
212
Guido van Rossumddefaf32007-01-14 03:31:43 +0000213 if (!_PyLong_Init())
214 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000215
Christian Heimes9c4756e2008-05-26 13:22:05 +0000216 if (!PyByteArray_Init())
Benjamin Petersoncc3b8d62009-05-10 23:43:14 +0000217 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000218
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000219 _PyFloat_Init();
220
Guido van Rossum25ce5661997-08-02 03:10:38 +0000221 interp->modules = PyDict_New();
222 if (interp->modules == NULL)
223 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossumd8faa362007-04-27 19:54:29 +0000224 interp->modules_reloading = PyDict_New();
225 if (interp->modules_reloading == NULL)
226 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000227
Guido van Rossumc94044c2000-03-10 23:03:54 +0000228 /* Init Unicode implementation; relies on the codec registry */
229 _PyUnicode_Init();
230
Barry Warsawf242aa02000-05-25 23:09:49 +0000231 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000232 if (bimod == NULL)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000233 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Martin v. Löwis1a214512008-06-11 05:26:20 +0000234 _PyImport_FixupExtension(bimod, "builtins", "builtins");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000235 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000236 if (interp->builtins == NULL)
237 Py_FatalError("Py_Initialize: can't initialize builtins dict");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000238 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000239
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000240 /* initialize builtin exceptions */
241 _PyExc_Init();
242
Guido van Rossum25ce5661997-08-02 03:10:38 +0000243 sysmod = _PySys_Init();
244 if (sysmod == NULL)
245 Py_FatalError("Py_Initialize: can't initialize sys");
246 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000247 if (interp->sysdict == NULL)
248 Py_FatalError("Py_Initialize: can't initialize sys dict");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000249 Py_INCREF(interp->sysdict);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000250 _PyImport_FixupExtension(sysmod, "sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000251 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000252 PyDict_SetItemString(interp->sysdict, "modules",
253 interp->modules);
254
Guido van Rossum826d8972007-10-30 18:34:07 +0000255 /* Set up a preliminary stderr printer until we have enough
256 infrastructure for the io module in place. */
257 pstderr = PyFile_NewStdPrinter(fileno(stderr));
258 if (pstderr == NULL)
259 Py_FatalError("Py_Initialize: can't set preliminary stderr");
260 PySys_SetObject("stderr", pstderr);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000261 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000262
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000263 _PyImport_Init();
264
Just van Rossum52e14d62002-12-30 22:08:05 +0000265 _PyImportHooks_Init();
266
Martin v. Löwis011e8422009-05-05 04:43:17 +0000267#if defined(HAVE_LANGINFO_H) && defined(CODESET)
268 /* On Unix, set the file system encoding according to the
269 user's preference, if the CODESET names a well-known
270 Python codec, and Py_FileSystemDefaultEncoding isn't
271 initialized by other means. Also set the encoding of
272 stdin and stdout if these are terminals. */
273
274 codeset = get_codeset();
275 if (codeset) {
276 if (!Py_FileSystemDefaultEncoding)
277 Py_FileSystemDefaultEncoding = codeset;
278 else
279 free(codeset);
280 }
281#endif
282
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000283 if (install_sigs)
284 initsigs(); /* Signal handling stuff, including initintr() */
Christian Heimes33fe8092008-04-13 13:53:33 +0000285
Georg Brandl86b2fb92008-07-16 03:43:04 +0000286 /* Initialize warnings. */
287 _PyWarnings_Init();
288 if (PySys_HasWarnOptions()) {
289 PyObject *warnings_module = PyImport_ImportModule("warnings");
290 if (!warnings_module)
291 PyErr_Clear();
292 Py_XDECREF(warnings_module);
293 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000294
295 initmain(); /* Module __main__ */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000296 if (initstdio() < 0)
297 Py_FatalError(
298 "Py_Initialize: can't initialize sys standard streams");
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 */
Victor Stinner52f6dd72010-03-12 14:45:56 +0000304
305 if (!Py_NoSiteFlag)
306 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000307}
308
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000309void
310Py_Initialize(void)
311{
312 Py_InitializeEx(1);
313}
314
315
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000316#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000317extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000318#endif
319
Guido van Rossume8432ac2007-07-09 15:04:50 +0000320/* Flush stdout and stderr */
321
Neal Norwitz2bad9702007-08-27 06:19:22 +0000322static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000323flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000324{
325 PyObject *fout = PySys_GetObject("stdout");
326 PyObject *ferr = PySys_GetObject("stderr");
327 PyObject *tmp;
328
Christian Heimes2be03732007-11-15 02:26:46 +0000329 if (fout != NULL && fout != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000330 tmp = PyObject_CallMethod(fout, "flush", "");
331 if (tmp == NULL)
332 PyErr_Clear();
333 else
334 Py_DECREF(tmp);
335 }
336
Christian Heimes2be03732007-11-15 02:26:46 +0000337 if (ferr != NULL || ferr != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000338 tmp = PyObject_CallMethod(ferr, "flush", "");
339 if (tmp == NULL)
340 PyErr_Clear();
341 else
342 Py_DECREF(tmp);
343 }
344}
345
Guido van Rossum25ce5661997-08-02 03:10:38 +0000346/* Undo the effect of Py_Initialize().
347
348 Beware: if multiple interpreter and/or thread states exist, these
349 are not wiped out; only the current thread and interpreter state
350 are deleted. But since everything else is deleted, those other
351 interpreter and thread states should no longer be used.
352
353 (XXX We should do better, e.g. wipe out all interpreters and
354 threads.)
355
356 Locking: as above.
357
358*/
359
360void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000361Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000362{
363 PyInterpreterState *interp;
364 PyThreadState *tstate;
365
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000366 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000367 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000368
Antoine Pitrou011bd622009-10-20 21:52:47 +0000369 wait_for_thread_shutdown();
370
Tim Peters384fd102001-01-21 03:40:37 +0000371 /* The interpreter is still entirely intact at this point, and the
372 * exit funcs may be relying on that. In particular, if some thread
373 * or exit func is still waiting to do an import, the import machinery
374 * expects Py_IsInitialized() to return true. So don't say the
375 * interpreter is uninitialized until after the exit funcs have run.
376 * Note that Threading.py uses an exit func to do a join on all the
377 * threads created thru it, so this also protects pending imports in
378 * the threads created via Threading.
379 */
Collin Winter670e6922007-03-21 02:57:17 +0000380 call_py_exitfuncs();
Tim Peters384fd102001-01-21 03:40:37 +0000381 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000382
Guido van Rossume8432ac2007-07-09 15:04:50 +0000383 /* Flush stdout+stderr */
384 flush_std_files();
385
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000386 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000387 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000388 interp = tstate->interp;
389
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000390 /* Disable signal handling */
391 PyOS_FiniInterrupts();
392
Christian Heimes26855632008-01-27 23:50:43 +0000393 /* Clear type lookup cache */
394 PyType_ClearCache();
395
Guido van Rossume13ddc92003-04-17 17:29:22 +0000396 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000397 * before all modules are destroyed.
398 * XXX If a __del__ or weakref callback is triggered here, and tries to
399 * XXX import a module, bad things can happen, because Python no
400 * XXX longer believes it's initialized.
401 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
402 * XXX is easy to provoke that way. I've also seen, e.g.,
403 * XXX Exception exceptions.ImportError: 'No module named sha'
404 * XXX in <function callback at 0x008F5718> ignored
405 * XXX but I'm unclear on exactly how that one happens. In any case,
406 * XXX I haven't seen a real-life report of either of these.
Neal Norwitz9589ee22006-03-04 19:01:22 +0000407 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000408 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000409#ifdef COUNT_ALLOCS
410 /* With COUNT_ALLOCS, it helps to run GC multiple times:
411 each collection might release some types from the type
412 list, so they become garbage. */
413 while (PyGC_Collect() > 0)
414 /* nothing */;
415#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000416
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000417 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000418 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000419
Guido van Rossume8432ac2007-07-09 15:04:50 +0000420 /* Flush stdout+stderr (again, in case more was printed) */
421 flush_std_files();
422
Guido van Rossume13ddc92003-04-17 17:29:22 +0000423 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000424 * new-style class definitions, for example.
425 * XXX This is disabled because it caused too many problems. If
426 * XXX a __del__ or weakref callback triggers here, Python code has
427 * XXX a hard time running, because even the sys module has been
428 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
429 * XXX One symptom is a sequence of information-free messages
430 * XXX coming from threads (if a __del__ or callback is invoked,
431 * XXX other threads can execute too, and any exception they encounter
432 * XXX triggers a comedy of errors as subsystem after subsystem
433 * XXX fails to find what it *expects* to find in sys to help report
434 * XXX the exception and consequent unexpected failures). I've also
435 * XXX seen segfaults then, after adding print statements to the
436 * XXX Python code getting called.
437 */
438#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000439 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000440#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000441
Guido van Rossum1707aad1997-12-08 23:43:45 +0000442 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
443 _PyImport_Fini();
444
445 /* Debugging stuff */
446#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000447 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000448#endif
449
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000450 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000451
Tim Peters9cf25ce2003-04-17 15:21:01 +0000452#ifdef Py_TRACE_REFS
453 /* Display all objects still alive -- this can invoke arbitrary
454 * __repr__ overrides, so requires a mostly-intact interpreter.
455 * Alas, a lot of stuff may still be alive now that will be cleaned
456 * up later.
457 */
Tim Peters269b2a62003-04-17 19:52:29 +0000458 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000459 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000460#endif /* Py_TRACE_REFS */
461
Guido van Rossumd922fa42003-04-15 14:10:09 +0000462 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000463 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000464
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000465 /* Now we decref the exception classes. After this point nothing
466 can raise an exception. That's okay, because each Fini() method
467 below has been checked to make sure no exceptions are ever
468 raised.
469 */
470
471 _PyExc_Fini();
472
Christian Heimes7d2ff882007-11-30 14:35:04 +0000473 /* Cleanup auto-thread-state */
474#ifdef WITH_THREAD
475 _PyGILState_Fini();
476#endif /* WITH_THREAD */
477
Guido van Rossumd922fa42003-04-15 14:10:09 +0000478 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000479 PyThreadState_Swap(NULL);
480 PyInterpreterState_Delete(interp);
481
Guido van Rossumd922fa42003-04-15 14:10:09 +0000482 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000483 PyMethod_Fini();
484 PyFrame_Fini();
485 PyCFunction_Fini();
486 PyTuple_Fini();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000487 PyList_Fini();
Raymond Hettingerd7946662005-08-01 21:39:29 +0000488 PySet_Fini();
Christian Heimes72b710a2008-05-26 13:28:38 +0000489 PyBytes_Fini();
Christian Heimes9c4756e2008-05-26 13:22:05 +0000490 PyByteArray_Fini();
Guido van Rossumddefaf32007-01-14 03:31:43 +0000491 PyLong_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000492 PyFloat_Fini();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000493 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000494
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000495 /* Cleanup Unicode implementation */
496 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000497
Christian Heimesc8967002007-11-30 10:18:26 +0000498 /* reset file system default encoding */
499 if (!Py_HasFileSystemDefaultEncoding) {
500 free((char*)Py_FileSystemDefaultEncoding);
Trent Nelson39e307e2008-03-19 06:45:48 +0000501 Py_FileSystemDefaultEncoding = NULL;
Christian Heimesc8967002007-11-30 10:18:26 +0000502 }
503
Guido van Rossumcc283f51997-08-05 02:22:03 +0000504 /* XXX Still allocated:
505 - various static ad-hoc pointers to interned strings
506 - int and float free list blocks
507 - whatever various modules and libraries allocate
508 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000509
510 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000511
Tim Peters269b2a62003-04-17 19:52:29 +0000512#ifdef Py_TRACE_REFS
513 /* Display addresses (& refcnts) of all objects still alive.
514 * An address can be used to find the repr of the object, printed
515 * above by _Py_PrintReferences.
516 */
517 if (Py_GETENV("PYTHONDUMPREFS"))
518 _Py_PrintReferenceAddresses(stderr);
519#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000520#ifdef PYMALLOC_DEBUG
521 if (Py_GETENV("PYTHONMALLOCSTATS"))
522 _PyObject_DebugMallocStats();
523#endif
524
Guido van Rossumcc283f51997-08-05 02:22:03 +0000525 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000526}
527
528/* Create and initialize a new interpreter and thread, and return the
529 new thread. This requires that Py_Initialize() has been called
530 first.
531
532 Unsuccessful initialization yields a NULL pointer. Note that *no*
533 exception information is available even in this case -- the
534 exception information is held in the thread, and there is no
535 thread.
536
537 Locking: as above.
538
539*/
540
541PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000542Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000543{
544 PyInterpreterState *interp;
545 PyThreadState *tstate, *save_tstate;
546 PyObject *bimod, *sysmod;
547
548 if (!initialized)
549 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
550
551 interp = PyInterpreterState_New();
552 if (interp == NULL)
553 return NULL;
554
555 tstate = PyThreadState_New(interp);
556 if (tstate == NULL) {
557 PyInterpreterState_Delete(interp);
558 return NULL;
559 }
560
561 save_tstate = PyThreadState_Swap(tstate);
562
563 /* XXX The following is lax in error checking */
564
565 interp->modules = PyDict_New();
Guido van Rossumd8faa362007-04-27 19:54:29 +0000566 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000567
Georg Brandl1a3284e2007-12-02 09:40:06 +0000568 bimod = _PyImport_FindExtension("builtins", "builtins");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000570 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000571 if (interp->builtins == NULL)
572 goto handle_error;
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000573 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000575
576 /* initialize builtin exceptions */
577 _PyExc_Init();
578
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579 sysmod = _PyImport_FindExtension("sys", "sys");
580 if (bimod != NULL && sysmod != NULL) {
Christian Heimes6a27efa2008-10-30 21:48:26 +0000581 PyObject *pstderr;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000582 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000583 if (interp->sysdict == NULL)
584 goto handle_error;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000585 Py_INCREF(interp->sysdict);
586 PySys_SetPath(Py_GetPath());
587 PyDict_SetItemString(interp->sysdict, "modules",
588 interp->modules);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000589 /* Set up a preliminary stderr printer until we have enough
590 infrastructure for the io module in place. */
591 pstderr = PyFile_NewStdPrinter(fileno(stderr));
592 if (pstderr == NULL)
593 Py_FatalError("Py_Initialize: can't set preliminary stderr");
594 PySys_SetObject("stderr", pstderr);
595 PySys_SetObject("__stderr__", pstderr);
596
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000597 _PyImportHooks_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000598 if (initstdio() < 0)
599 Py_FatalError(
600 "Py_Initialize: can't initialize sys standard streams");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000601 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000602 if (!Py_NoSiteFlag)
603 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000604 }
605
606 if (!PyErr_Occurred())
607 return tstate;
608
Thomas Wouters89f507f2006-12-13 04:49:30 +0000609handle_error:
Guido van Rossum25ce5661997-08-02 03:10:38 +0000610 /* Oops, it didn't work. Undo it all. */
611
612 PyErr_Print();
613 PyThreadState_Clear(tstate);
614 PyThreadState_Swap(save_tstate);
615 PyThreadState_Delete(tstate);
616 PyInterpreterState_Delete(interp);
617
618 return NULL;
619}
620
621/* Delete an interpreter and its last thread. This requires that the
622 given thread state is current, that the thread has no remaining
623 frames, and that it is its interpreter's only remaining thread.
624 It is a fatal error to violate these constraints.
625
626 (Py_Finalize() doesn't have these constraints -- it zaps
627 everything, regardless.)
628
629 Locking: as above.
630
631*/
632
633void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000634Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000635{
636 PyInterpreterState *interp = tstate->interp;
637
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000638 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000639 Py_FatalError("Py_EndInterpreter: thread is not current");
640 if (tstate->frame != NULL)
641 Py_FatalError("Py_EndInterpreter: thread still has a frame");
642 if (tstate != interp->tstate_head || tstate->next != NULL)
643 Py_FatalError("Py_EndInterpreter: not the last thread");
644
645 PyImport_Cleanup();
646 PyInterpreterState_Clear(interp);
647 PyThreadState_Swap(NULL);
648 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000649}
650
Martin v. Löwis790465f2008-04-05 20:41:37 +0000651static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000652
653void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000654Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000655{
656 if (pn && *pn)
657 progname = pn;
658}
659
Martin v. Löwis790465f2008-04-05 20:41:37 +0000660wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000661Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000662{
663 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000664}
665
Martin v. Löwis790465f2008-04-05 20:41:37 +0000666static wchar_t *default_home = NULL;
667static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000668
669void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000670Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000671{
672 default_home = home;
673}
674
Martin v. Löwis790465f2008-04-05 20:41:37 +0000675wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000676Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000677{
Martin v. Löwis790465f2008-04-05 20:41:37 +0000678 wchar_t *home = default_home;
679 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
680 char* chome = Py_GETENV("PYTHONHOME");
681 if (chome) {
682 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
683 if (r != (size_t)-1 && r <= PATH_MAX)
684 home = env_home;
685 }
686
687 }
Guido van Rossuma61691e1998-02-06 22:27:24 +0000688 return home;
689}
690
Guido van Rossum6135a871995-01-09 17:53:26 +0000691/* Create __main__ module */
692
693static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000694initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000695{
Guido van Rossum82598051997-03-05 00:20:32 +0000696 PyObject *m, *d;
697 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000698 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000699 Py_FatalError("can't create __main__ module");
700 d = PyModule_GetDict(m);
701 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Georg Brandl1a3284e2007-12-02 09:40:06 +0000702 PyObject *bimod = PyImport_ImportModule("builtins");
Guido van Rossum858cb731997-11-19 16:15:37 +0000703 if (bimod == NULL ||
704 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000705 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000706 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000707 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000708}
709
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000710/* Import the site module (not into __main__ though) */
711
712static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000713initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000714{
Victor Stinner52f6dd72010-03-12 14:45:56 +0000715 PyObject *m;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000716 m = PyImport_ImportModule("site");
717 if (m == NULL) {
Victor Stinner52f6dd72010-03-12 14:45:56 +0000718 PyErr_Print();
719 Py_Finalize();
720 exit(1);
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000721 }
722 else {
723 Py_DECREF(m);
724 }
725}
726
Antoine Pitrou05608432009-01-09 18:53:14 +0000727static PyObject*
728create_stdio(PyObject* io,
729 int fd, int write_mode, char* name,
730 char* encoding, char* errors)
731{
Antoine Pitrou91696412009-01-09 22:12:30 +0000732 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
Antoine Pitrou05608432009-01-09 18:53:14 +0000733 const char* mode;
Antoine Pitrou91696412009-01-09 22:12:30 +0000734 PyObject *line_buffering;
735 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000736
Antoine Pitrou27fe9fc2009-01-26 21:48:00 +0000737 /* stdin is always opened in buffered mode, first because it shouldn't
738 make a difference in common use cases, second because TextIOWrapper
739 depends on the presence of a read1() method which only exists on
740 buffered streams.
741 */
742 if (Py_UnbufferedStdioFlag && write_mode)
Antoine Pitrou05608432009-01-09 18:53:14 +0000743 buffering = 0;
744 else
745 buffering = -1;
746 if (write_mode)
747 mode = "wb";
748 else
749 mode = "rb";
750 buf = PyObject_CallMethod(io, "open", "isiOOOi",
751 fd, mode, buffering,
752 Py_None, Py_None, Py_None, 0);
753 if (buf == NULL)
754 goto error;
755
Antoine Pitrou27fe9fc2009-01-26 21:48:00 +0000756 if (buffering) {
Antoine Pitrou05608432009-01-09 18:53:14 +0000757 raw = PyObject_GetAttrString(buf, "raw");
758 if (raw == NULL)
759 goto error;
760 }
761 else {
762 raw = buf;
763 Py_INCREF(raw);
764 }
765
766 text = PyUnicode_FromString(name);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000767 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
Antoine Pitrou05608432009-01-09 18:53:14 +0000768 goto error;
Antoine Pitrou91696412009-01-09 22:12:30 +0000769 res = PyObject_CallMethod(raw, "isatty", "");
770 if (res == NULL)
771 goto error;
772 isatty = PyObject_IsTrue(res);
773 Py_DECREF(res);
774 if (isatty == -1)
775 goto error;
776 if (isatty || Py_UnbufferedStdioFlag)
Antoine Pitrou05608432009-01-09 18:53:14 +0000777 line_buffering = Py_True;
778 else
779 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000780
781 Py_CLEAR(raw);
782 Py_CLEAR(text);
783
Antoine Pitrou05608432009-01-09 18:53:14 +0000784 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
785 buf, encoding, errors,
786 "\n", line_buffering);
787 Py_CLEAR(buf);
788 if (stream == NULL)
789 goto error;
790
791 if (write_mode)
792 mode = "w";
793 else
794 mode = "r";
795 text = PyUnicode_FromString(mode);
796 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
797 goto error;
798 Py_CLEAR(text);
799 return stream;
800
801error:
802 Py_XDECREF(buf);
803 Py_XDECREF(stream);
804 Py_XDECREF(text);
805 Py_XDECREF(raw);
806 return NULL;
807}
808
Georg Brandl1a3284e2007-12-02 09:40:06 +0000809/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000810static int
811initstdio(void)
812{
813 PyObject *iomod = NULL, *wrapper;
814 PyObject *bimod = NULL;
815 PyObject *m;
816 PyObject *std = NULL;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000817 int status = 0, fd;
Trent Nelson39e307e2008-03-19 06:45:48 +0000818 PyObject * encoding_attr;
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +0000819 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000820
821 /* Hack to avoid a nasty recursion issue when Python is invoked
822 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
823 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
824 goto error;
825 }
826 Py_DECREF(m);
827
828 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
829 goto error;
830 }
831 Py_DECREF(m);
832
Georg Brandl1a3284e2007-12-02 09:40:06 +0000833 if (!(bimod = PyImport_ImportModule("builtins"))) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000834 goto error;
835 }
836
837 if (!(iomod = PyImport_ImportModule("io"))) {
838 goto error;
839 }
840 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
841 goto error;
842 }
843
Georg Brandl1a3284e2007-12-02 09:40:06 +0000844 /* Set builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000845 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
846 goto error;
847 }
848
Martin v. Löwis0f599892008-06-02 11:13:03 +0000849 encoding = Py_GETENV("PYTHONIOENCODING");
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000850 errors = NULL;
Martin v. Löwis0f599892008-06-02 11:13:03 +0000851 if (encoding) {
852 encoding = strdup(encoding);
853 errors = strchr(encoding, ':');
854 if (errors) {
855 *errors = '\0';
856 errors++;
857 }
858 }
859
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000860 /* Set sys.stdin */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000861 fd = fileno(stdin);
862 /* Under some conditions stdin, stdout and stderr may not be connected
863 * and fileno() may point to an invalid file descriptor. For example
864 * GUI apps don't have valid standard streams by default.
865 */
866 if (fd < 0) {
867#ifdef MS_WINDOWS
868 std = Py_None;
869 Py_INCREF(std);
870#else
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000871 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000872#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000873 }
Christian Heimes58cb1b82007-11-13 02:19:40 +0000874 else {
Antoine Pitrou05608432009-01-09 18:53:14 +0000875 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
876 if (std == NULL)
Christian Heimes58cb1b82007-11-13 02:19:40 +0000877 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000878 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000879 PySys_SetObject("__stdin__", std);
880 PySys_SetObject("stdin", std);
881 Py_DECREF(std);
882
883 /* Set sys.stdout */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000884 fd = fileno(stdout);
885 if (fd < 0) {
886#ifdef MS_WINDOWS
887 std = Py_None;
888 Py_INCREF(std);
889#else
890 goto error;
891#endif
892 }
893 else {
Antoine Pitrou05608432009-01-09 18:53:14 +0000894 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
895 if (std == NULL)
Christian Heimes58cb1b82007-11-13 02:19:40 +0000896 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000897 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000898 PySys_SetObject("__stdout__", std);
899 PySys_SetObject("stdout", std);
900 Py_DECREF(std);
901
Guido van Rossum98297ee2007-11-06 21:34:58 +0000902#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000903 /* Set sys.stderr, replaces the preliminary stderr */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000904 fd = fileno(stderr);
905 if (fd < 0) {
906#ifdef MS_WINDOWS
907 std = Py_None;
908 Py_INCREF(std);
909#else
910 goto error;
911#endif
912 }
913 else {
Antoine Pitrou05608432009-01-09 18:53:14 +0000914 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
915 if (std == NULL)
Christian Heimes58cb1b82007-11-13 02:19:40 +0000916 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000917 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000918
919 /* Same as hack above, pre-import stderr's codec to avoid recursion
920 when import.c tries to write to stderr in verbose mode. */
921 encoding_attr = PyObject_GetAttrString(std, "encoding");
922 if (encoding_attr != NULL) {
923 const char * encoding;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000924 encoding = _PyUnicode_AsString(encoding_attr);
Trent Nelson39e307e2008-03-19 06:45:48 +0000925 if (encoding != NULL) {
926 _PyCodec_Lookup(encoding);
927 }
928 }
929 PyErr_Clear(); /* Not a fatal error if codec isn't available */
930
Christian Heimesdb233082007-11-13 02:34:21 +0000931 PySys_SetObject("__stderr__", std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000932 PySys_SetObject("stderr", std);
933 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000934#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000935
Christian Heimes58cb1b82007-11-13 02:19:40 +0000936 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000937 error:
Christian Heimesdb233082007-11-13 02:34:21 +0000938 status = -1;
939 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000940
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000941 if (encoding)
942 free(encoding);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000943 Py_XDECREF(bimod);
944 Py_XDECREF(iomod);
945 return status;
946}
947
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000948/* Parse input from a file and execute it */
949
950int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000951PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000952 PyCompilerFlags *flags)
953{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000954 if (filename == NULL)
955 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000956 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000957 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000958 if (closeit)
959 fclose(fp);
960 return err;
961 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000962 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000963 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000964}
965
966int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000967PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000968{
Guido van Rossum82598051997-03-05 00:20:32 +0000969 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000970 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000971 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000972
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000973 if (flags == NULL) {
974 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000975 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000976 }
Guido van Rossum82598051997-03-05 00:20:32 +0000977 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000978 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000979 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
Guido van Rossum82598051997-03-05 00:20:32 +0000980 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000981 }
Guido van Rossum82598051997-03-05 00:20:32 +0000982 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000983 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000984 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
Guido van Rossum82598051997-03-05 00:20:32 +0000985 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000986 }
987 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000988 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000989 PRINT_TOTAL_REFS();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000990 if (ret == E_EOF)
991 return 0;
992 /*
993 if (ret == E_NOMEM)
994 return -1;
995 */
996 }
997}
998
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000999/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001000static int PARSER_FLAGS(PyCompilerFlags *flags)
1001{
1002 int parser_flags = 0;
1003 if (!flags)
1004 return 0;
1005 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1006 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1007 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1008 parser_flags |= PyPARSE_IGNORE_COOKIE;
Brett Cannone3944a52009-04-01 05:08:41 +00001009 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1010 parser_flags |= PyPARSE_BARRY_AS_BDFL;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001011 return parser_flags;
1012}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001013
Thomas Wouters89f507f2006-12-13 04:49:30 +00001014#if 0
1015/* Keep an example of flags with future keyword support. */
1016#define PARSER_FLAGS(flags) \
1017 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1018 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1019 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1020 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
1021#endif
1022
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001023int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001024PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001025{
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001026 PyObject *m, *d, *v, *w, *oenc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001027 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001028 PyArena *arena;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001029 char *ps1 = "", *ps2 = "", *enc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001030 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001031
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001032 if (fp == stdin) {
1033 /* Fetch encoding from sys.stdin */
1034 v = PySys_GetObject("stdin");
Christian Heimes2be03732007-11-15 02:26:46 +00001035 if (v == NULL || v == Py_None)
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001036 return -1;
1037 oenc = PyObject_GetAttrString(v, "encoding");
1038 if (!oenc)
1039 return -1;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001040 enc = _PyUnicode_AsString(oenc);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001041 }
Guido van Rossum82598051997-03-05 00:20:32 +00001042 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001043 if (v != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001044 v = PyObject_Str(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001045 if (v == NULL)
1046 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +00001047 else if (PyUnicode_Check(v))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001048 ps1 = _PyUnicode_AsString(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001049 }
Guido van Rossum82598051997-03-05 00:20:32 +00001050 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001051 if (w != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001052 w = PyObject_Str(w);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001053 if (w == NULL)
1054 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +00001055 else if (PyUnicode_Check(w))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001056 ps2 = _PyUnicode_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001057 }
Neal Norwitz9589ee22006-03-04 19:01:22 +00001058 arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001059 if (arena == NULL) {
1060 Py_XDECREF(v);
1061 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001062 Py_XDECREF(oenc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001063 return -1;
1064 }
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001065 mod = PyParser_ASTFromFile(fp, filename, enc,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001066 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001067 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001068 Py_XDECREF(v);
1069 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001070 Py_XDECREF(oenc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001071 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001072 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073 if (errcode == E_EOF) {
1074 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001075 return E_EOF;
1076 }
Guido van Rossum82598051997-03-05 00:20:32 +00001077 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001078 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001079 }
Guido van Rossum82598051997-03-05 00:20:32 +00001080 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001081 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001082 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001083 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001084 }
Guido van Rossum82598051997-03-05 00:20:32 +00001085 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001086 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001087 PyArena_Free(arena);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001088 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001089 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001090 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001091 return -1;
1092 }
Guido van Rossum82598051997-03-05 00:20:32 +00001093 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001094 return 0;
1095}
1096
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001097/* Check whether a file maybe a pyc file: Look at the extension,
1098 the file type, and, if we may close it, at the first few bytes. */
1099
1100static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001101maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001102{
1103 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1104 return 1;
1105
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001106 /* Only look into the file if we are allowed to close it, since
1107 it then should also be seekable. */
1108 if (closeit) {
1109 /* Read only two bytes of the magic. If the file was opened in
1110 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1111 be read as they are on disk. */
1112 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1113 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +00001114 /* Mess: In case of -x, the stream is NOT at its start now,
1115 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001116 which makes the current stream position formally undefined,
1117 and a x-platform nightmare.
1118 Unfortunately, we have no direct way to know whether -x
1119 was specified. So we use a terrible hack: if the current
1120 stream position is not 0, we assume -x was specified, and
1121 give up. Bug 132850 on SourceForge spells out the
1122 hopelessness of trying anything else (fseek and ftell
1123 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +00001124 */
Tim Peters3e876562001-02-11 04:35:39 +00001125 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001126 if (ftell(fp) == 0) {
1127 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +00001128 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001129 ispyc = 1;
1130 rewind(fp);
1131 }
Tim Peters3e876562001-02-11 04:35:39 +00001132 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001133 }
1134 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001135}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001136
Guido van Rossum0df002c2000-08-27 19:21:52 +00001137int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001138PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001139 PyCompilerFlags *flags)
1140{
Guido van Rossum82598051997-03-05 00:20:32 +00001141 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001142 const char *ext;
Matthias Klose042f1332009-04-04 14:32:42 +00001143 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001144
Guido van Rossum82598051997-03-05 00:20:32 +00001145 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001146 if (m == NULL)
1147 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001148 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +00001149 if (PyDict_GetItemString(d, "__file__") == NULL) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001150 PyObject *f;
1151 f = PyUnicode_DecodeFSDefault(filename);
Fred Drake8ed02042002-10-17 21:24:58 +00001152 if (f == NULL)
1153 return -1;
1154 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1155 Py_DECREF(f);
1156 return -1;
1157 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001158 set_file_name = 1;
Fred Drake8ed02042002-10-17 21:24:58 +00001159 Py_DECREF(f);
1160 }
Matthias Klose042f1332009-04-04 14:32:42 +00001161 len = strlen(filename);
1162 ext = filename + len - (len > 4 ? 4 : 0);
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001163 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001164 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +00001165 if (closeit)
1166 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +00001167 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001168 fprintf(stderr, "python: Can't reopen .pyc file\n");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001169 ret = -1;
1170 goto done;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001171 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +00001172 /* Turn on optimization if a .pyo file is given */
1173 if (strcmp(ext, ".pyo") == 0)
1174 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001175 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001176 } else {
Tim Petersd08e3822003-04-17 15:24:21 +00001177 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001178 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001179 }
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001180 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001181 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001182 PyErr_Print();
Guido van Rossumd8faa362007-04-27 19:54:29 +00001183 ret = -1;
1184 goto done;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001185 }
Guido van Rossum82598051997-03-05 00:20:32 +00001186 Py_DECREF(v);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001187 ret = 0;
1188 done:
1189 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1190 PyErr_Clear();
1191 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001192}
1193
1194int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001195PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001196{
Guido van Rossum82598051997-03-05 00:20:32 +00001197 PyObject *m, *d, *v;
1198 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001199 if (m == NULL)
1200 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001201 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +00001202 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001203 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001204 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001205 return -1;
1206 }
Guido van Rossum82598051997-03-05 00:20:32 +00001207 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001208 return 0;
1209}
1210
Barry Warsaw035574d1997-08-29 22:07:17 +00001211static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001212parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1213 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001214{
1215 long hold;
1216 PyObject *v;
1217
1218 /* old style errors */
1219 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +00001220 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001221 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001222
1223 /* new style errors. `err' is an instance */
1224
1225 if (! (v = PyObject_GetAttrString(err, "msg")))
1226 goto finally;
1227 *message = v;
1228
1229 if (!(v = PyObject_GetAttrString(err, "filename")))
1230 goto finally;
1231 if (v == Py_None)
1232 *filename = NULL;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001233 else if (! (*filename = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001234 goto finally;
1235
1236 Py_DECREF(v);
1237 if (!(v = PyObject_GetAttrString(err, "lineno")))
1238 goto finally;
Christian Heimes217cfd12007-12-02 14:31:20 +00001239 hold = PyLong_AsLong(v);
Barry Warsaw035574d1997-08-29 22:07:17 +00001240 Py_DECREF(v);
1241 v = NULL;
1242 if (hold < 0 && PyErr_Occurred())
1243 goto finally;
1244 *lineno = (int)hold;
1245
1246 if (!(v = PyObject_GetAttrString(err, "offset")))
1247 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001248 if (v == Py_None) {
1249 *offset = -1;
1250 Py_DECREF(v);
1251 v = NULL;
1252 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001253 hold = PyLong_AsLong(v);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001254 Py_DECREF(v);
1255 v = NULL;
1256 if (hold < 0 && PyErr_Occurred())
1257 goto finally;
1258 *offset = (int)hold;
1259 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001260
1261 if (!(v = PyObject_GetAttrString(err, "text")))
1262 goto finally;
1263 if (v == Py_None)
1264 *text = NULL;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001265 else if (!PyUnicode_Check(v) ||
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001266 !(*text = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001267 goto finally;
1268 Py_DECREF(v);
1269 return 1;
1270
1271finally:
1272 Py_XDECREF(v);
1273 return 0;
1274}
1275
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001276void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001277PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001278{
Guido van Rossuma61691e1998-02-06 22:27:24 +00001279 PyErr_PrintEx(1);
1280}
1281
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001282static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001283print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001284{
1285 char *nl;
1286 if (offset >= 0) {
1287 if (offset > 0 && offset == (int)strlen(text))
1288 offset--;
1289 for (;;) {
1290 nl = strchr(text, '\n');
1291 if (nl == NULL || nl-text >= offset)
1292 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001293 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001294 text = nl+1;
1295 }
1296 while (*text == ' ' || *text == '\t') {
1297 text++;
1298 offset--;
1299 }
1300 }
1301 PyFile_WriteString(" ", f);
1302 PyFile_WriteString(text, f);
1303 if (*text == '\0' || text[strlen(text)-1] != '\n')
1304 PyFile_WriteString("\n", f);
1305 if (offset == -1)
1306 return;
1307 PyFile_WriteString(" ", f);
1308 offset--;
1309 while (offset > 0) {
1310 PyFile_WriteString(" ", f);
1311 offset--;
1312 }
1313 PyFile_WriteString("^\n", f);
1314}
1315
Guido van Rossum66e8e862001-03-23 17:54:43 +00001316static void
1317handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001318{
Neal Norwitz9589ee22006-03-04 19:01:22 +00001319 PyObject *exception, *value, *tb;
1320 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001321
Guido van Rossumd8faa362007-04-27 19:54:29 +00001322 if (Py_InspectFlag)
1323 /* Don't exit if -i flag was given. This flag is set to 0
1324 * when entering interactive mode for inspecting. */
1325 return;
1326
Guido van Rossum66e8e862001-03-23 17:54:43 +00001327 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001328 fflush(stdout);
1329 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001330 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001331 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001332 /* The error code should be in the `code' attribute. */
1333 PyObject *code = PyObject_GetAttrString(value, "code");
1334 if (code) {
1335 Py_DECREF(value);
1336 value = code;
1337 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001338 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001339 }
1340 /* If we failed to dig out the 'code' attribute,
1341 just let the else clause below print the error. */
1342 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001343 if (PyLong_Check(value))
1344 exitcode = (int)PyLong_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001345 else {
1346 PyObject_Print(value, stderr, Py_PRINT_RAW);
1347 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001348 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001349 }
Tim Peterscf615b52003-04-19 18:47:02 +00001350 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001351 /* Restore and clear the exception info, in order to properly decref
1352 * the exception, value, and traceback. If we just exit instead,
1353 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1354 * some finalizers from running.
1355 */
Tim Peterscf615b52003-04-19 18:47:02 +00001356 PyErr_Restore(exception, value, tb);
1357 PyErr_Clear();
1358 Py_Exit(exitcode);
1359 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001360}
1361
1362void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001363PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001364{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001365 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001366
1367 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1368 handle_system_exit();
1369 }
Guido van Rossum82598051997-03-05 00:20:32 +00001370 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001371 if (exception == NULL)
1372 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001373 PyErr_NormalizeException(&exception, &v, &tb);
Antoine Pitroue2dffc02008-08-26 22:02:58 +00001374 if (tb == NULL) {
1375 tb = Py_None;
1376 Py_INCREF(tb);
1377 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001378 PyException_SetTraceback(v, tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001379 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001380 return;
Georg Brandl86b2fb92008-07-16 03:43:04 +00001381 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001382 if (set_sys_last_vars) {
1383 PySys_SetObject("last_type", exception);
1384 PySys_SetObject("last_value", v);
Benjamin Petersone6528212008-07-15 15:32:09 +00001385 PySys_SetObject("last_traceback", tb);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001386 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001387 hook = PySys_GetObject("excepthook");
1388 if (hook) {
Benjamin Petersone6528212008-07-15 15:32:09 +00001389 PyObject *args = PyTuple_Pack(3, exception, v, tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001390 PyObject *result = PyEval_CallObject(hook, args);
1391 if (result == NULL) {
1392 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001393 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1394 handle_system_exit();
1395 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001396 PyErr_Fetch(&exception2, &v2, &tb2);
1397 PyErr_NormalizeException(&exception2, &v2, &tb2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001398 /* It should not be possible for exception2 or v2
1399 to be NULL. However PyErr_Display() can't
1400 tolerate NULLs, so just be safe. */
1401 if (exception2 == NULL) {
1402 exception2 = Py_None;
1403 Py_INCREF(exception2);
1404 }
1405 if (v2 == NULL) {
1406 v2 = Py_None;
1407 Py_INCREF(v2);
1408 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001409 fflush(stdout);
1410 PySys_WriteStderr("Error in sys.excepthook:\n");
1411 PyErr_Display(exception2, v2, tb2);
1412 PySys_WriteStderr("\nOriginal exception was:\n");
1413 PyErr_Display(exception, v, tb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001414 Py_DECREF(exception2);
1415 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001416 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001417 }
1418 Py_XDECREF(result);
1419 Py_XDECREF(args);
1420 } else {
1421 PySys_WriteStderr("sys.excepthook is missing\n");
1422 PyErr_Display(exception, v, tb);
1423 }
1424 Py_XDECREF(exception);
1425 Py_XDECREF(v);
1426 Py_XDECREF(tb);
1427}
1428
Benjamin Petersone6528212008-07-15 15:32:09 +00001429static void
1430print_exception(PyObject *f, PyObject *value)
1431{
1432 int err = 0;
1433 PyObject *type, *tb;
1434
Benjamin Peterson26582602008-08-23 20:08:07 +00001435 if (!PyExceptionInstance_Check(value)) {
1436 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1437 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1438 PyFile_WriteString(" found\n", f);
1439 return;
1440 }
1441
Benjamin Petersone6528212008-07-15 15:32:09 +00001442 Py_INCREF(value);
1443 fflush(stdout);
1444 type = (PyObject *) Py_TYPE(value);
1445 tb = PyException_GetTraceback(value);
1446 if (tb && tb != Py_None)
1447 err = PyTraceBack_Print(tb, f);
1448 if (err == 0 &&
1449 PyObject_HasAttrString(value, "print_file_and_line"))
1450 {
1451 PyObject *message;
1452 const char *filename, *text;
1453 int lineno, offset;
1454 if (!parse_syntax_error(value, &message, &filename,
1455 &lineno, &offset, &text))
1456 PyErr_Clear();
1457 else {
1458 char buf[10];
1459 PyFile_WriteString(" File \"", f);
1460 if (filename == NULL)
1461 PyFile_WriteString("<string>", f);
1462 else
1463 PyFile_WriteString(filename, f);
1464 PyFile_WriteString("\", line ", f);
1465 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1466 PyFile_WriteString(buf, f);
1467 PyFile_WriteString("\n", f);
1468 if (text != NULL)
1469 print_error_text(f, offset, text);
1470 Py_DECREF(value);
1471 value = message;
1472 /* Can't be bothered to check all those
1473 PyFile_WriteString() calls */
1474 if (PyErr_Occurred())
1475 err = -1;
1476 }
1477 }
1478 if (err) {
1479 /* Don't do anything else */
1480 }
1481 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001482 PyObject* moduleName;
Thomas Hellerd88ddfa2008-07-15 17:14:51 +00001483 char* className;
1484 assert(PyExceptionClass_Check(type));
1485 className = PyExceptionClass_Name(type);
Benjamin Petersone6528212008-07-15 15:32:09 +00001486 if (className != NULL) {
1487 char *dot = strrchr(className, '.');
1488 if (dot != NULL)
1489 className = dot+1;
1490 }
1491
1492 moduleName = PyObject_GetAttrString(type, "__module__");
1493 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1494 {
1495 Py_DECREF(moduleName);
1496 err = PyFile_WriteString("<unknown>", f);
1497 }
1498 else {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001499 char* modstr = _PyUnicode_AsString(moduleName);
Benjamin Petersone6528212008-07-15 15:32:09 +00001500 if (modstr && strcmp(modstr, "builtins"))
1501 {
1502 err = PyFile_WriteString(modstr, f);
1503 err += PyFile_WriteString(".", f);
1504 }
1505 Py_DECREF(moduleName);
1506 }
1507 if (err == 0) {
1508 if (className == NULL)
1509 err = PyFile_WriteString("<unknown>", f);
1510 else
1511 err = PyFile_WriteString(className, f);
1512 }
1513 }
1514 if (err == 0 && (value != Py_None)) {
1515 PyObject *s = PyObject_Str(value);
1516 /* only print colon if the str() of the
1517 object is not the empty string
1518 */
1519 if (s == NULL)
1520 err = -1;
1521 else if (!PyUnicode_Check(s) ||
1522 PyUnicode_GetSize(s) != 0)
1523 err = PyFile_WriteString(": ", f);
1524 if (err == 0)
1525 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1526 Py_XDECREF(s);
1527 }
1528 /* try to write a newline in any case */
1529 err += PyFile_WriteString("\n", f);
1530 Py_XDECREF(tb);
1531 Py_DECREF(value);
1532 /* If an error happened here, don't show it.
1533 XXX This is wrong, but too many callers rely on this behavior. */
1534 if (err != 0)
1535 PyErr_Clear();
1536}
1537
1538static const char *cause_message =
1539 "\nThe above exception was the direct cause "
1540 "of the following exception:\n\n";
1541
1542static const char *context_message =
1543 "\nDuring handling of the above exception, "
1544 "another exception occurred:\n\n";
1545
1546static void
1547print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1548{
1549 int err = 0, res;
1550 PyObject *cause, *context;
1551
1552 if (seen != NULL) {
1553 /* Exception chaining */
1554 if (PySet_Add(seen, value) == -1)
1555 PyErr_Clear();
1556 else if (PyExceptionInstance_Check(value)) {
1557 cause = PyException_GetCause(value);
1558 context = PyException_GetContext(value);
1559 if (cause) {
1560 res = PySet_Contains(seen, cause);
1561 if (res == -1)
1562 PyErr_Clear();
1563 if (res == 0) {
1564 print_exception_recursive(
1565 f, cause, seen);
1566 err |= PyFile_WriteString(
1567 cause_message, f);
1568 }
1569 }
Antoine Pitrou7b0d4a22009-11-28 16:12:28 +00001570 else if (context) {
Benjamin Petersone6528212008-07-15 15:32:09 +00001571 res = PySet_Contains(seen, context);
1572 if (res == -1)
1573 PyErr_Clear();
1574 if (res == 0) {
1575 print_exception_recursive(
1576 f, context, seen);
1577 err |= PyFile_WriteString(
1578 context_message, f);
1579 }
1580 }
1581 Py_XDECREF(context);
1582 Py_XDECREF(cause);
1583 }
1584 }
1585 print_exception(f, value);
1586 if (err != 0)
1587 PyErr_Clear();
1588}
1589
Thomas Wouters477c8d52006-05-27 19:21:47 +00001590void
1591PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001592{
Benjamin Petersone6528212008-07-15 15:32:09 +00001593 PyObject *seen;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001594 PyObject *f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +00001595 if (f == Py_None) {
1596 /* pass */
1597 }
1598 else if (f == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001599 _PyObject_Dump(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001600 fprintf(stderr, "lost sys.stderr\n");
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001601 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001602 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001603 /* We choose to ignore seen being possibly NULL, and report
1604 at least the main exception (it could be a MemoryError).
1605 */
1606 seen = PySet_New(NULL);
1607 if (seen == NULL)
1608 PyErr_Clear();
1609 print_exception_recursive(f, value, seen);
1610 Py_XDECREF(seen);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001611 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001612}
1613
Guido van Rossum82598051997-03-05 00:20:32 +00001614PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001615PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001616 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001617{
Neal Norwitze92fba02006-03-04 18:52:26 +00001618 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001619 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001620 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001621 if (arena == NULL)
1622 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001623
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001624 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001625 if (mod != NULL)
1626 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001627 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001628 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001629}
1630
1631PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001632PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001633 PyObject *locals, int closeit, PyCompilerFlags *flags)
1634{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001635 PyObject *ret;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001636 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001637 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001638 if (arena == NULL)
1639 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001640
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001641 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001642 flags, NULL, arena);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001643 if (closeit)
1644 fclose(fp);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001645 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001646 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001647 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001648 }
Neal Norwitze92fba02006-03-04 18:52:26 +00001649 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001650 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001651 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001652}
1653
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001654static void
1655flush_io(void)
1656{
1657 PyObject *f, *r;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001658 PyObject *type, *value, *traceback;
1659
1660 /* Save the current exception */
1661 PyErr_Fetch(&type, &value, &traceback);
1662
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001663 f = PySys_GetObject("stderr");
1664 if (f != NULL) {
1665 r = PyObject_CallMethod(f, "flush", "");
1666 if (r)
1667 Py_DECREF(r);
1668 else
1669 PyErr_Clear();
1670 }
1671 f = PySys_GetObject("stdout");
1672 if (f != NULL) {
1673 r = PyObject_CallMethod(f, "flush", "");
1674 if (r)
1675 Py_DECREF(r);
1676 else
1677 PyErr_Clear();
1678 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001679
1680 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001681}
1682
Guido van Rossum82598051997-03-05 00:20:32 +00001683static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001684run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001685 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001686{
Guido van Rossum82598051997-03-05 00:20:32 +00001687 PyCodeObject *co;
1688 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001689 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001690 if (co == NULL)
1691 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001692 v = PyEval_EvalCode(co, globals, locals);
1693 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001694 return v;
1695}
1696
Guido van Rossum82598051997-03-05 00:20:32 +00001697static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001698run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001699 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001700{
Guido van Rossum82598051997-03-05 00:20:32 +00001701 PyCodeObject *co;
1702 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001703 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001704 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001705
Guido van Rossum82598051997-03-05 00:20:32 +00001706 magic = PyMarshal_ReadLongFromFile(fp);
1707 if (magic != PyImport_GetMagicNumber()) {
1708 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001709 "Bad magic number in .pyc file");
1710 return NULL;
1711 }
Guido van Rossum82598051997-03-05 00:20:32 +00001712 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001713 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001714 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001715 if (v == NULL || !PyCode_Check(v)) {
1716 Py_XDECREF(v);
1717 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001718 "Bad code object in .pyc file");
1719 return NULL;
1720 }
Guido van Rossum82598051997-03-05 00:20:32 +00001721 co = (PyCodeObject *)v;
1722 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001723 if (v && flags)
1724 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001725 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001726 return v;
1727}
1728
Guido van Rossum82598051997-03-05 00:20:32 +00001729PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001730Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001731 PyCompilerFlags *flags)
1732{
Guido van Rossum82598051997-03-05 00:20:32 +00001733 PyCodeObject *co;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001734 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001735 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001736 if (arena == NULL)
1737 return NULL;
1738
1739 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001740 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001741 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001742 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001743 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001744 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001745 PyObject *result = PyAST_mod2obj(mod);
1746 PyArena_Free(arena);
1747 return result;
1748 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001749 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001750 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001751 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001752}
1753
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001754struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001755Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001756{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001757 struct symtable *st;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001758 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001759 PyCompilerFlags flags;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001760 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001761 if (arena == NULL)
1762 return NULL;
1763
Christian Heimesb1b3efc2008-03-26 23:24:27 +00001764 flags.cf_flags = 0;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001765 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001766 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001767 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001768 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001769 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001770 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001771 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001772 return st;
1773}
1774
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001775/* Preferred access to parser is through AST. */
1776mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001777PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001778 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001779{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001780 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001781 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001783 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001784
1785 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001786 &_PyParser_Grammar, start, &err,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001787 &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001788 if (flags == NULL) {
1789 localflags.cf_flags = 0;
1790 flags = &localflags;
1791 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001792 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001793 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001794 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001795 PyNode_Free(n);
1796 return mod;
1797 }
1798 else {
1799 err_input(&err);
1800 return NULL;
1801 }
1802}
1803
1804mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001805PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1806 int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001807 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001808 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001809{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001810 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001811 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001812 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001813 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001814
Christian Heimes4d6ec852008-03-26 22:34:47 +00001815 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001816 &_PyParser_Grammar,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001817 start, ps1, ps2, &err, &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001818 if (flags == NULL) {
1819 localflags.cf_flags = 0;
1820 flags = &localflags;
1821 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001822 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001823 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001824 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001825 PyNode_Free(n);
1826 return mod;
1827 }
1828 else {
1829 err_input(&err);
1830 if (errcode)
1831 *errcode = err.error;
1832 return NULL;
1833 }
1834}
1835
Guido van Rossuma110aa61994-08-29 12:50:44 +00001836/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001837
Guido van Rossuma110aa61994-08-29 12:50:44 +00001838node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001839PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001840{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001841 perrdetail err;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001842 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1843 &_PyParser_Grammar,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001844 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001845 if (n == NULL)
1846 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001847
Guido van Rossuma110aa61994-08-29 12:50:44 +00001848 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001849}
1850
Guido van Rossuma110aa61994-08-29 12:50:44 +00001851/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001852
Guido van Rossuma110aa61994-08-29 12:50:44 +00001853node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001854PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001855{
Tim Petersfe2127d2001-07-16 05:37:24 +00001856 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001857 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1858 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001859 if (n == NULL)
1860 err_input(&err);
1861 return n;
1862}
1863
1864node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001865PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001866 int start, int flags)
1867{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001868 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001869 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1870 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001871 if (n == NULL)
1872 err_input(&err);
1873 return n;
1874}
1875
1876node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001877PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001878{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001879 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001880}
1881
Guido van Rossum66ebd912003-04-17 16:02:26 +00001882/* May want to move a more generalized form of this to parsetok.c or
1883 even parser modules. */
1884
1885void
1886PyParser_SetError(perrdetail *err)
1887{
1888 err_input(err);
1889}
1890
Guido van Rossuma110aa61994-08-29 12:50:44 +00001891/* Set the error appropriate to the given input error code (see errcode.h) */
1892
1893static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001894err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001895{
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001896 PyObject *v, *w, *errtype, *errtext;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001897 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001898 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001899 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001900 switch (err->error) {
Victor Stinner52f6dd72010-03-12 14:45:56 +00001901 case E_ERROR:
1902 return;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001903 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001904 errtype = PyExc_IndentationError;
1905 if (err->expected == INDENT)
1906 msg = "expected an indented block";
1907 else if (err->token == INDENT)
1908 msg = "unexpected indent";
1909 else if (err->token == DEDENT)
1910 msg = "unexpected unindent";
1911 else {
1912 errtype = PyExc_SyntaxError;
1913 msg = "invalid syntax";
1914 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001915 break;
1916 case E_TOKEN:
1917 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001918 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001919 case E_EOFS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001920 msg = "EOF while scanning triple-quoted string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001921 break;
1922 case E_EOLS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001923 msg = "EOL while scanning string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001924 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001925 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001926 if (!PyErr_Occurred())
1927 PyErr_SetNone(PyExc_KeyboardInterrupt);
Georg Brandl3dbca812008-07-23 16:10:53 +00001928 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001929 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001930 PyErr_NoMemory();
Georg Brandl3dbca812008-07-23 16:10:53 +00001931 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001932 case E_EOF:
1933 msg = "unexpected EOF while parsing";
1934 break;
Fred Drake85f36392000-07-11 17:53:00 +00001935 case E_TABSPACE:
1936 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001937 msg = "inconsistent use of tabs and spaces in indentation";
1938 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001939 case E_OVERFLOW:
1940 msg = "expression too long";
1941 break;
Fred Drake85f36392000-07-11 17:53:00 +00001942 case E_DEDENT:
1943 errtype = PyExc_IndentationError;
1944 msg = "unindent does not match any outer indentation level";
1945 break;
1946 case E_TOODEEP:
1947 errtype = PyExc_IndentationError;
1948 msg = "too many levels of indentation";
1949 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001950 case E_DECODE: {
1951 PyObject *type, *value, *tb;
1952 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001953 if (value != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001954 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001955 if (u != NULL) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001956 msg = _PyUnicode_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001957 }
1958 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001959 if (msg == NULL)
1960 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001961 Py_XDECREF(type);
1962 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001963 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001964 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001965 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001966 case E_LINECONT:
1967 msg = "unexpected character after line continuation character";
1968 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001969
1970 case E_IDENTIFIER:
1971 msg = "invalid character in identifier";
1972 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001973 default:
1974 fprintf(stderr, "error=%d\n", err->error);
1975 msg = "unknown parsing error";
1976 break;
1977 }
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001978 /* err->text may not be UTF-8 in case of decoding errors.
1979 Explicitly convert to an object. */
1980 if (!err->text) {
1981 errtext = Py_None;
1982 Py_INCREF(Py_None);
1983 } else {
1984 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1985 "replace");
1986 }
1987 v = Py_BuildValue("(ziiN)", err->filename,
1988 err->lineno, err->offset, errtext);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001989 w = NULL;
1990 if (v != NULL)
1991 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001992 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001993 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001994 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001995 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00001996cleanup:
1997 if (err->text != NULL) {
1998 PyObject_FREE(err->text);
1999 err->text = NULL;
2000 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002001}
2002
2003/* Print fatal error message and abort */
2004
2005void
Tim Peters7c321a82002-07-09 02:57:01 +00002006Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002007{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00002008 fprintf(stderr, "Fatal Python error: %s\n", msg);
Jesse Nollera9314042009-03-31 22:36:44 +00002009 fflush(stderr); /* it helps in Windows debug build */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00002010 if (PyErr_Occurred()) {
2011 PyErr_Print();
2012 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002013#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002014 {
2015 size_t len = strlen(msg);
2016 WCHAR* buffer;
2017 size_t i;
2018
2019 /* Convert the message to wchar_t. This uses a simple one-to-one
2020 conversion, assuming that the this error message actually uses ASCII
2021 only. If this ceases to be true, we will have to convert. */
2022 buffer = alloca( (len+1) * (sizeof *buffer));
2023 for( i=0; i<=len; ++i)
2024 buffer[i] = msg[i];
2025 OutputDebugStringW(L"Fatal Python error: ");
2026 OutputDebugStringW(buffer);
2027 OutputDebugStringW(L"\n");
2028 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002029#ifdef _DEBUG
2030 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002031#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002032#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002033 abort();
2034}
2035
2036/* Clean up and exit */
2037
Guido van Rossuma110aa61994-08-29 12:50:44 +00002038#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002039#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002040#endif
2041
Collin Winter670e6922007-03-21 02:57:17 +00002042static void (*pyexitfunc)(void) = NULL;
2043/* For the atexit module. */
2044void _Py_PyAtExit(void (*func)(void))
2045{
2046 pyexitfunc = func;
2047}
2048
2049static void
2050call_py_exitfuncs(void)
2051{
Guido van Rossum98297ee2007-11-06 21:34:58 +00002052 if (pyexitfunc == NULL)
Collin Winter670e6922007-03-21 02:57:17 +00002053 return;
2054
2055 (*pyexitfunc)();
2056 PyErr_Clear();
2057}
2058
Antoine Pitrou011bd622009-10-20 21:52:47 +00002059/* Wait until threading._shutdown completes, provided
2060 the threading module was imported in the first place.
2061 The shutdown routine will wait until all non-daemon
2062 "threading" threads have completed. */
2063static void
2064wait_for_thread_shutdown(void)
2065{
2066#ifdef WITH_THREAD
2067 PyObject *result;
2068 PyThreadState *tstate = PyThreadState_GET();
2069 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2070 "threading");
2071 if (threading == NULL) {
2072 /* threading not imported */
2073 PyErr_Clear();
2074 return;
2075 }
2076 result = PyObject_CallMethod(threading, "_shutdown", "");
2077 if (result == NULL) {
2078 PyErr_WriteUnraisable(threading);
2079 }
2080 else {
2081 Py_DECREF(result);
2082 }
2083 Py_DECREF(threading);
2084#endif
2085}
2086
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002087#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002088static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002089static int nexitfuncs = 0;
2090
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002091int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002092{
2093 if (nexitfuncs >= NEXITFUNCS)
2094 return -1;
2095 exitfuncs[nexitfuncs++] = func;
2096 return 0;
2097}
2098
Guido van Rossumcc283f51997-08-05 02:22:03 +00002099static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002100call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002101{
Guido van Rossum1662dd51994-09-07 14:38:28 +00002102 while (nexitfuncs > 0)
2103 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002104
2105 fflush(stdout);
2106 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002107}
2108
2109void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002110Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002111{
Guido van Rossumcc283f51997-08-05 02:22:03 +00002112 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002113
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002114 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002115}
2116
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002117static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002118initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002119{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002120#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002121 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002122#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002123#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002124 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002125#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002126#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002127 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002128#endif
Guido van Rossum82598051997-03-05 00:20:32 +00002129 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002130}
2131
Guido van Rossum7433b121997-02-14 19:45:36 +00002132
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002133/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2134 *
2135 * All of the code in this function must only use async-signal-safe functions,
2136 * listed at `man 7 signal` or
2137 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2138 */
2139void
2140_Py_RestoreSignals(void)
2141{
2142#ifdef SIGPIPE
2143 PyOS_setsig(SIGPIPE, SIG_DFL);
2144#endif
2145#ifdef SIGXFZ
2146 PyOS_setsig(SIGXFZ, SIG_DFL);
2147#endif
2148#ifdef SIGXFSZ
2149 PyOS_setsig(SIGXFSZ, SIG_DFL);
2150#endif
2151}
2152
2153
Guido van Rossum7433b121997-02-14 19:45:36 +00002154/*
2155 * The file descriptor fd is considered ``interactive'' if either
2156 * a) isatty(fd) is TRUE, or
2157 * b) the -i flag was given, and the filename associated with
2158 * the descriptor is NULL or "<stdin>" or "???".
2159 */
2160int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002161Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002162{
2163 if (isatty((int)fileno(fp)))
2164 return 1;
2165 if (!Py_InteractiveFlag)
2166 return 0;
2167 return (filename == NULL) ||
2168 (strcmp(filename, "<stdin>") == 0) ||
2169 (strcmp(filename, "???") == 0);
2170}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002171
2172
Tim Petersd08e3822003-04-17 15:24:21 +00002173#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002174#if defined(WIN32) && defined(_MSC_VER)
2175
2176/* Stack checking for Microsoft C */
2177
2178#include <malloc.h>
2179#include <excpt.h>
2180
Fred Drakee8de31c2000-08-31 05:38:39 +00002181/*
2182 * Return non-zero when we run out of memory on the stack; zero otherwise.
2183 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002184int
Fred Drake399739f2000-08-31 05:52:44 +00002185PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002186{
2187 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00002188 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002189 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00002190 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002191 return 0;
Christian Heimes7131fd92008-02-19 14:21:46 +00002192 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
Trent Nelson39e307e2008-03-19 06:45:48 +00002193 EXCEPTION_EXECUTE_HANDLER :
2194 EXCEPTION_CONTINUE_SEARCH) {
Christian Heimes7131fd92008-02-19 14:21:46 +00002195 int errcode = _resetstkoflw();
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +00002196 if (errcode == 0)
Christian Heimes7131fd92008-02-19 14:21:46 +00002197 {
2198 Py_FatalError("Could not reset the stack!");
2199 }
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002200 }
2201 return 1;
2202}
2203
2204#endif /* WIN32 && _MSC_VER */
2205
2206/* Alternate implementations can be added here... */
2207
2208#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002209
2210
2211/* Wrappers around sigaction() or signal(). */
2212
2213PyOS_sighandler_t
2214PyOS_getsig(int sig)
2215{
2216#ifdef HAVE_SIGACTION
2217 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002218 if (sigaction(sig, NULL, &context) == -1)
2219 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00002220 return context.sa_handler;
2221#else
2222 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002223/* Special signal handling for the secure CRT in Visual Studio 2005 */
2224#if defined(_MSC_VER) && _MSC_VER >= 1400
2225 switch (sig) {
2226 /* Only these signals are valid */
2227 case SIGINT:
2228 case SIGILL:
2229 case SIGFPE:
2230 case SIGSEGV:
2231 case SIGTERM:
2232 case SIGBREAK:
2233 case SIGABRT:
2234 break;
2235 /* Don't call signal() with other values or it will assert */
2236 default:
2237 return SIG_ERR;
2238 }
2239#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002240 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002241 if (handler != SIG_ERR)
2242 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00002243 return handler;
2244#endif
2245}
2246
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002247/*
2248 * All of the code in this function must only use async-signal-safe functions,
2249 * listed at `man 7 signal` or
2250 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2251 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002252PyOS_sighandler_t
2253PyOS_setsig(int sig, PyOS_sighandler_t handler)
2254{
2255#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002256 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00002257 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002258 sigemptyset(&context.sa_mask);
2259 context.sa_flags = 0;
2260 if (sigaction(sig, &context, &ocontext) == -1)
2261 return SIG_ERR;
2262 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002263#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002264 PyOS_sighandler_t oldhandler;
2265 oldhandler = signal(sig, handler);
2266#ifdef HAVE_SIGINTERRUPT
2267 siginterrupt(sig, 1);
2268#endif
2269 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002270#endif
2271}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002272
2273/* Deprecated C API functions still provided for binary compatiblity */
2274
2275#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002276PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002277PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2278{
2279 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2280}
2281
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002282#undef PyParser_SimpleParseString
2283PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002284PyParser_SimpleParseString(const char *str, int start)
2285{
2286 return PyParser_SimpleParseStringFlags(str, start, 0);
2287}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002288
2289#undef PyRun_AnyFile
2290PyAPI_FUNC(int)
2291PyRun_AnyFile(FILE *fp, const char *name)
2292{
2293 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
2294}
2295
2296#undef PyRun_AnyFileEx
2297PyAPI_FUNC(int)
2298PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2299{
2300 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
2301}
2302
2303#undef PyRun_AnyFileFlags
2304PyAPI_FUNC(int)
2305PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2306{
2307 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2308}
2309
2310#undef PyRun_File
2311PyAPI_FUNC(PyObject *)
2312PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2313{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002314 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002315}
2316
2317#undef PyRun_FileEx
2318PyAPI_FUNC(PyObject *)
2319PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2320{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002321 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002322}
2323
2324#undef PyRun_FileFlags
2325PyAPI_FUNC(PyObject *)
2326PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2327 PyCompilerFlags *flags)
2328{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002329 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002330}
2331
2332#undef PyRun_SimpleFile
2333PyAPI_FUNC(int)
2334PyRun_SimpleFile(FILE *f, const char *p)
2335{
2336 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
2337}
2338
2339#undef PyRun_SimpleFileEx
2340PyAPI_FUNC(int)
2341PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2342{
2343 return PyRun_SimpleFileExFlags(f, p, c, NULL);
2344}
2345
2346
2347#undef PyRun_String
2348PyAPI_FUNC(PyObject *)
2349PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2350{
2351 return PyRun_StringFlags(str, s, g, l, NULL);
2352}
2353
2354#undef PyRun_SimpleString
2355PyAPI_FUNC(int)
2356PyRun_SimpleString(const char *s)
2357{
2358 return PyRun_SimpleStringFlags(s, NULL);
2359}
2360
2361#undef Py_CompileString
2362PyAPI_FUNC(PyObject *)
2363Py_CompileString(const char *str, const char *p, int s)
2364{
2365 return Py_CompileStringFlags(str, p, s, NULL);
2366}
2367
2368#undef PyRun_InteractiveOne
2369PyAPI_FUNC(int)
2370PyRun_InteractiveOne(FILE *f, const char *p)
2371{
2372 return PyRun_InteractiveOneFlags(f, p, NULL);
2373}
2374
2375#undef PyRun_InteractiveLoop
2376PyAPI_FUNC(int)
2377PyRun_InteractiveLoop(FILE *f, const char *p)
2378{
2379 return PyRun_InteractiveLoopFlags(f, p, NULL);
2380}
2381
2382#ifdef __cplusplus
2383}
2384#endif