blob: b99a541d54202c2f7b5f9e0d47db8245d402ce24 [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");
Benjamin Peterson791dc2f2008-09-05 23:27:15 +0000299 if (!Py_NoSiteFlag)
300 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000301
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000302 /* auto-thread-state API, if available */
303#ifdef WITH_THREAD
304 _PyGILState_Init(interp, tstate);
305#endif /* WITH_THREAD */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000306}
307
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000308void
309Py_Initialize(void)
310{
311 Py_InitializeEx(1);
312}
313
314
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000315#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000316extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000317#endif
318
Guido van Rossume8432ac2007-07-09 15:04:50 +0000319/* Flush stdout and stderr */
320
Neal Norwitz2bad9702007-08-27 06:19:22 +0000321static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000322flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000323{
324 PyObject *fout = PySys_GetObject("stdout");
325 PyObject *ferr = PySys_GetObject("stderr");
326 PyObject *tmp;
327
Christian Heimes2be03732007-11-15 02:26:46 +0000328 if (fout != NULL && fout != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000329 tmp = PyObject_CallMethod(fout, "flush", "");
330 if (tmp == NULL)
331 PyErr_Clear();
332 else
333 Py_DECREF(tmp);
334 }
335
Christian Heimes2be03732007-11-15 02:26:46 +0000336 if (ferr != NULL || ferr != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000337 tmp = PyObject_CallMethod(ferr, "flush", "");
338 if (tmp == NULL)
339 PyErr_Clear();
340 else
341 Py_DECREF(tmp);
342 }
343}
344
Guido van Rossum25ce5661997-08-02 03:10:38 +0000345/* Undo the effect of Py_Initialize().
346
347 Beware: if multiple interpreter and/or thread states exist, these
348 are not wiped out; only the current thread and interpreter state
349 are deleted. But since everything else is deleted, those other
350 interpreter and thread states should no longer be used.
351
352 (XXX We should do better, e.g. wipe out all interpreters and
353 threads.)
354
355 Locking: as above.
356
357*/
358
359void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000360Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000361{
362 PyInterpreterState *interp;
363 PyThreadState *tstate;
364
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000365 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000366 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000367
Antoine Pitrou011bd622009-10-20 21:52:47 +0000368 wait_for_thread_shutdown();
369
Tim Peters384fd102001-01-21 03:40:37 +0000370 /* The interpreter is still entirely intact at this point, and the
371 * exit funcs may be relying on that. In particular, if some thread
372 * or exit func is still waiting to do an import, the import machinery
373 * expects Py_IsInitialized() to return true. So don't say the
374 * interpreter is uninitialized until after the exit funcs have run.
375 * Note that Threading.py uses an exit func to do a join on all the
376 * threads created thru it, so this also protects pending imports in
377 * the threads created via Threading.
378 */
Collin Winter670e6922007-03-21 02:57:17 +0000379 call_py_exitfuncs();
Tim Peters384fd102001-01-21 03:40:37 +0000380 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000381
Guido van Rossume8432ac2007-07-09 15:04:50 +0000382 /* Flush stdout+stderr */
383 flush_std_files();
384
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000385 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000386 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000387 interp = tstate->interp;
388
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000389 /* Disable signal handling */
390 PyOS_FiniInterrupts();
391
Christian Heimes26855632008-01-27 23:50:43 +0000392 /* Clear type lookup cache */
393 PyType_ClearCache();
394
Guido van Rossume13ddc92003-04-17 17:29:22 +0000395 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000396 * before all modules are destroyed.
397 * XXX If a __del__ or weakref callback is triggered here, and tries to
398 * XXX import a module, bad things can happen, because Python no
399 * XXX longer believes it's initialized.
400 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
401 * XXX is easy to provoke that way. I've also seen, e.g.,
402 * XXX Exception exceptions.ImportError: 'No module named sha'
403 * XXX in <function callback at 0x008F5718> ignored
404 * XXX but I'm unclear on exactly how that one happens. In any case,
405 * XXX I haven't seen a real-life report of either of these.
Neal Norwitz9589ee22006-03-04 19:01:22 +0000406 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000407 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000408#ifdef COUNT_ALLOCS
409 /* With COUNT_ALLOCS, it helps to run GC multiple times:
410 each collection might release some types from the type
411 list, so they become garbage. */
412 while (PyGC_Collect() > 0)
413 /* nothing */;
414#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000415
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000416 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000417 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000418
Guido van Rossume8432ac2007-07-09 15:04:50 +0000419 /* Flush stdout+stderr (again, in case more was printed) */
420 flush_std_files();
421
Guido van Rossume13ddc92003-04-17 17:29:22 +0000422 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000423 * new-style class definitions, for example.
424 * XXX This is disabled because it caused too many problems. If
425 * XXX a __del__ or weakref callback triggers here, Python code has
426 * XXX a hard time running, because even the sys module has been
427 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
428 * XXX One symptom is a sequence of information-free messages
429 * XXX coming from threads (if a __del__ or callback is invoked,
430 * XXX other threads can execute too, and any exception they encounter
431 * XXX triggers a comedy of errors as subsystem after subsystem
432 * XXX fails to find what it *expects* to find in sys to help report
433 * XXX the exception and consequent unexpected failures). I've also
434 * XXX seen segfaults then, after adding print statements to the
435 * XXX Python code getting called.
436 */
437#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000438 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000439#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000440
Guido van Rossum1707aad1997-12-08 23:43:45 +0000441 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
442 _PyImport_Fini();
443
444 /* Debugging stuff */
445#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000446 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000447#endif
448
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000449 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000450
Tim Peters9cf25ce2003-04-17 15:21:01 +0000451#ifdef Py_TRACE_REFS
452 /* Display all objects still alive -- this can invoke arbitrary
453 * __repr__ overrides, so requires a mostly-intact interpreter.
454 * Alas, a lot of stuff may still be alive now that will be cleaned
455 * up later.
456 */
Tim Peters269b2a62003-04-17 19:52:29 +0000457 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000458 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000459#endif /* Py_TRACE_REFS */
460
Guido van Rossumd922fa42003-04-15 14:10:09 +0000461 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000462 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000463
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000464 /* Now we decref the exception classes. After this point nothing
465 can raise an exception. That's okay, because each Fini() method
466 below has been checked to make sure no exceptions are ever
467 raised.
468 */
469
470 _PyExc_Fini();
471
Christian Heimes7d2ff882007-11-30 14:35:04 +0000472 /* Cleanup auto-thread-state */
473#ifdef WITH_THREAD
474 _PyGILState_Fini();
475#endif /* WITH_THREAD */
476
Guido van Rossumd922fa42003-04-15 14:10:09 +0000477 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000478 PyThreadState_Swap(NULL);
479 PyInterpreterState_Delete(interp);
480
Guido van Rossumd922fa42003-04-15 14:10:09 +0000481 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000482 PyMethod_Fini();
483 PyFrame_Fini();
484 PyCFunction_Fini();
485 PyTuple_Fini();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000486 PyList_Fini();
Raymond Hettingerd7946662005-08-01 21:39:29 +0000487 PySet_Fini();
Christian Heimes72b710a2008-05-26 13:28:38 +0000488 PyBytes_Fini();
Christian Heimes9c4756e2008-05-26 13:22:05 +0000489 PyByteArray_Fini();
Guido van Rossumddefaf32007-01-14 03:31:43 +0000490 PyLong_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000491 PyFloat_Fini();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000492 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000493
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000494 /* Cleanup Unicode implementation */
495 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000496
Christian Heimesc8967002007-11-30 10:18:26 +0000497 /* reset file system default encoding */
498 if (!Py_HasFileSystemDefaultEncoding) {
499 free((char*)Py_FileSystemDefaultEncoding);
Trent Nelson39e307e2008-03-19 06:45:48 +0000500 Py_FileSystemDefaultEncoding = NULL;
Christian Heimesc8967002007-11-30 10:18:26 +0000501 }
502
Guido van Rossumcc283f51997-08-05 02:22:03 +0000503 /* XXX Still allocated:
504 - various static ad-hoc pointers to interned strings
505 - int and float free list blocks
506 - whatever various modules and libraries allocate
507 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000508
509 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000510
Tim Peters269b2a62003-04-17 19:52:29 +0000511#ifdef Py_TRACE_REFS
512 /* Display addresses (& refcnts) of all objects still alive.
513 * An address can be used to find the repr of the object, printed
514 * above by _Py_PrintReferences.
515 */
516 if (Py_GETENV("PYTHONDUMPREFS"))
517 _Py_PrintReferenceAddresses(stderr);
518#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000519#ifdef PYMALLOC_DEBUG
520 if (Py_GETENV("PYTHONMALLOCSTATS"))
521 _PyObject_DebugMallocStats();
522#endif
523
Guido van Rossumcc283f51997-08-05 02:22:03 +0000524 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000525}
526
527/* Create and initialize a new interpreter and thread, and return the
528 new thread. This requires that Py_Initialize() has been called
529 first.
530
531 Unsuccessful initialization yields a NULL pointer. Note that *no*
532 exception information is available even in this case -- the
533 exception information is held in the thread, and there is no
534 thread.
535
536 Locking: as above.
537
538*/
539
540PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000541Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000542{
543 PyInterpreterState *interp;
544 PyThreadState *tstate, *save_tstate;
545 PyObject *bimod, *sysmod;
546
547 if (!initialized)
548 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
549
550 interp = PyInterpreterState_New();
551 if (interp == NULL)
552 return NULL;
553
554 tstate = PyThreadState_New(interp);
555 if (tstate == NULL) {
556 PyInterpreterState_Delete(interp);
557 return NULL;
558 }
559
560 save_tstate = PyThreadState_Swap(tstate);
561
562 /* XXX The following is lax in error checking */
563
564 interp->modules = PyDict_New();
Guido van Rossumd8faa362007-04-27 19:54:29 +0000565 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000566
Georg Brandl1a3284e2007-12-02 09:40:06 +0000567 bimod = _PyImport_FindExtension("builtins", "builtins");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000568 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000569 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000570 if (interp->builtins == NULL)
571 goto handle_error;
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000572 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000574
575 /* initialize builtin exceptions */
576 _PyExc_Init();
577
Guido van Rossum25ce5661997-08-02 03:10:38 +0000578 sysmod = _PyImport_FindExtension("sys", "sys");
579 if (bimod != NULL && sysmod != NULL) {
Christian Heimes6a27efa2008-10-30 21:48:26 +0000580 PyObject *pstderr;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000581 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000582 if (interp->sysdict == NULL)
583 goto handle_error;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000584 Py_INCREF(interp->sysdict);
585 PySys_SetPath(Py_GetPath());
586 PyDict_SetItemString(interp->sysdict, "modules",
587 interp->modules);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000588 /* Set up a preliminary stderr printer until we have enough
589 infrastructure for the io module in place. */
590 pstderr = PyFile_NewStdPrinter(fileno(stderr));
591 if (pstderr == NULL)
592 Py_FatalError("Py_Initialize: can't set preliminary stderr");
593 PySys_SetObject("stderr", pstderr);
594 PySys_SetObject("__stderr__", pstderr);
595
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000596 _PyImportHooks_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000597 if (initstdio() < 0)
598 Py_FatalError(
599 "Py_Initialize: can't initialize sys standard streams");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000600 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000601 if (!Py_NoSiteFlag)
602 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000603 }
604
605 if (!PyErr_Occurred())
606 return tstate;
607
Thomas Wouters89f507f2006-12-13 04:49:30 +0000608handle_error:
Guido van Rossum25ce5661997-08-02 03:10:38 +0000609 /* Oops, it didn't work. Undo it all. */
610
611 PyErr_Print();
612 PyThreadState_Clear(tstate);
613 PyThreadState_Swap(save_tstate);
614 PyThreadState_Delete(tstate);
615 PyInterpreterState_Delete(interp);
616
617 return NULL;
618}
619
620/* Delete an interpreter and its last thread. This requires that the
621 given thread state is current, that the thread has no remaining
622 frames, and that it is its interpreter's only remaining thread.
623 It is a fatal error to violate these constraints.
624
625 (Py_Finalize() doesn't have these constraints -- it zaps
626 everything, regardless.)
627
628 Locking: as above.
629
630*/
631
632void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000633Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000634{
635 PyInterpreterState *interp = tstate->interp;
636
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000637 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000638 Py_FatalError("Py_EndInterpreter: thread is not current");
639 if (tstate->frame != NULL)
640 Py_FatalError("Py_EndInterpreter: thread still has a frame");
641 if (tstate != interp->tstate_head || tstate->next != NULL)
642 Py_FatalError("Py_EndInterpreter: not the last thread");
643
644 PyImport_Cleanup();
645 PyInterpreterState_Clear(interp);
646 PyThreadState_Swap(NULL);
647 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000648}
649
Martin v. Löwis790465f2008-04-05 20:41:37 +0000650static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000651
652void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000653Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000654{
655 if (pn && *pn)
656 progname = pn;
657}
658
Martin v. Löwis790465f2008-04-05 20:41:37 +0000659wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000660Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000661{
662 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000663}
664
Martin v. Löwis790465f2008-04-05 20:41:37 +0000665static wchar_t *default_home = NULL;
666static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000667
668void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000669Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000670{
671 default_home = home;
672}
673
Martin v. Löwis790465f2008-04-05 20:41:37 +0000674wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000675Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000676{
Martin v. Löwis790465f2008-04-05 20:41:37 +0000677 wchar_t *home = default_home;
678 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
679 char* chome = Py_GETENV("PYTHONHOME");
680 if (chome) {
681 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
682 if (r != (size_t)-1 && r <= PATH_MAX)
683 home = env_home;
684 }
685
686 }
Guido van Rossuma61691e1998-02-06 22:27:24 +0000687 return home;
688}
689
Guido van Rossum6135a871995-01-09 17:53:26 +0000690/* Create __main__ module */
691
692static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000693initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000694{
Guido van Rossum82598051997-03-05 00:20:32 +0000695 PyObject *m, *d;
696 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000697 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000698 Py_FatalError("can't create __main__ module");
699 d = PyModule_GetDict(m);
700 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Georg Brandl1a3284e2007-12-02 09:40:06 +0000701 PyObject *bimod = PyImport_ImportModule("builtins");
Guido van Rossum858cb731997-11-19 16:15:37 +0000702 if (bimod == NULL ||
703 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000704 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000705 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000706 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000707}
708
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000709/* Import the site module (not into __main__ though) */
710
711static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000712initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000713{
714 PyObject *m, *f;
715 m = PyImport_ImportModule("site");
716 if (m == NULL) {
717 f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +0000718 if (f == NULL || f == Py_None)
719 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000720 if (Py_VerboseFlag) {
721 PyFile_WriteString(
722 "'import site' failed; traceback:\n", f);
723 PyErr_Print();
724 }
725 else {
726 PyFile_WriteString(
727 "'import site' failed; use -v for traceback\n", f);
728 PyErr_Clear();
729 }
730 }
731 else {
732 Py_DECREF(m);
733 }
734}
735
Antoine Pitrou05608432009-01-09 18:53:14 +0000736static PyObject*
737create_stdio(PyObject* io,
738 int fd, int write_mode, char* name,
739 char* encoding, char* errors)
740{
Antoine Pitrou91696412009-01-09 22:12:30 +0000741 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
Antoine Pitrou05608432009-01-09 18:53:14 +0000742 const char* mode;
Antoine Pitrou91696412009-01-09 22:12:30 +0000743 PyObject *line_buffering;
744 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000745
Antoine Pitrou27fe9fc2009-01-26 21:48:00 +0000746 /* stdin is always opened in buffered mode, first because it shouldn't
747 make a difference in common use cases, second because TextIOWrapper
748 depends on the presence of a read1() method which only exists on
749 buffered streams.
750 */
751 if (Py_UnbufferedStdioFlag && write_mode)
Antoine Pitrou05608432009-01-09 18:53:14 +0000752 buffering = 0;
753 else
754 buffering = -1;
755 if (write_mode)
756 mode = "wb";
757 else
758 mode = "rb";
759 buf = PyObject_CallMethod(io, "open", "isiOOOi",
760 fd, mode, buffering,
761 Py_None, Py_None, Py_None, 0);
762 if (buf == NULL)
763 goto error;
764
Antoine Pitrou27fe9fc2009-01-26 21:48:00 +0000765 if (buffering) {
Antoine Pitrou05608432009-01-09 18:53:14 +0000766 raw = PyObject_GetAttrString(buf, "raw");
767 if (raw == NULL)
768 goto error;
769 }
770 else {
771 raw = buf;
772 Py_INCREF(raw);
773 }
774
775 text = PyUnicode_FromString(name);
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000776 if (text == NULL || PyObject_SetAttrString(raw, "name", text) < 0)
Antoine Pitrou05608432009-01-09 18:53:14 +0000777 goto error;
Antoine Pitrou91696412009-01-09 22:12:30 +0000778 res = PyObject_CallMethod(raw, "isatty", "");
779 if (res == NULL)
780 goto error;
781 isatty = PyObject_IsTrue(res);
782 Py_DECREF(res);
783 if (isatty == -1)
784 goto error;
785 if (isatty || Py_UnbufferedStdioFlag)
Antoine Pitrou05608432009-01-09 18:53:14 +0000786 line_buffering = Py_True;
787 else
788 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000789
790 Py_CLEAR(raw);
791 Py_CLEAR(text);
792
Antoine Pitrou05608432009-01-09 18:53:14 +0000793 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
794 buf, encoding, errors,
795 "\n", line_buffering);
796 Py_CLEAR(buf);
797 if (stream == NULL)
798 goto error;
799
800 if (write_mode)
801 mode = "w";
802 else
803 mode = "r";
804 text = PyUnicode_FromString(mode);
805 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
806 goto error;
807 Py_CLEAR(text);
808 return stream;
809
810error:
811 Py_XDECREF(buf);
812 Py_XDECREF(stream);
813 Py_XDECREF(text);
814 Py_XDECREF(raw);
815 return NULL;
816}
817
Georg Brandl1a3284e2007-12-02 09:40:06 +0000818/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000819static int
820initstdio(void)
821{
822 PyObject *iomod = NULL, *wrapper;
823 PyObject *bimod = NULL;
824 PyObject *m;
825 PyObject *std = NULL;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000826 int status = 0, fd;
Trent Nelson39e307e2008-03-19 06:45:48 +0000827 PyObject * encoding_attr;
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +0000828 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000829
830 /* Hack to avoid a nasty recursion issue when Python is invoked
831 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
832 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
833 goto error;
834 }
835 Py_DECREF(m);
836
837 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
838 goto error;
839 }
840 Py_DECREF(m);
841
Georg Brandl1a3284e2007-12-02 09:40:06 +0000842 if (!(bimod = PyImport_ImportModule("builtins"))) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000843 goto error;
844 }
845
846 if (!(iomod = PyImport_ImportModule("io"))) {
847 goto error;
848 }
849 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
850 goto error;
851 }
852
Georg Brandl1a3284e2007-12-02 09:40:06 +0000853 /* Set builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000854 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
855 goto error;
856 }
857
Martin v. Löwis0f599892008-06-02 11:13:03 +0000858 encoding = Py_GETENV("PYTHONIOENCODING");
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000859 errors = NULL;
Martin v. Löwis0f599892008-06-02 11:13:03 +0000860 if (encoding) {
861 encoding = strdup(encoding);
862 errors = strchr(encoding, ':');
863 if (errors) {
864 *errors = '\0';
865 errors++;
866 }
867 }
868
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000869 /* Set sys.stdin */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000870 fd = fileno(stdin);
871 /* Under some conditions stdin, stdout and stderr may not be connected
872 * and fileno() may point to an invalid file descriptor. For example
873 * GUI apps don't have valid standard streams by default.
874 */
875 if (fd < 0) {
876#ifdef MS_WINDOWS
877 std = Py_None;
878 Py_INCREF(std);
879#else
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000880 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000881#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000882 }
Christian Heimes58cb1b82007-11-13 02:19:40 +0000883 else {
Antoine Pitrou05608432009-01-09 18:53:14 +0000884 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
885 if (std == NULL)
Christian Heimes58cb1b82007-11-13 02:19:40 +0000886 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000887 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000888 PySys_SetObject("__stdin__", std);
889 PySys_SetObject("stdin", std);
890 Py_DECREF(std);
891
892 /* Set sys.stdout */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000893 fd = fileno(stdout);
894 if (fd < 0) {
895#ifdef MS_WINDOWS
896 std = Py_None;
897 Py_INCREF(std);
898#else
899 goto error;
900#endif
901 }
902 else {
Antoine Pitrou05608432009-01-09 18:53:14 +0000903 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
904 if (std == NULL)
Christian Heimes58cb1b82007-11-13 02:19:40 +0000905 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000906 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000907 PySys_SetObject("__stdout__", std);
908 PySys_SetObject("stdout", std);
909 Py_DECREF(std);
910
Guido van Rossum98297ee2007-11-06 21:34:58 +0000911#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000912 /* Set sys.stderr, replaces the preliminary stderr */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000913 fd = fileno(stderr);
914 if (fd < 0) {
915#ifdef MS_WINDOWS
916 std = Py_None;
917 Py_INCREF(std);
918#else
919 goto error;
920#endif
921 }
922 else {
Antoine Pitrou05608432009-01-09 18:53:14 +0000923 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
924 if (std == NULL)
Christian Heimes58cb1b82007-11-13 02:19:40 +0000925 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000926 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000927
928 /* Same as hack above, pre-import stderr's codec to avoid recursion
929 when import.c tries to write to stderr in verbose mode. */
930 encoding_attr = PyObject_GetAttrString(std, "encoding");
931 if (encoding_attr != NULL) {
932 const char * encoding;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000933 encoding = _PyUnicode_AsString(encoding_attr);
Trent Nelson39e307e2008-03-19 06:45:48 +0000934 if (encoding != NULL) {
935 _PyCodec_Lookup(encoding);
936 }
937 }
938 PyErr_Clear(); /* Not a fatal error if codec isn't available */
939
Christian Heimesdb233082007-11-13 02:34:21 +0000940 PySys_SetObject("__stderr__", std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000941 PySys_SetObject("stderr", std);
942 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000943#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000944
Christian Heimes58cb1b82007-11-13 02:19:40 +0000945 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000946 error:
Christian Heimesdb233082007-11-13 02:34:21 +0000947 status = -1;
948 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000949
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000950 if (encoding)
951 free(encoding);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000952 Py_XDECREF(bimod);
953 Py_XDECREF(iomod);
954 return status;
955}
956
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000957/* Parse input from a file and execute it */
958
959int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000960PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000961 PyCompilerFlags *flags)
962{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000963 if (filename == NULL)
964 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000965 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000966 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000967 if (closeit)
968 fclose(fp);
969 return err;
970 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000971 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000972 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000973}
974
975int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000976PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000977{
Guido van Rossum82598051997-03-05 00:20:32 +0000978 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000979 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000980 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000981
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000982 if (flags == NULL) {
983 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000984 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000985 }
Guido van Rossum82598051997-03-05 00:20:32 +0000986 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000987 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000988 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
Guido van Rossum82598051997-03-05 00:20:32 +0000989 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000990 }
Guido van Rossum82598051997-03-05 00:20:32 +0000991 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000992 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000993 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
Guido van Rossum82598051997-03-05 00:20:32 +0000994 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000995 }
996 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000997 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000998 PRINT_TOTAL_REFS();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000999 if (ret == E_EOF)
1000 return 0;
1001 /*
1002 if (ret == E_NOMEM)
1003 return -1;
1004 */
1005 }
1006}
1007
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001008/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001009static int PARSER_FLAGS(PyCompilerFlags *flags)
1010{
1011 int parser_flags = 0;
1012 if (!flags)
1013 return 0;
1014 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1015 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1016 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1017 parser_flags |= PyPARSE_IGNORE_COOKIE;
Brett Cannone3944a52009-04-01 05:08:41 +00001018 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1019 parser_flags |= PyPARSE_BARRY_AS_BDFL;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001020 return parser_flags;
1021}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001022
Thomas Wouters89f507f2006-12-13 04:49:30 +00001023#if 0
1024/* Keep an example of flags with future keyword support. */
1025#define PARSER_FLAGS(flags) \
1026 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1027 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1028 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1029 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
1030#endif
1031
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001032int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001033PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001034{
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001035 PyObject *m, *d, *v, *w, *oenc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001036 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001037 PyArena *arena;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001038 char *ps1 = "", *ps2 = "", *enc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001039 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001040
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001041 if (fp == stdin) {
1042 /* Fetch encoding from sys.stdin */
1043 v = PySys_GetObject("stdin");
Christian Heimes2be03732007-11-15 02:26:46 +00001044 if (v == NULL || v == Py_None)
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001045 return -1;
1046 oenc = PyObject_GetAttrString(v, "encoding");
1047 if (!oenc)
1048 return -1;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001049 enc = _PyUnicode_AsString(oenc);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001050 }
Guido van Rossum82598051997-03-05 00:20:32 +00001051 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001052 if (v != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001053 v = PyObject_Str(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001054 if (v == NULL)
1055 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +00001056 else if (PyUnicode_Check(v))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001057 ps1 = _PyUnicode_AsString(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001058 }
Guido van Rossum82598051997-03-05 00:20:32 +00001059 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001060 if (w != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001061 w = PyObject_Str(w);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001062 if (w == NULL)
1063 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +00001064 else if (PyUnicode_Check(w))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001065 ps2 = _PyUnicode_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001066 }
Neal Norwitz9589ee22006-03-04 19:01:22 +00001067 arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001068 if (arena == NULL) {
1069 Py_XDECREF(v);
1070 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001071 Py_XDECREF(oenc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001072 return -1;
1073 }
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001074 mod = PyParser_ASTFromFile(fp, filename, enc,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001075 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001076 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001077 Py_XDECREF(v);
1078 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001079 Py_XDECREF(oenc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001080 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001081 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001082 if (errcode == E_EOF) {
1083 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001084 return E_EOF;
1085 }
Guido van Rossum82598051997-03-05 00:20:32 +00001086 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001087 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001088 }
Guido van Rossum82598051997-03-05 00:20:32 +00001089 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001090 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001091 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001092 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001093 }
Guido van Rossum82598051997-03-05 00:20:32 +00001094 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001095 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001096 PyArena_Free(arena);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001097 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001098 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001099 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001100 return -1;
1101 }
Guido van Rossum82598051997-03-05 00:20:32 +00001102 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001103 return 0;
1104}
1105
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001106/* Check whether a file maybe a pyc file: Look at the extension,
1107 the file type, and, if we may close it, at the first few bytes. */
1108
1109static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001110maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001111{
1112 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1113 return 1;
1114
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001115 /* Only look into the file if we are allowed to close it, since
1116 it then should also be seekable. */
1117 if (closeit) {
1118 /* Read only two bytes of the magic. If the file was opened in
1119 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1120 be read as they are on disk. */
1121 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1122 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +00001123 /* Mess: In case of -x, the stream is NOT at its start now,
1124 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001125 which makes the current stream position formally undefined,
1126 and a x-platform nightmare.
1127 Unfortunately, we have no direct way to know whether -x
1128 was specified. So we use a terrible hack: if the current
1129 stream position is not 0, we assume -x was specified, and
1130 give up. Bug 132850 on SourceForge spells out the
1131 hopelessness of trying anything else (fseek and ftell
1132 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +00001133 */
Tim Peters3e876562001-02-11 04:35:39 +00001134 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001135 if (ftell(fp) == 0) {
1136 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +00001137 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001138 ispyc = 1;
1139 rewind(fp);
1140 }
Tim Peters3e876562001-02-11 04:35:39 +00001141 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001142 }
1143 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001144}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001145
Guido van Rossum0df002c2000-08-27 19:21:52 +00001146int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001147PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001148 PyCompilerFlags *flags)
1149{
Guido van Rossum82598051997-03-05 00:20:32 +00001150 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001151 const char *ext;
Matthias Klose042f1332009-04-04 14:32:42 +00001152 int set_file_name = 0, ret, len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001153
Guido van Rossum82598051997-03-05 00:20:32 +00001154 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001155 if (m == NULL)
1156 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001157 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +00001158 if (PyDict_GetItemString(d, "__file__") == NULL) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001159 PyObject *f;
1160 f = PyUnicode_DecodeFSDefault(filename);
Fred Drake8ed02042002-10-17 21:24:58 +00001161 if (f == NULL)
1162 return -1;
1163 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1164 Py_DECREF(f);
1165 return -1;
1166 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001167 set_file_name = 1;
Fred Drake8ed02042002-10-17 21:24:58 +00001168 Py_DECREF(f);
1169 }
Matthias Klose042f1332009-04-04 14:32:42 +00001170 len = strlen(filename);
1171 ext = filename + len - (len > 4 ? 4 : 0);
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001172 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001173 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +00001174 if (closeit)
1175 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +00001176 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001177 fprintf(stderr, "python: Can't reopen .pyc file\n");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001178 ret = -1;
1179 goto done;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001180 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +00001181 /* Turn on optimization if a .pyo file is given */
1182 if (strcmp(ext, ".pyo") == 0)
1183 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001184 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001185 } else {
Tim Petersd08e3822003-04-17 15:24:21 +00001186 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001187 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001188 }
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001189 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001190 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001191 PyErr_Print();
Guido van Rossumd8faa362007-04-27 19:54:29 +00001192 ret = -1;
1193 goto done;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001194 }
Guido van Rossum82598051997-03-05 00:20:32 +00001195 Py_DECREF(v);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001196 ret = 0;
1197 done:
1198 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1199 PyErr_Clear();
1200 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001201}
1202
1203int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001204PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001205{
Guido van Rossum82598051997-03-05 00:20:32 +00001206 PyObject *m, *d, *v;
1207 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001208 if (m == NULL)
1209 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001210 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +00001211 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001212 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001213 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001214 return -1;
1215 }
Guido van Rossum82598051997-03-05 00:20:32 +00001216 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001217 return 0;
1218}
1219
Barry Warsaw035574d1997-08-29 22:07:17 +00001220static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001221parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1222 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001223{
1224 long hold;
1225 PyObject *v;
1226
1227 /* old style errors */
1228 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +00001229 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001230 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001231
1232 /* new style errors. `err' is an instance */
1233
1234 if (! (v = PyObject_GetAttrString(err, "msg")))
1235 goto finally;
1236 *message = v;
1237
1238 if (!(v = PyObject_GetAttrString(err, "filename")))
1239 goto finally;
1240 if (v == Py_None)
1241 *filename = NULL;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001242 else if (! (*filename = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001243 goto finally;
1244
1245 Py_DECREF(v);
1246 if (!(v = PyObject_GetAttrString(err, "lineno")))
1247 goto finally;
Christian Heimes217cfd12007-12-02 14:31:20 +00001248 hold = PyLong_AsLong(v);
Barry Warsaw035574d1997-08-29 22:07:17 +00001249 Py_DECREF(v);
1250 v = NULL;
1251 if (hold < 0 && PyErr_Occurred())
1252 goto finally;
1253 *lineno = (int)hold;
1254
1255 if (!(v = PyObject_GetAttrString(err, "offset")))
1256 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001257 if (v == Py_None) {
1258 *offset = -1;
1259 Py_DECREF(v);
1260 v = NULL;
1261 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001262 hold = PyLong_AsLong(v);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001263 Py_DECREF(v);
1264 v = NULL;
1265 if (hold < 0 && PyErr_Occurred())
1266 goto finally;
1267 *offset = (int)hold;
1268 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001269
1270 if (!(v = PyObject_GetAttrString(err, "text")))
1271 goto finally;
1272 if (v == Py_None)
1273 *text = NULL;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001274 else if (!PyUnicode_Check(v) ||
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001275 !(*text = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001276 goto finally;
1277 Py_DECREF(v);
1278 return 1;
1279
1280finally:
1281 Py_XDECREF(v);
1282 return 0;
1283}
1284
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001285void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001286PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001287{
Guido van Rossuma61691e1998-02-06 22:27:24 +00001288 PyErr_PrintEx(1);
1289}
1290
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001291static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001292print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001293{
1294 char *nl;
1295 if (offset >= 0) {
1296 if (offset > 0 && offset == (int)strlen(text))
1297 offset--;
1298 for (;;) {
1299 nl = strchr(text, '\n');
1300 if (nl == NULL || nl-text >= offset)
1301 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001302 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001303 text = nl+1;
1304 }
1305 while (*text == ' ' || *text == '\t') {
1306 text++;
1307 offset--;
1308 }
1309 }
1310 PyFile_WriteString(" ", f);
1311 PyFile_WriteString(text, f);
1312 if (*text == '\0' || text[strlen(text)-1] != '\n')
1313 PyFile_WriteString("\n", f);
1314 if (offset == -1)
1315 return;
1316 PyFile_WriteString(" ", f);
1317 offset--;
1318 while (offset > 0) {
1319 PyFile_WriteString(" ", f);
1320 offset--;
1321 }
1322 PyFile_WriteString("^\n", f);
1323}
1324
Guido van Rossum66e8e862001-03-23 17:54:43 +00001325static void
1326handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001327{
Neal Norwitz9589ee22006-03-04 19:01:22 +00001328 PyObject *exception, *value, *tb;
1329 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001330
Guido van Rossumd8faa362007-04-27 19:54:29 +00001331 if (Py_InspectFlag)
1332 /* Don't exit if -i flag was given. This flag is set to 0
1333 * when entering interactive mode for inspecting. */
1334 return;
1335
Guido van Rossum66e8e862001-03-23 17:54:43 +00001336 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001337 fflush(stdout);
1338 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001339 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001340 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001341 /* The error code should be in the `code' attribute. */
1342 PyObject *code = PyObject_GetAttrString(value, "code");
1343 if (code) {
1344 Py_DECREF(value);
1345 value = code;
1346 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001347 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001348 }
1349 /* If we failed to dig out the 'code' attribute,
1350 just let the else clause below print the error. */
1351 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001352 if (PyLong_Check(value))
1353 exitcode = (int)PyLong_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001354 else {
1355 PyObject_Print(value, stderr, Py_PRINT_RAW);
1356 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001357 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001358 }
Tim Peterscf615b52003-04-19 18:47:02 +00001359 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001360 /* Restore and clear the exception info, in order to properly decref
1361 * the exception, value, and traceback. If we just exit instead,
1362 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1363 * some finalizers from running.
1364 */
Tim Peterscf615b52003-04-19 18:47:02 +00001365 PyErr_Restore(exception, value, tb);
1366 PyErr_Clear();
1367 Py_Exit(exitcode);
1368 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001369}
1370
1371void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001372PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001373{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001374 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001375
1376 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1377 handle_system_exit();
1378 }
Guido van Rossum82598051997-03-05 00:20:32 +00001379 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001380 if (exception == NULL)
1381 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001382 PyErr_NormalizeException(&exception, &v, &tb);
Antoine Pitroue2dffc02008-08-26 22:02:58 +00001383 if (tb == NULL) {
1384 tb = Py_None;
1385 Py_INCREF(tb);
1386 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001387 PyException_SetTraceback(v, tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001388 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001389 return;
Georg Brandl86b2fb92008-07-16 03:43:04 +00001390 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001391 if (set_sys_last_vars) {
1392 PySys_SetObject("last_type", exception);
1393 PySys_SetObject("last_value", v);
Benjamin Petersone6528212008-07-15 15:32:09 +00001394 PySys_SetObject("last_traceback", tb);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001395 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001396 hook = PySys_GetObject("excepthook");
1397 if (hook) {
Benjamin Petersone6528212008-07-15 15:32:09 +00001398 PyObject *args = PyTuple_Pack(3, exception, v, tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001399 PyObject *result = PyEval_CallObject(hook, args);
1400 if (result == NULL) {
1401 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001402 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1403 handle_system_exit();
1404 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001405 PyErr_Fetch(&exception2, &v2, &tb2);
1406 PyErr_NormalizeException(&exception2, &v2, &tb2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001407 /* It should not be possible for exception2 or v2
1408 to be NULL. However PyErr_Display() can't
1409 tolerate NULLs, so just be safe. */
1410 if (exception2 == NULL) {
1411 exception2 = Py_None;
1412 Py_INCREF(exception2);
1413 }
1414 if (v2 == NULL) {
1415 v2 = Py_None;
1416 Py_INCREF(v2);
1417 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001418 fflush(stdout);
1419 PySys_WriteStderr("Error in sys.excepthook:\n");
1420 PyErr_Display(exception2, v2, tb2);
1421 PySys_WriteStderr("\nOriginal exception was:\n");
1422 PyErr_Display(exception, v, tb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001423 Py_DECREF(exception2);
1424 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001425 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001426 }
1427 Py_XDECREF(result);
1428 Py_XDECREF(args);
1429 } else {
1430 PySys_WriteStderr("sys.excepthook is missing\n");
1431 PyErr_Display(exception, v, tb);
1432 }
1433 Py_XDECREF(exception);
1434 Py_XDECREF(v);
1435 Py_XDECREF(tb);
1436}
1437
Benjamin Petersone6528212008-07-15 15:32:09 +00001438static void
1439print_exception(PyObject *f, PyObject *value)
1440{
1441 int err = 0;
1442 PyObject *type, *tb;
1443
Benjamin Peterson26582602008-08-23 20:08:07 +00001444 if (!PyExceptionInstance_Check(value)) {
1445 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1446 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1447 PyFile_WriteString(" found\n", f);
1448 return;
1449 }
1450
Benjamin Petersone6528212008-07-15 15:32:09 +00001451 Py_INCREF(value);
1452 fflush(stdout);
1453 type = (PyObject *) Py_TYPE(value);
1454 tb = PyException_GetTraceback(value);
1455 if (tb && tb != Py_None)
1456 err = PyTraceBack_Print(tb, f);
1457 if (err == 0 &&
1458 PyObject_HasAttrString(value, "print_file_and_line"))
1459 {
1460 PyObject *message;
1461 const char *filename, *text;
1462 int lineno, offset;
1463 if (!parse_syntax_error(value, &message, &filename,
1464 &lineno, &offset, &text))
1465 PyErr_Clear();
1466 else {
1467 char buf[10];
1468 PyFile_WriteString(" File \"", f);
1469 if (filename == NULL)
1470 PyFile_WriteString("<string>", f);
1471 else
1472 PyFile_WriteString(filename, f);
1473 PyFile_WriteString("\", line ", f);
1474 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1475 PyFile_WriteString(buf, f);
1476 PyFile_WriteString("\n", f);
1477 if (text != NULL)
1478 print_error_text(f, offset, text);
1479 Py_DECREF(value);
1480 value = message;
1481 /* Can't be bothered to check all those
1482 PyFile_WriteString() calls */
1483 if (PyErr_Occurred())
1484 err = -1;
1485 }
1486 }
1487 if (err) {
1488 /* Don't do anything else */
1489 }
1490 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001491 PyObject* moduleName;
Thomas Hellerd88ddfa2008-07-15 17:14:51 +00001492 char* className;
1493 assert(PyExceptionClass_Check(type));
1494 className = PyExceptionClass_Name(type);
Benjamin Petersone6528212008-07-15 15:32:09 +00001495 if (className != NULL) {
1496 char *dot = strrchr(className, '.');
1497 if (dot != NULL)
1498 className = dot+1;
1499 }
1500
1501 moduleName = PyObject_GetAttrString(type, "__module__");
1502 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1503 {
1504 Py_DECREF(moduleName);
1505 err = PyFile_WriteString("<unknown>", f);
1506 }
1507 else {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001508 char* modstr = _PyUnicode_AsString(moduleName);
Benjamin Petersone6528212008-07-15 15:32:09 +00001509 if (modstr && strcmp(modstr, "builtins"))
1510 {
1511 err = PyFile_WriteString(modstr, f);
1512 err += PyFile_WriteString(".", f);
1513 }
1514 Py_DECREF(moduleName);
1515 }
1516 if (err == 0) {
1517 if (className == NULL)
1518 err = PyFile_WriteString("<unknown>", f);
1519 else
1520 err = PyFile_WriteString(className, f);
1521 }
1522 }
1523 if (err == 0 && (value != Py_None)) {
1524 PyObject *s = PyObject_Str(value);
1525 /* only print colon if the str() of the
1526 object is not the empty string
1527 */
1528 if (s == NULL)
1529 err = -1;
1530 else if (!PyUnicode_Check(s) ||
1531 PyUnicode_GetSize(s) != 0)
1532 err = PyFile_WriteString(": ", f);
1533 if (err == 0)
1534 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1535 Py_XDECREF(s);
1536 }
1537 /* try to write a newline in any case */
1538 err += PyFile_WriteString("\n", f);
1539 Py_XDECREF(tb);
1540 Py_DECREF(value);
1541 /* If an error happened here, don't show it.
1542 XXX This is wrong, but too many callers rely on this behavior. */
1543 if (err != 0)
1544 PyErr_Clear();
1545}
1546
1547static const char *cause_message =
1548 "\nThe above exception was the direct cause "
1549 "of the following exception:\n\n";
1550
1551static const char *context_message =
1552 "\nDuring handling of the above exception, "
1553 "another exception occurred:\n\n";
1554
1555static void
1556print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1557{
1558 int err = 0, res;
1559 PyObject *cause, *context;
1560
1561 if (seen != NULL) {
1562 /* Exception chaining */
1563 if (PySet_Add(seen, value) == -1)
1564 PyErr_Clear();
1565 else if (PyExceptionInstance_Check(value)) {
1566 cause = PyException_GetCause(value);
1567 context = PyException_GetContext(value);
1568 if (cause) {
1569 res = PySet_Contains(seen, cause);
1570 if (res == -1)
1571 PyErr_Clear();
1572 if (res == 0) {
1573 print_exception_recursive(
1574 f, cause, seen);
1575 err |= PyFile_WriteString(
1576 cause_message, f);
1577 }
1578 }
Antoine Pitrou7b0d4a22009-11-28 16:12:28 +00001579 else if (context) {
Benjamin Petersone6528212008-07-15 15:32:09 +00001580 res = PySet_Contains(seen, context);
1581 if (res == -1)
1582 PyErr_Clear();
1583 if (res == 0) {
1584 print_exception_recursive(
1585 f, context, seen);
1586 err |= PyFile_WriteString(
1587 context_message, f);
1588 }
1589 }
1590 Py_XDECREF(context);
1591 Py_XDECREF(cause);
1592 }
1593 }
1594 print_exception(f, value);
1595 if (err != 0)
1596 PyErr_Clear();
1597}
1598
Thomas Wouters477c8d52006-05-27 19:21:47 +00001599void
1600PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001601{
Benjamin Petersone6528212008-07-15 15:32:09 +00001602 PyObject *seen;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001603 PyObject *f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +00001604 if (f == Py_None) {
1605 /* pass */
1606 }
1607 else if (f == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001608 _PyObject_Dump(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001609 fprintf(stderr, "lost sys.stderr\n");
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001610 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001611 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001612 /* We choose to ignore seen being possibly NULL, and report
1613 at least the main exception (it could be a MemoryError).
1614 */
1615 seen = PySet_New(NULL);
1616 if (seen == NULL)
1617 PyErr_Clear();
1618 print_exception_recursive(f, value, seen);
1619 Py_XDECREF(seen);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001620 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001621}
1622
Guido van Rossum82598051997-03-05 00:20:32 +00001623PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001624PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001625 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001626{
Neal Norwitze92fba02006-03-04 18:52:26 +00001627 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001628 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001629 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001630 if (arena == NULL)
1631 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001632
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001633 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001634 if (mod != NULL)
1635 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001636 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001637 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001638}
1639
1640PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001641PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001642 PyObject *locals, int closeit, PyCompilerFlags *flags)
1643{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001644 PyObject *ret;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001645 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001646 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001647 if (arena == NULL)
1648 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001649
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001650 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001651 flags, NULL, arena);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001652 if (closeit)
1653 fclose(fp);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001654 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001655 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001656 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001657 }
Neal Norwitze92fba02006-03-04 18:52:26 +00001658 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001659 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001660 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001661}
1662
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001663static void
1664flush_io(void)
1665{
1666 PyObject *f, *r;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001667 PyObject *type, *value, *traceback;
1668
1669 /* Save the current exception */
1670 PyErr_Fetch(&type, &value, &traceback);
1671
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001672 f = PySys_GetObject("stderr");
1673 if (f != NULL) {
1674 r = PyObject_CallMethod(f, "flush", "");
1675 if (r)
1676 Py_DECREF(r);
1677 else
1678 PyErr_Clear();
1679 }
1680 f = PySys_GetObject("stdout");
1681 if (f != NULL) {
1682 r = PyObject_CallMethod(f, "flush", "");
1683 if (r)
1684 Py_DECREF(r);
1685 else
1686 PyErr_Clear();
1687 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001688
1689 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001690}
1691
Guido van Rossum82598051997-03-05 00:20:32 +00001692static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001693run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001694 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001695{
Guido van Rossum82598051997-03-05 00:20:32 +00001696 PyCodeObject *co;
1697 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001698 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001699 if (co == NULL)
1700 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001701 v = PyEval_EvalCode(co, globals, locals);
1702 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001703 return v;
1704}
1705
Guido van Rossum82598051997-03-05 00:20:32 +00001706static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001707run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001708 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001709{
Guido van Rossum82598051997-03-05 00:20:32 +00001710 PyCodeObject *co;
1711 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001712 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001713 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001714
Guido van Rossum82598051997-03-05 00:20:32 +00001715 magic = PyMarshal_ReadLongFromFile(fp);
1716 if (magic != PyImport_GetMagicNumber()) {
1717 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001718 "Bad magic number in .pyc file");
1719 return NULL;
1720 }
Guido van Rossum82598051997-03-05 00:20:32 +00001721 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001722 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001723 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001724 if (v == NULL || !PyCode_Check(v)) {
1725 Py_XDECREF(v);
1726 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001727 "Bad code object in .pyc file");
1728 return NULL;
1729 }
Guido van Rossum82598051997-03-05 00:20:32 +00001730 co = (PyCodeObject *)v;
1731 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001732 if (v && flags)
1733 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001734 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001735 return v;
1736}
1737
Guido van Rossum82598051997-03-05 00:20:32 +00001738PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001739Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001740 PyCompilerFlags *flags)
1741{
Guido van Rossum82598051997-03-05 00:20:32 +00001742 PyCodeObject *co;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001743 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001744 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001745 if (arena == NULL)
1746 return NULL;
1747
1748 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001749 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001750 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001751 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001752 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001753 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001754 PyObject *result = PyAST_mod2obj(mod);
1755 PyArena_Free(arena);
1756 return result;
1757 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001758 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001759 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001760 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001761}
1762
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001763struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001764Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001765{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001766 struct symtable *st;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001767 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001768 PyCompilerFlags flags;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001769 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001770 if (arena == NULL)
1771 return NULL;
1772
Christian Heimesb1b3efc2008-03-26 23:24:27 +00001773 flags.cf_flags = 0;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001774 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001775 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001776 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001777 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001778 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001779 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001780 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001781 return st;
1782}
1783
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001784/* Preferred access to parser is through AST. */
1785mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001786PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001787 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001788{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001789 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001790 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001791 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001792 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001793
1794 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001795 &_PyParser_Grammar, start, &err,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001796 &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001797 if (flags == NULL) {
1798 localflags.cf_flags = 0;
1799 flags = &localflags;
1800 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001801 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001802 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001803 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001804 PyNode_Free(n);
1805 return mod;
1806 }
1807 else {
1808 err_input(&err);
1809 return NULL;
1810 }
1811}
1812
1813mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001814PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1815 int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001816 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001817 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001818{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001820 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001821 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001822 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001823
Christian Heimes4d6ec852008-03-26 22:34:47 +00001824 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001825 &_PyParser_Grammar,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001826 start, ps1, ps2, &err, &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001827 if (flags == NULL) {
1828 localflags.cf_flags = 0;
1829 flags = &localflags;
1830 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001832 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001833 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001834 PyNode_Free(n);
1835 return mod;
1836 }
1837 else {
1838 err_input(&err);
1839 if (errcode)
1840 *errcode = err.error;
1841 return NULL;
1842 }
1843}
1844
Guido van Rossuma110aa61994-08-29 12:50:44 +00001845/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001846
Guido van Rossuma110aa61994-08-29 12:50:44 +00001847node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001848PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001849{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001850 perrdetail err;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001851 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1852 &_PyParser_Grammar,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001853 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001854 if (n == NULL)
1855 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001856
Guido van Rossuma110aa61994-08-29 12:50:44 +00001857 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001858}
1859
Guido van Rossuma110aa61994-08-29 12:50:44 +00001860/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001861
Guido van Rossuma110aa61994-08-29 12:50:44 +00001862node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001863PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001864{
Tim Petersfe2127d2001-07-16 05:37:24 +00001865 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001866 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1867 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001868 if (n == NULL)
1869 err_input(&err);
1870 return n;
1871}
1872
1873node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001874PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001875 int start, int flags)
1876{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001877 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001878 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1879 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001880 if (n == NULL)
1881 err_input(&err);
1882 return n;
1883}
1884
1885node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001886PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001887{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001888 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001889}
1890
Guido van Rossum66ebd912003-04-17 16:02:26 +00001891/* May want to move a more generalized form of this to parsetok.c or
1892 even parser modules. */
1893
1894void
1895PyParser_SetError(perrdetail *err)
1896{
1897 err_input(err);
1898}
1899
Guido van Rossuma110aa61994-08-29 12:50:44 +00001900/* Set the error appropriate to the given input error code (see errcode.h) */
1901
1902static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001903err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001904{
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001905 PyObject *v, *w, *errtype, *errtext;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001906 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001907 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001908 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001909 switch (err->error) {
1910 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001911 errtype = PyExc_IndentationError;
1912 if (err->expected == INDENT)
1913 msg = "expected an indented block";
1914 else if (err->token == INDENT)
1915 msg = "unexpected indent";
1916 else if (err->token == DEDENT)
1917 msg = "unexpected unindent";
1918 else {
1919 errtype = PyExc_SyntaxError;
1920 msg = "invalid syntax";
1921 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001922 break;
1923 case E_TOKEN:
1924 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001925 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001926 case E_EOFS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001927 msg = "EOF while scanning triple-quoted string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001928 break;
1929 case E_EOLS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001930 msg = "EOL while scanning string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001931 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001932 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001933 if (!PyErr_Occurred())
1934 PyErr_SetNone(PyExc_KeyboardInterrupt);
Georg Brandl3dbca812008-07-23 16:10:53 +00001935 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001936 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001937 PyErr_NoMemory();
Georg Brandl3dbca812008-07-23 16:10:53 +00001938 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001939 case E_EOF:
1940 msg = "unexpected EOF while parsing";
1941 break;
Fred Drake85f36392000-07-11 17:53:00 +00001942 case E_TABSPACE:
1943 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001944 msg = "inconsistent use of tabs and spaces in indentation";
1945 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001946 case E_OVERFLOW:
1947 msg = "expression too long";
1948 break;
Fred Drake85f36392000-07-11 17:53:00 +00001949 case E_DEDENT:
1950 errtype = PyExc_IndentationError;
1951 msg = "unindent does not match any outer indentation level";
1952 break;
1953 case E_TOODEEP:
1954 errtype = PyExc_IndentationError;
1955 msg = "too many levels of indentation";
1956 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001957 case E_DECODE: {
1958 PyObject *type, *value, *tb;
1959 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001960 if (value != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001961 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001962 if (u != NULL) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001963 msg = _PyUnicode_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001964 }
1965 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001966 if (msg == NULL)
1967 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001968 Py_XDECREF(type);
1969 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001970 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001971 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001972 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001973 case E_LINECONT:
1974 msg = "unexpected character after line continuation character";
1975 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001976
1977 case E_IDENTIFIER:
1978 msg = "invalid character in identifier";
1979 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001980 default:
1981 fprintf(stderr, "error=%d\n", err->error);
1982 msg = "unknown parsing error";
1983 break;
1984 }
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001985 /* err->text may not be UTF-8 in case of decoding errors.
1986 Explicitly convert to an object. */
1987 if (!err->text) {
1988 errtext = Py_None;
1989 Py_INCREF(Py_None);
1990 } else {
1991 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1992 "replace");
1993 }
1994 v = Py_BuildValue("(ziiN)", err->filename,
1995 err->lineno, err->offset, errtext);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001996 w = NULL;
1997 if (v != NULL)
1998 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001999 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00002000 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00002001 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00002002 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002003cleanup:
2004 if (err->text != NULL) {
2005 PyObject_FREE(err->text);
2006 err->text = NULL;
2007 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002008}
2009
2010/* Print fatal error message and abort */
2011
2012void
Tim Peters7c321a82002-07-09 02:57:01 +00002013Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002014{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00002015 fprintf(stderr, "Fatal Python error: %s\n", msg);
Jesse Nollera9314042009-03-31 22:36:44 +00002016 fflush(stderr); /* it helps in Windows debug build */
Guido van Rossumce3a72a2007-10-19 23:16:50 +00002017 if (PyErr_Occurred()) {
2018 PyErr_Print();
2019 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002020#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002021 {
2022 size_t len = strlen(msg);
2023 WCHAR* buffer;
2024 size_t i;
2025
2026 /* Convert the message to wchar_t. This uses a simple one-to-one
2027 conversion, assuming that the this error message actually uses ASCII
2028 only. If this ceases to be true, we will have to convert. */
2029 buffer = alloca( (len+1) * (sizeof *buffer));
2030 for( i=0; i<=len; ++i)
2031 buffer[i] = msg[i];
2032 OutputDebugStringW(L"Fatal Python error: ");
2033 OutputDebugStringW(buffer);
2034 OutputDebugStringW(L"\n");
2035 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002036#ifdef _DEBUG
2037 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002038#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002039#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002040 abort();
2041}
2042
2043/* Clean up and exit */
2044
Guido van Rossuma110aa61994-08-29 12:50:44 +00002045#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002046#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002047#endif
2048
Collin Winter670e6922007-03-21 02:57:17 +00002049static void (*pyexitfunc)(void) = NULL;
2050/* For the atexit module. */
2051void _Py_PyAtExit(void (*func)(void))
2052{
2053 pyexitfunc = func;
2054}
2055
2056static void
2057call_py_exitfuncs(void)
2058{
Guido van Rossum98297ee2007-11-06 21:34:58 +00002059 if (pyexitfunc == NULL)
Collin Winter670e6922007-03-21 02:57:17 +00002060 return;
2061
2062 (*pyexitfunc)();
2063 PyErr_Clear();
2064}
2065
Antoine Pitrou011bd622009-10-20 21:52:47 +00002066/* Wait until threading._shutdown completes, provided
2067 the threading module was imported in the first place.
2068 The shutdown routine will wait until all non-daemon
2069 "threading" threads have completed. */
2070static void
2071wait_for_thread_shutdown(void)
2072{
2073#ifdef WITH_THREAD
2074 PyObject *result;
2075 PyThreadState *tstate = PyThreadState_GET();
2076 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2077 "threading");
2078 if (threading == NULL) {
2079 /* threading not imported */
2080 PyErr_Clear();
2081 return;
2082 }
2083 result = PyObject_CallMethod(threading, "_shutdown", "");
2084 if (result == NULL) {
2085 PyErr_WriteUnraisable(threading);
2086 }
2087 else {
2088 Py_DECREF(result);
2089 }
2090 Py_DECREF(threading);
2091#endif
2092}
2093
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002094#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002095static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002096static int nexitfuncs = 0;
2097
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002098int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002099{
2100 if (nexitfuncs >= NEXITFUNCS)
2101 return -1;
2102 exitfuncs[nexitfuncs++] = func;
2103 return 0;
2104}
2105
Guido van Rossumcc283f51997-08-05 02:22:03 +00002106static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002107call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002108{
Guido van Rossum1662dd51994-09-07 14:38:28 +00002109 while (nexitfuncs > 0)
2110 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002111
2112 fflush(stdout);
2113 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002114}
2115
2116void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002117Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002118{
Guido van Rossumcc283f51997-08-05 02:22:03 +00002119 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002120
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002121 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002122}
2123
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002124static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002125initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002126{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002127#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002128 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002129#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002130#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002131 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002132#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002133#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002134 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002135#endif
Guido van Rossum82598051997-03-05 00:20:32 +00002136 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002137}
2138
Guido van Rossum7433b121997-02-14 19:45:36 +00002139
2140/*
2141 * The file descriptor fd is considered ``interactive'' if either
2142 * a) isatty(fd) is TRUE, or
2143 * b) the -i flag was given, and the filename associated with
2144 * the descriptor is NULL or "<stdin>" or "???".
2145 */
2146int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002147Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002148{
2149 if (isatty((int)fileno(fp)))
2150 return 1;
2151 if (!Py_InteractiveFlag)
2152 return 0;
2153 return (filename == NULL) ||
2154 (strcmp(filename, "<stdin>") == 0) ||
2155 (strcmp(filename, "???") == 0);
2156}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002157
2158
Tim Petersd08e3822003-04-17 15:24:21 +00002159#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002160#if defined(WIN32) && defined(_MSC_VER)
2161
2162/* Stack checking for Microsoft C */
2163
2164#include <malloc.h>
2165#include <excpt.h>
2166
Fred Drakee8de31c2000-08-31 05:38:39 +00002167/*
2168 * Return non-zero when we run out of memory on the stack; zero otherwise.
2169 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002170int
Fred Drake399739f2000-08-31 05:52:44 +00002171PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002172{
2173 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00002174 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002175 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00002176 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002177 return 0;
Christian Heimes7131fd92008-02-19 14:21:46 +00002178 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
Trent Nelson39e307e2008-03-19 06:45:48 +00002179 EXCEPTION_EXECUTE_HANDLER :
2180 EXCEPTION_CONTINUE_SEARCH) {
Christian Heimes7131fd92008-02-19 14:21:46 +00002181 int errcode = _resetstkoflw();
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +00002182 if (errcode == 0)
Christian Heimes7131fd92008-02-19 14:21:46 +00002183 {
2184 Py_FatalError("Could not reset the stack!");
2185 }
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002186 }
2187 return 1;
2188}
2189
2190#endif /* WIN32 && _MSC_VER */
2191
2192/* Alternate implementations can be added here... */
2193
2194#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002195
2196
2197/* Wrappers around sigaction() or signal(). */
2198
2199PyOS_sighandler_t
2200PyOS_getsig(int sig)
2201{
2202#ifdef HAVE_SIGACTION
2203 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002204 if (sigaction(sig, NULL, &context) == -1)
2205 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00002206 return context.sa_handler;
2207#else
2208 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002209/* Special signal handling for the secure CRT in Visual Studio 2005 */
2210#if defined(_MSC_VER) && _MSC_VER >= 1400
2211 switch (sig) {
2212 /* Only these signals are valid */
2213 case SIGINT:
2214 case SIGILL:
2215 case SIGFPE:
2216 case SIGSEGV:
2217 case SIGTERM:
2218 case SIGBREAK:
2219 case SIGABRT:
2220 break;
2221 /* Don't call signal() with other values or it will assert */
2222 default:
2223 return SIG_ERR;
2224 }
2225#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002226 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002227 if (handler != SIG_ERR)
2228 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00002229 return handler;
2230#endif
2231}
2232
2233PyOS_sighandler_t
2234PyOS_setsig(int sig, PyOS_sighandler_t handler)
2235{
2236#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002237 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00002238 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002239 sigemptyset(&context.sa_mask);
2240 context.sa_flags = 0;
2241 if (sigaction(sig, &context, &ocontext) == -1)
2242 return SIG_ERR;
2243 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002244#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002245 PyOS_sighandler_t oldhandler;
2246 oldhandler = signal(sig, handler);
2247#ifdef HAVE_SIGINTERRUPT
2248 siginterrupt(sig, 1);
2249#endif
2250 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002251#endif
2252}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002253
2254/* Deprecated C API functions still provided for binary compatiblity */
2255
2256#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002257PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002258PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2259{
2260 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2261}
2262
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002263#undef PyParser_SimpleParseString
2264PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002265PyParser_SimpleParseString(const char *str, int start)
2266{
2267 return PyParser_SimpleParseStringFlags(str, start, 0);
2268}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002269
2270#undef PyRun_AnyFile
2271PyAPI_FUNC(int)
2272PyRun_AnyFile(FILE *fp, const char *name)
2273{
2274 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
2275}
2276
2277#undef PyRun_AnyFileEx
2278PyAPI_FUNC(int)
2279PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2280{
2281 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
2282}
2283
2284#undef PyRun_AnyFileFlags
2285PyAPI_FUNC(int)
2286PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2287{
2288 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2289}
2290
2291#undef PyRun_File
2292PyAPI_FUNC(PyObject *)
2293PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2294{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002295 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002296}
2297
2298#undef PyRun_FileEx
2299PyAPI_FUNC(PyObject *)
2300PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2301{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002302 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002303}
2304
2305#undef PyRun_FileFlags
2306PyAPI_FUNC(PyObject *)
2307PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2308 PyCompilerFlags *flags)
2309{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002310 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002311}
2312
2313#undef PyRun_SimpleFile
2314PyAPI_FUNC(int)
2315PyRun_SimpleFile(FILE *f, const char *p)
2316{
2317 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
2318}
2319
2320#undef PyRun_SimpleFileEx
2321PyAPI_FUNC(int)
2322PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2323{
2324 return PyRun_SimpleFileExFlags(f, p, c, NULL);
2325}
2326
2327
2328#undef PyRun_String
2329PyAPI_FUNC(PyObject *)
2330PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2331{
2332 return PyRun_StringFlags(str, s, g, l, NULL);
2333}
2334
2335#undef PyRun_SimpleString
2336PyAPI_FUNC(int)
2337PyRun_SimpleString(const char *s)
2338{
2339 return PyRun_SimpleStringFlags(s, NULL);
2340}
2341
2342#undef Py_CompileString
2343PyAPI_FUNC(PyObject *)
2344Py_CompileString(const char *str, const char *p, int s)
2345{
2346 return Py_CompileStringFlags(str, p, s, NULL);
2347}
2348
2349#undef PyRun_InteractiveOne
2350PyAPI_FUNC(int)
2351PyRun_InteractiveOne(FILE *f, const char *p)
2352{
2353 return PyRun_InteractiveOneFlags(f, p, NULL);
2354}
2355
2356#undef PyRun_InteractiveLoop
2357PyAPI_FUNC(int)
2358PyRun_InteractiveLoop(FILE *f, const char *p)
2359{
2360 return PyRun_InteractiveLoopFlags(f, p, NULL);
2361}
2362
2363#ifdef __cplusplus
2364}
2365#endif