blob: cc617be4d11ffce9535ae81e37d0463f45a91aac [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 }
Barry Warsaw28a691b2010-04-17 00:19:56 +00001158 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0)
1159 return -1;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001160 set_file_name = 1;
Fred Drake8ed02042002-10-17 21:24:58 +00001161 Py_DECREF(f);
1162 }
Matthias Klose042f1332009-04-04 14:32:42 +00001163 len = strlen(filename);
1164 ext = filename + len - (len > 4 ? 4 : 0);
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001165 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001166 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +00001167 if (closeit)
1168 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +00001169 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001170 fprintf(stderr, "python: Can't reopen .pyc file\n");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001171 ret = -1;
1172 goto done;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001173 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +00001174 /* Turn on optimization if a .pyo file is given */
1175 if (strcmp(ext, ".pyo") == 0)
1176 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001177 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001178 } else {
Tim Petersd08e3822003-04-17 15:24:21 +00001179 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001180 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001181 }
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001182 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001183 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001184 PyErr_Print();
Guido van Rossumd8faa362007-04-27 19:54:29 +00001185 ret = -1;
1186 goto done;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001187 }
Guido van Rossum82598051997-03-05 00:20:32 +00001188 Py_DECREF(v);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001189 ret = 0;
1190 done:
1191 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1192 PyErr_Clear();
1193 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001194}
1195
1196int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001197PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001198{
Guido van Rossum82598051997-03-05 00:20:32 +00001199 PyObject *m, *d, *v;
1200 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001201 if (m == NULL)
1202 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001203 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +00001204 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001205 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001206 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001207 return -1;
1208 }
Guido van Rossum82598051997-03-05 00:20:32 +00001209 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001210 return 0;
1211}
1212
Barry Warsaw035574d1997-08-29 22:07:17 +00001213static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001214parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1215 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001216{
1217 long hold;
1218 PyObject *v;
1219
1220 /* old style errors */
1221 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +00001222 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001223 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001224
1225 /* new style errors. `err' is an instance */
1226
1227 if (! (v = PyObject_GetAttrString(err, "msg")))
1228 goto finally;
1229 *message = v;
1230
1231 if (!(v = PyObject_GetAttrString(err, "filename")))
1232 goto finally;
1233 if (v == Py_None)
1234 *filename = NULL;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001235 else if (! (*filename = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001236 goto finally;
1237
1238 Py_DECREF(v);
1239 if (!(v = PyObject_GetAttrString(err, "lineno")))
1240 goto finally;
Christian Heimes217cfd12007-12-02 14:31:20 +00001241 hold = PyLong_AsLong(v);
Barry Warsaw035574d1997-08-29 22:07:17 +00001242 Py_DECREF(v);
1243 v = NULL;
1244 if (hold < 0 && PyErr_Occurred())
1245 goto finally;
1246 *lineno = (int)hold;
1247
1248 if (!(v = PyObject_GetAttrString(err, "offset")))
1249 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001250 if (v == Py_None) {
1251 *offset = -1;
1252 Py_DECREF(v);
1253 v = NULL;
1254 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001255 hold = PyLong_AsLong(v);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001256 Py_DECREF(v);
1257 v = NULL;
1258 if (hold < 0 && PyErr_Occurred())
1259 goto finally;
1260 *offset = (int)hold;
1261 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001262
1263 if (!(v = PyObject_GetAttrString(err, "text")))
1264 goto finally;
1265 if (v == Py_None)
1266 *text = NULL;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001267 else if (!PyUnicode_Check(v) ||
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001268 !(*text = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001269 goto finally;
1270 Py_DECREF(v);
1271 return 1;
1272
1273finally:
1274 Py_XDECREF(v);
1275 return 0;
1276}
1277
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001278void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001279PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001280{
Guido van Rossuma61691e1998-02-06 22:27:24 +00001281 PyErr_PrintEx(1);
1282}
1283
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001284static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001285print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001286{
1287 char *nl;
1288 if (offset >= 0) {
1289 if (offset > 0 && offset == (int)strlen(text))
1290 offset--;
1291 for (;;) {
1292 nl = strchr(text, '\n');
1293 if (nl == NULL || nl-text >= offset)
1294 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001295 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001296 text = nl+1;
1297 }
1298 while (*text == ' ' || *text == '\t') {
1299 text++;
1300 offset--;
1301 }
1302 }
1303 PyFile_WriteString(" ", f);
1304 PyFile_WriteString(text, f);
1305 if (*text == '\0' || text[strlen(text)-1] != '\n')
1306 PyFile_WriteString("\n", f);
1307 if (offset == -1)
1308 return;
1309 PyFile_WriteString(" ", f);
1310 offset--;
1311 while (offset > 0) {
1312 PyFile_WriteString(" ", f);
1313 offset--;
1314 }
1315 PyFile_WriteString("^\n", f);
1316}
1317
Guido van Rossum66e8e862001-03-23 17:54:43 +00001318static void
1319handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001320{
Neal Norwitz9589ee22006-03-04 19:01:22 +00001321 PyObject *exception, *value, *tb;
1322 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001323
Guido van Rossumd8faa362007-04-27 19:54:29 +00001324 if (Py_InspectFlag)
1325 /* Don't exit if -i flag was given. This flag is set to 0
1326 * when entering interactive mode for inspecting. */
1327 return;
1328
Guido van Rossum66e8e862001-03-23 17:54:43 +00001329 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001330 fflush(stdout);
1331 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001332 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001333 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001334 /* The error code should be in the `code' attribute. */
1335 PyObject *code = PyObject_GetAttrString(value, "code");
1336 if (code) {
1337 Py_DECREF(value);
1338 value = code;
1339 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001340 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001341 }
1342 /* If we failed to dig out the 'code' attribute,
1343 just let the else clause below print the error. */
1344 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001345 if (PyLong_Check(value))
1346 exitcode = (int)PyLong_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001347 else {
1348 PyObject_Print(value, stderr, Py_PRINT_RAW);
1349 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001350 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001351 }
Tim Peterscf615b52003-04-19 18:47:02 +00001352 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001353 /* Restore and clear the exception info, in order to properly decref
1354 * the exception, value, and traceback. If we just exit instead,
1355 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1356 * some finalizers from running.
1357 */
Tim Peterscf615b52003-04-19 18:47:02 +00001358 PyErr_Restore(exception, value, tb);
1359 PyErr_Clear();
1360 Py_Exit(exitcode);
1361 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001362}
1363
1364void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001365PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001366{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001367 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001368
1369 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1370 handle_system_exit();
1371 }
Guido van Rossum82598051997-03-05 00:20:32 +00001372 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001373 if (exception == NULL)
1374 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001375 PyErr_NormalizeException(&exception, &v, &tb);
Antoine Pitroue2dffc02008-08-26 22:02:58 +00001376 if (tb == NULL) {
1377 tb = Py_None;
1378 Py_INCREF(tb);
1379 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001380 PyException_SetTraceback(v, tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001381 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001382 return;
Georg Brandl86b2fb92008-07-16 03:43:04 +00001383 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001384 if (set_sys_last_vars) {
1385 PySys_SetObject("last_type", exception);
1386 PySys_SetObject("last_value", v);
Benjamin Petersone6528212008-07-15 15:32:09 +00001387 PySys_SetObject("last_traceback", tb);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001388 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001389 hook = PySys_GetObject("excepthook");
1390 if (hook) {
Benjamin Petersone6528212008-07-15 15:32:09 +00001391 PyObject *args = PyTuple_Pack(3, exception, v, tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001392 PyObject *result = PyEval_CallObject(hook, args);
1393 if (result == NULL) {
1394 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001395 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1396 handle_system_exit();
1397 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001398 PyErr_Fetch(&exception2, &v2, &tb2);
1399 PyErr_NormalizeException(&exception2, &v2, &tb2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001400 /* It should not be possible for exception2 or v2
1401 to be NULL. However PyErr_Display() can't
1402 tolerate NULLs, so just be safe. */
1403 if (exception2 == NULL) {
1404 exception2 = Py_None;
1405 Py_INCREF(exception2);
1406 }
1407 if (v2 == NULL) {
1408 v2 = Py_None;
1409 Py_INCREF(v2);
1410 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001411 fflush(stdout);
1412 PySys_WriteStderr("Error in sys.excepthook:\n");
1413 PyErr_Display(exception2, v2, tb2);
1414 PySys_WriteStderr("\nOriginal exception was:\n");
1415 PyErr_Display(exception, v, tb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001416 Py_DECREF(exception2);
1417 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001418 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001419 }
1420 Py_XDECREF(result);
1421 Py_XDECREF(args);
1422 } else {
1423 PySys_WriteStderr("sys.excepthook is missing\n");
1424 PyErr_Display(exception, v, tb);
1425 }
1426 Py_XDECREF(exception);
1427 Py_XDECREF(v);
1428 Py_XDECREF(tb);
1429}
1430
Benjamin Petersone6528212008-07-15 15:32:09 +00001431static void
1432print_exception(PyObject *f, PyObject *value)
1433{
1434 int err = 0;
1435 PyObject *type, *tb;
1436
Benjamin Peterson26582602008-08-23 20:08:07 +00001437 if (!PyExceptionInstance_Check(value)) {
1438 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1439 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1440 PyFile_WriteString(" found\n", f);
1441 return;
1442 }
1443
Benjamin Petersone6528212008-07-15 15:32:09 +00001444 Py_INCREF(value);
1445 fflush(stdout);
1446 type = (PyObject *) Py_TYPE(value);
1447 tb = PyException_GetTraceback(value);
1448 if (tb && tb != Py_None)
1449 err = PyTraceBack_Print(tb, f);
1450 if (err == 0 &&
1451 PyObject_HasAttrString(value, "print_file_and_line"))
1452 {
1453 PyObject *message;
1454 const char *filename, *text;
1455 int lineno, offset;
1456 if (!parse_syntax_error(value, &message, &filename,
1457 &lineno, &offset, &text))
1458 PyErr_Clear();
1459 else {
1460 char buf[10];
1461 PyFile_WriteString(" File \"", f);
1462 if (filename == NULL)
1463 PyFile_WriteString("<string>", f);
1464 else
1465 PyFile_WriteString(filename, f);
1466 PyFile_WriteString("\", line ", f);
1467 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1468 PyFile_WriteString(buf, f);
1469 PyFile_WriteString("\n", f);
1470 if (text != NULL)
1471 print_error_text(f, offset, text);
1472 Py_DECREF(value);
1473 value = message;
1474 /* Can't be bothered to check all those
1475 PyFile_WriteString() calls */
1476 if (PyErr_Occurred())
1477 err = -1;
1478 }
1479 }
1480 if (err) {
1481 /* Don't do anything else */
1482 }
1483 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001484 PyObject* moduleName;
Thomas Hellerd88ddfa2008-07-15 17:14:51 +00001485 char* className;
1486 assert(PyExceptionClass_Check(type));
1487 className = PyExceptionClass_Name(type);
Benjamin Petersone6528212008-07-15 15:32:09 +00001488 if (className != NULL) {
1489 char *dot = strrchr(className, '.');
1490 if (dot != NULL)
1491 className = dot+1;
1492 }
1493
1494 moduleName = PyObject_GetAttrString(type, "__module__");
1495 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1496 {
1497 Py_DECREF(moduleName);
1498 err = PyFile_WriteString("<unknown>", f);
1499 }
1500 else {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001501 char* modstr = _PyUnicode_AsString(moduleName);
Benjamin Petersone6528212008-07-15 15:32:09 +00001502 if (modstr && strcmp(modstr, "builtins"))
1503 {
1504 err = PyFile_WriteString(modstr, f);
1505 err += PyFile_WriteString(".", f);
1506 }
1507 Py_DECREF(moduleName);
1508 }
1509 if (err == 0) {
1510 if (className == NULL)
1511 err = PyFile_WriteString("<unknown>", f);
1512 else
1513 err = PyFile_WriteString(className, f);
1514 }
1515 }
1516 if (err == 0 && (value != Py_None)) {
1517 PyObject *s = PyObject_Str(value);
1518 /* only print colon if the str() of the
1519 object is not the empty string
1520 */
1521 if (s == NULL)
1522 err = -1;
1523 else if (!PyUnicode_Check(s) ||
1524 PyUnicode_GetSize(s) != 0)
1525 err = PyFile_WriteString(": ", f);
1526 if (err == 0)
1527 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1528 Py_XDECREF(s);
1529 }
1530 /* try to write a newline in any case */
1531 err += PyFile_WriteString("\n", f);
1532 Py_XDECREF(tb);
1533 Py_DECREF(value);
1534 /* If an error happened here, don't show it.
1535 XXX This is wrong, but too many callers rely on this behavior. */
1536 if (err != 0)
1537 PyErr_Clear();
1538}
1539
1540static const char *cause_message =
1541 "\nThe above exception was the direct cause "
1542 "of the following exception:\n\n";
1543
1544static const char *context_message =
1545 "\nDuring handling of the above exception, "
1546 "another exception occurred:\n\n";
1547
1548static void
1549print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1550{
1551 int err = 0, res;
1552 PyObject *cause, *context;
1553
1554 if (seen != NULL) {
1555 /* Exception chaining */
1556 if (PySet_Add(seen, value) == -1)
1557 PyErr_Clear();
1558 else if (PyExceptionInstance_Check(value)) {
1559 cause = PyException_GetCause(value);
1560 context = PyException_GetContext(value);
1561 if (cause) {
1562 res = PySet_Contains(seen, cause);
1563 if (res == -1)
1564 PyErr_Clear();
1565 if (res == 0) {
1566 print_exception_recursive(
1567 f, cause, seen);
1568 err |= PyFile_WriteString(
1569 cause_message, f);
1570 }
1571 }
Antoine Pitrou7b0d4a22009-11-28 16:12:28 +00001572 else if (context) {
Benjamin Petersone6528212008-07-15 15:32:09 +00001573 res = PySet_Contains(seen, context);
1574 if (res == -1)
1575 PyErr_Clear();
1576 if (res == 0) {
1577 print_exception_recursive(
1578 f, context, seen);
1579 err |= PyFile_WriteString(
1580 context_message, f);
1581 }
1582 }
1583 Py_XDECREF(context);
1584 Py_XDECREF(cause);
1585 }
1586 }
1587 print_exception(f, value);
1588 if (err != 0)
1589 PyErr_Clear();
1590}
1591
Thomas Wouters477c8d52006-05-27 19:21:47 +00001592void
1593PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001594{
Benjamin Petersone6528212008-07-15 15:32:09 +00001595 PyObject *seen;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001596 PyObject *f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +00001597 if (f == Py_None) {
1598 /* pass */
1599 }
1600 else if (f == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001601 _PyObject_Dump(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001602 fprintf(stderr, "lost sys.stderr\n");
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001603 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001604 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001605 /* We choose to ignore seen being possibly NULL, and report
1606 at least the main exception (it could be a MemoryError).
1607 */
1608 seen = PySet_New(NULL);
1609 if (seen == NULL)
1610 PyErr_Clear();
1611 print_exception_recursive(f, value, seen);
1612 Py_XDECREF(seen);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001613 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001614}
1615
Guido van Rossum82598051997-03-05 00:20:32 +00001616PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001617PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001618 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001619{
Neal Norwitze92fba02006-03-04 18:52:26 +00001620 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001621 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001622 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001623 if (arena == NULL)
1624 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001625
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001626 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001627 if (mod != NULL)
1628 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001629 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001630 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001631}
1632
1633PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001634PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001635 PyObject *locals, int closeit, PyCompilerFlags *flags)
1636{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001637 PyObject *ret;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001638 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001639 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001640 if (arena == NULL)
1641 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001642
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001643 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001644 flags, NULL, arena);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001645 if (closeit)
1646 fclose(fp);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001647 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001648 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001649 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001650 }
Neal Norwitze92fba02006-03-04 18:52:26 +00001651 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001652 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001653 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001654}
1655
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001656static void
1657flush_io(void)
1658{
1659 PyObject *f, *r;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001660 PyObject *type, *value, *traceback;
1661
1662 /* Save the current exception */
1663 PyErr_Fetch(&type, &value, &traceback);
1664
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001665 f = PySys_GetObject("stderr");
1666 if (f != NULL) {
1667 r = PyObject_CallMethod(f, "flush", "");
1668 if (r)
1669 Py_DECREF(r);
1670 else
1671 PyErr_Clear();
1672 }
1673 f = PySys_GetObject("stdout");
1674 if (f != NULL) {
1675 r = PyObject_CallMethod(f, "flush", "");
1676 if (r)
1677 Py_DECREF(r);
1678 else
1679 PyErr_Clear();
1680 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001681
1682 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001683}
1684
Guido van Rossum82598051997-03-05 00:20:32 +00001685static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001686run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001687 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001688{
Guido van Rossum82598051997-03-05 00:20:32 +00001689 PyCodeObject *co;
1690 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001691 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001692 if (co == NULL)
1693 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001694 v = PyEval_EvalCode(co, globals, locals);
1695 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001696 return v;
1697}
1698
Guido van Rossum82598051997-03-05 00:20:32 +00001699static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001700run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001702{
Guido van Rossum82598051997-03-05 00:20:32 +00001703 PyCodeObject *co;
1704 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001705 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001706 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001707
Guido van Rossum82598051997-03-05 00:20:32 +00001708 magic = PyMarshal_ReadLongFromFile(fp);
1709 if (magic != PyImport_GetMagicNumber()) {
1710 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001711 "Bad magic number in .pyc file");
1712 return NULL;
1713 }
Guido van Rossum82598051997-03-05 00:20:32 +00001714 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001715 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001716 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001717 if (v == NULL || !PyCode_Check(v)) {
1718 Py_XDECREF(v);
1719 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001720 "Bad code object in .pyc file");
1721 return NULL;
1722 }
Guido van Rossum82598051997-03-05 00:20:32 +00001723 co = (PyCodeObject *)v;
1724 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001725 if (v && flags)
1726 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001727 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001728 return v;
1729}
1730
Guido van Rossum82598051997-03-05 00:20:32 +00001731PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001732Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001733 PyCompilerFlags *flags)
1734{
Guido van Rossum82598051997-03-05 00:20:32 +00001735 PyCodeObject *co;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001736 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001737 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001738 if (arena == NULL)
1739 return NULL;
1740
1741 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001742 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001743 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001744 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001745 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001746 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001747 PyObject *result = PyAST_mod2obj(mod);
1748 PyArena_Free(arena);
1749 return result;
1750 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001751 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001752 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001753 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001754}
1755
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001756struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001757Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001758{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001759 struct symtable *st;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001760 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001761 PyCompilerFlags flags;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001762 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001763 if (arena == NULL)
1764 return NULL;
1765
Christian Heimesb1b3efc2008-03-26 23:24:27 +00001766 flags.cf_flags = 0;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001767 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001768 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001769 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001770 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001771 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001772 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001773 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001774 return st;
1775}
1776
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001777/* Preferred access to parser is through AST. */
1778mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001779PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001780 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001781{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001783 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001784 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001785 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001786
1787 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001788 &_PyParser_Grammar, start, &err,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001789 &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001790 if (flags == NULL) {
1791 localflags.cf_flags = 0;
1792 flags = &localflags;
1793 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001794 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001795 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001796 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001797 PyNode_Free(n);
1798 return mod;
1799 }
1800 else {
1801 err_input(&err);
1802 return NULL;
1803 }
1804}
1805
1806mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001807PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1808 int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001809 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001810 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001812 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001813 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001814 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001815 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001816
Christian Heimes4d6ec852008-03-26 22:34:47 +00001817 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001818 &_PyParser_Grammar,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001819 start, ps1, ps2, &err, &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001820 if (flags == NULL) {
1821 localflags.cf_flags = 0;
1822 flags = &localflags;
1823 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001824 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001825 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001826 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001827 PyNode_Free(n);
1828 return mod;
1829 }
1830 else {
1831 err_input(&err);
1832 if (errcode)
1833 *errcode = err.error;
1834 return NULL;
1835 }
1836}
1837
Guido van Rossuma110aa61994-08-29 12:50:44 +00001838/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001839
Guido van Rossuma110aa61994-08-29 12:50:44 +00001840node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001841PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001842{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001843 perrdetail err;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001844 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1845 &_PyParser_Grammar,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001846 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001847 if (n == NULL)
1848 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001849
Guido van Rossuma110aa61994-08-29 12:50:44 +00001850 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001851}
1852
Guido van Rossuma110aa61994-08-29 12:50:44 +00001853/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001854
Guido van Rossuma110aa61994-08-29 12:50:44 +00001855node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001856PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001857{
Tim Petersfe2127d2001-07-16 05:37:24 +00001858 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001859 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1860 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001861 if (n == NULL)
1862 err_input(&err);
1863 return n;
1864}
1865
1866node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001867PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001868 int start, int flags)
1869{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001870 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001871 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1872 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001873 if (n == NULL)
1874 err_input(&err);
1875 return n;
1876}
1877
1878node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001879PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001880{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001881 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001882}
1883
Guido van Rossum66ebd912003-04-17 16:02:26 +00001884/* May want to move a more generalized form of this to parsetok.c or
1885 even parser modules. */
1886
1887void
1888PyParser_SetError(perrdetail *err)
1889{
1890 err_input(err);
1891}
1892
Guido van Rossuma110aa61994-08-29 12:50:44 +00001893/* Set the error appropriate to the given input error code (see errcode.h) */
1894
1895static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001896err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001897{
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001898 PyObject *v, *w, *errtype, *errtext;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001899 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001900 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001901 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001902 switch (err->error) {
Victor Stinner52f6dd72010-03-12 14:45:56 +00001903 case E_ERROR:
1904 return;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001905 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001906 errtype = PyExc_IndentationError;
1907 if (err->expected == INDENT)
1908 msg = "expected an indented block";
1909 else if (err->token == INDENT)
1910 msg = "unexpected indent";
1911 else if (err->token == DEDENT)
1912 msg = "unexpected unindent";
1913 else {
1914 errtype = PyExc_SyntaxError;
1915 msg = "invalid syntax";
1916 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001917 break;
1918 case E_TOKEN:
1919 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001920 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001921 case E_EOFS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001922 msg = "EOF while scanning triple-quoted string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001923 break;
1924 case E_EOLS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001925 msg = "EOL while scanning string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001926 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001927 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001928 if (!PyErr_Occurred())
1929 PyErr_SetNone(PyExc_KeyboardInterrupt);
Georg Brandl3dbca812008-07-23 16:10:53 +00001930 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001931 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001932 PyErr_NoMemory();
Georg Brandl3dbca812008-07-23 16:10:53 +00001933 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001934 case E_EOF:
1935 msg = "unexpected EOF while parsing";
1936 break;
Fred Drake85f36392000-07-11 17:53:00 +00001937 case E_TABSPACE:
1938 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001939 msg = "inconsistent use of tabs and spaces in indentation";
1940 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001941 case E_OVERFLOW:
1942 msg = "expression too long";
1943 break;
Fred Drake85f36392000-07-11 17:53:00 +00001944 case E_DEDENT:
1945 errtype = PyExc_IndentationError;
1946 msg = "unindent does not match any outer indentation level";
1947 break;
1948 case E_TOODEEP:
1949 errtype = PyExc_IndentationError;
1950 msg = "too many levels of indentation";
1951 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001952 case E_DECODE: {
1953 PyObject *type, *value, *tb;
1954 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001955 if (value != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001956 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001957 if (u != NULL) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001958 msg = _PyUnicode_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001959 }
1960 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001961 if (msg == NULL)
1962 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001963 Py_XDECREF(type);
1964 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001965 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001966 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001967 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001968 case E_LINECONT:
1969 msg = "unexpected character after line continuation character";
1970 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001971
1972 case E_IDENTIFIER:
1973 msg = "invalid character in identifier";
1974 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001975 default:
1976 fprintf(stderr, "error=%d\n", err->error);
1977 msg = "unknown parsing error";
1978 break;
1979 }
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001980 /* err->text may not be UTF-8 in case of decoding errors.
1981 Explicitly convert to an object. */
1982 if (!err->text) {
1983 errtext = Py_None;
1984 Py_INCREF(Py_None);
1985 } else {
1986 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1987 "replace");
1988 }
1989 v = Py_BuildValue("(ziiN)", err->filename,
1990 err->lineno, err->offset, errtext);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001991 w = NULL;
1992 if (v != NULL)
1993 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001994 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001995 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001996 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001997 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00001998cleanup:
1999 if (err->text != NULL) {
2000 PyObject_FREE(err->text);
2001 err->text = NULL;
2002 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002003}
2004
2005/* Print fatal error message and abort */
2006
2007void
Tim Peters7c321a82002-07-09 02:57:01 +00002008Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002009{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00002010 fprintf(stderr, "Fatal Python error: %s\n", msg);
Jesse Nollera9314042009-03-31 22:36:44 +00002011 fflush(stderr); /* it helps in Windows debug build */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00002012 if (PyErr_Occurred()) {
2013 PyErr_Print();
2014 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002015#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002016 {
2017 size_t len = strlen(msg);
2018 WCHAR* buffer;
2019 size_t i;
2020
2021 /* Convert the message to wchar_t. This uses a simple one-to-one
2022 conversion, assuming that the this error message actually uses ASCII
2023 only. If this ceases to be true, we will have to convert. */
2024 buffer = alloca( (len+1) * (sizeof *buffer));
2025 for( i=0; i<=len; ++i)
2026 buffer[i] = msg[i];
2027 OutputDebugStringW(L"Fatal Python error: ");
2028 OutputDebugStringW(buffer);
2029 OutputDebugStringW(L"\n");
2030 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002031#ifdef _DEBUG
2032 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002033#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002034#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002035 abort();
2036}
2037
2038/* Clean up and exit */
2039
Guido van Rossuma110aa61994-08-29 12:50:44 +00002040#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002041#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002042#endif
2043
Collin Winter670e6922007-03-21 02:57:17 +00002044static void (*pyexitfunc)(void) = NULL;
2045/* For the atexit module. */
2046void _Py_PyAtExit(void (*func)(void))
2047{
2048 pyexitfunc = func;
2049}
2050
2051static void
2052call_py_exitfuncs(void)
2053{
Guido van Rossum98297ee2007-11-06 21:34:58 +00002054 if (pyexitfunc == NULL)
Collin Winter670e6922007-03-21 02:57:17 +00002055 return;
2056
2057 (*pyexitfunc)();
2058 PyErr_Clear();
2059}
2060
Antoine Pitrou011bd622009-10-20 21:52:47 +00002061/* Wait until threading._shutdown completes, provided
2062 the threading module was imported in the first place.
2063 The shutdown routine will wait until all non-daemon
2064 "threading" threads have completed. */
2065static void
2066wait_for_thread_shutdown(void)
2067{
2068#ifdef WITH_THREAD
2069 PyObject *result;
2070 PyThreadState *tstate = PyThreadState_GET();
2071 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2072 "threading");
2073 if (threading == NULL) {
2074 /* threading not imported */
2075 PyErr_Clear();
2076 return;
2077 }
2078 result = PyObject_CallMethod(threading, "_shutdown", "");
2079 if (result == NULL) {
2080 PyErr_WriteUnraisable(threading);
2081 }
2082 else {
2083 Py_DECREF(result);
2084 }
2085 Py_DECREF(threading);
2086#endif
2087}
2088
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002089#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002090static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002091static int nexitfuncs = 0;
2092
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002093int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002094{
2095 if (nexitfuncs >= NEXITFUNCS)
2096 return -1;
2097 exitfuncs[nexitfuncs++] = func;
2098 return 0;
2099}
2100
Guido van Rossumcc283f51997-08-05 02:22:03 +00002101static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002102call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002103{
Guido van Rossum1662dd51994-09-07 14:38:28 +00002104 while (nexitfuncs > 0)
2105 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002106
2107 fflush(stdout);
2108 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002109}
2110
2111void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002112Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002113{
Guido van Rossumcc283f51997-08-05 02:22:03 +00002114 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002115
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002116 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002117}
2118
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002119static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002120initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002121{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002122#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002123 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002124#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002125#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002126 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002127#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002128#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002129 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002130#endif
Guido van Rossum82598051997-03-05 00:20:32 +00002131 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002132}
2133
Guido van Rossum7433b121997-02-14 19:45:36 +00002134
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002135/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2136 *
2137 * All of the code in this function must only use async-signal-safe functions,
2138 * listed at `man 7 signal` or
2139 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2140 */
2141void
2142_Py_RestoreSignals(void)
2143{
2144#ifdef SIGPIPE
2145 PyOS_setsig(SIGPIPE, SIG_DFL);
2146#endif
2147#ifdef SIGXFZ
2148 PyOS_setsig(SIGXFZ, SIG_DFL);
2149#endif
2150#ifdef SIGXFSZ
2151 PyOS_setsig(SIGXFSZ, SIG_DFL);
2152#endif
2153}
2154
2155
Guido van Rossum7433b121997-02-14 19:45:36 +00002156/*
2157 * The file descriptor fd is considered ``interactive'' if either
2158 * a) isatty(fd) is TRUE, or
2159 * b) the -i flag was given, and the filename associated with
2160 * the descriptor is NULL or "<stdin>" or "???".
2161 */
2162int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002163Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002164{
2165 if (isatty((int)fileno(fp)))
2166 return 1;
2167 if (!Py_InteractiveFlag)
2168 return 0;
2169 return (filename == NULL) ||
2170 (strcmp(filename, "<stdin>") == 0) ||
2171 (strcmp(filename, "???") == 0);
2172}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002173
2174
Tim Petersd08e3822003-04-17 15:24:21 +00002175#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002176#if defined(WIN32) && defined(_MSC_VER)
2177
2178/* Stack checking for Microsoft C */
2179
2180#include <malloc.h>
2181#include <excpt.h>
2182
Fred Drakee8de31c2000-08-31 05:38:39 +00002183/*
2184 * Return non-zero when we run out of memory on the stack; zero otherwise.
2185 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002186int
Fred Drake399739f2000-08-31 05:52:44 +00002187PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002188{
2189 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00002190 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002191 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00002192 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002193 return 0;
Christian Heimes7131fd92008-02-19 14:21:46 +00002194 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
Trent Nelson39e307e2008-03-19 06:45:48 +00002195 EXCEPTION_EXECUTE_HANDLER :
2196 EXCEPTION_CONTINUE_SEARCH) {
Christian Heimes7131fd92008-02-19 14:21:46 +00002197 int errcode = _resetstkoflw();
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +00002198 if (errcode == 0)
Christian Heimes7131fd92008-02-19 14:21:46 +00002199 {
2200 Py_FatalError("Could not reset the stack!");
2201 }
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002202 }
2203 return 1;
2204}
2205
2206#endif /* WIN32 && _MSC_VER */
2207
2208/* Alternate implementations can be added here... */
2209
2210#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002211
2212
2213/* Wrappers around sigaction() or signal(). */
2214
2215PyOS_sighandler_t
2216PyOS_getsig(int sig)
2217{
2218#ifdef HAVE_SIGACTION
2219 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002220 if (sigaction(sig, NULL, &context) == -1)
2221 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00002222 return context.sa_handler;
2223#else
2224 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002225/* Special signal handling for the secure CRT in Visual Studio 2005 */
2226#if defined(_MSC_VER) && _MSC_VER >= 1400
2227 switch (sig) {
2228 /* Only these signals are valid */
2229 case SIGINT:
2230 case SIGILL:
2231 case SIGFPE:
2232 case SIGSEGV:
2233 case SIGTERM:
2234 case SIGBREAK:
2235 case SIGABRT:
2236 break;
2237 /* Don't call signal() with other values or it will assert */
2238 default:
2239 return SIG_ERR;
2240 }
2241#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002242 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002243 if (handler != SIG_ERR)
2244 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00002245 return handler;
2246#endif
2247}
2248
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002249/*
2250 * All of the code in this function must only use async-signal-safe functions,
2251 * listed at `man 7 signal` or
2252 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2253 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002254PyOS_sighandler_t
2255PyOS_setsig(int sig, PyOS_sighandler_t handler)
2256{
2257#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002258 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00002259 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002260 sigemptyset(&context.sa_mask);
2261 context.sa_flags = 0;
2262 if (sigaction(sig, &context, &ocontext) == -1)
2263 return SIG_ERR;
2264 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002265#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002266 PyOS_sighandler_t oldhandler;
2267 oldhandler = signal(sig, handler);
2268#ifdef HAVE_SIGINTERRUPT
2269 siginterrupt(sig, 1);
2270#endif
2271 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002272#endif
2273}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002274
2275/* Deprecated C API functions still provided for binary compatiblity */
2276
2277#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002278PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002279PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2280{
2281 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2282}
2283
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002284#undef PyParser_SimpleParseString
2285PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002286PyParser_SimpleParseString(const char *str, int start)
2287{
2288 return PyParser_SimpleParseStringFlags(str, start, 0);
2289}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002290
2291#undef PyRun_AnyFile
2292PyAPI_FUNC(int)
2293PyRun_AnyFile(FILE *fp, const char *name)
2294{
2295 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
2296}
2297
2298#undef PyRun_AnyFileEx
2299PyAPI_FUNC(int)
2300PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2301{
2302 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
2303}
2304
2305#undef PyRun_AnyFileFlags
2306PyAPI_FUNC(int)
2307PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2308{
2309 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2310}
2311
2312#undef PyRun_File
2313PyAPI_FUNC(PyObject *)
2314PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2315{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002316 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002317}
2318
2319#undef PyRun_FileEx
2320PyAPI_FUNC(PyObject *)
2321PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2322{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002323 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002324}
2325
2326#undef PyRun_FileFlags
2327PyAPI_FUNC(PyObject *)
2328PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2329 PyCompilerFlags *flags)
2330{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002331 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002332}
2333
2334#undef PyRun_SimpleFile
2335PyAPI_FUNC(int)
2336PyRun_SimpleFile(FILE *f, const char *p)
2337{
2338 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
2339}
2340
2341#undef PyRun_SimpleFileEx
2342PyAPI_FUNC(int)
2343PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2344{
2345 return PyRun_SimpleFileExFlags(f, p, c, NULL);
2346}
2347
2348
2349#undef PyRun_String
2350PyAPI_FUNC(PyObject *)
2351PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2352{
2353 return PyRun_StringFlags(str, s, g, l, NULL);
2354}
2355
2356#undef PyRun_SimpleString
2357PyAPI_FUNC(int)
2358PyRun_SimpleString(const char *s)
2359{
2360 return PyRun_SimpleStringFlags(s, NULL);
2361}
2362
2363#undef Py_CompileString
2364PyAPI_FUNC(PyObject *)
2365Py_CompileString(const char *str, const char *p, int s)
2366{
2367 return Py_CompileStringFlags(str, p, s, NULL);
2368}
2369
2370#undef PyRun_InteractiveOne
2371PyAPI_FUNC(int)
2372PyRun_InteractiveOne(FILE *f, const char *p)
2373{
2374 return PyRun_InteractiveOneFlags(f, p, NULL);
2375}
2376
2377#undef PyRun_InteractiveLoop
2378PyAPI_FUNC(int)
2379PyRun_InteractiveLoop(FILE *f, const char *p)
2380{
2381 return PyRun_InteractiveLoopFlags(f, p, NULL);
2382}
2383
2384#ifdef __cplusplus
2385}
2386#endif