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