blob: 7add832387cf8ab3befa8fd60df6f5b6092d79f9 [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;
1014 return parser_flags;
1015}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001016
Thomas Wouters89f507f2006-12-13 04:49:30 +00001017#if 0
1018/* Keep an example of flags with future keyword support. */
1019#define PARSER_FLAGS(flags) \
1020 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1021 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1022 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1023 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
1024#endif
1025
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001026int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001027PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001028{
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001029 PyObject *m, *d, *v, *w, *oenc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001030 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001031 PyArena *arena;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001032 char *ps1 = "", *ps2 = "", *enc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001033 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001034
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001035 if (fp == stdin) {
1036 /* Fetch encoding from sys.stdin */
1037 v = PySys_GetObject("stdin");
Christian Heimes2be03732007-11-15 02:26:46 +00001038 if (v == NULL || v == Py_None)
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001039 return -1;
1040 oenc = PyObject_GetAttrString(v, "encoding");
1041 if (!oenc)
1042 return -1;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001043 enc = _PyUnicode_AsString(oenc);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001044 }
Guido van Rossum82598051997-03-05 00:20:32 +00001045 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001046 if (v != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001047 v = PyObject_Str(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001048 if (v == NULL)
1049 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +00001050 else if (PyUnicode_Check(v))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001051 ps1 = _PyUnicode_AsString(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001052 }
Guido van Rossum82598051997-03-05 00:20:32 +00001053 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001054 if (w != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001055 w = PyObject_Str(w);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001056 if (w == NULL)
1057 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +00001058 else if (PyUnicode_Check(w))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001059 ps2 = _PyUnicode_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001060 }
Neal Norwitz9589ee22006-03-04 19:01:22 +00001061 arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001062 if (arena == NULL) {
1063 Py_XDECREF(v);
1064 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001065 Py_XDECREF(oenc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001066 return -1;
1067 }
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001068 mod = PyParser_ASTFromFile(fp, filename, enc,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001069 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001070 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001071 Py_XDECREF(v);
1072 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001073 Py_XDECREF(oenc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001074 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001075 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001076 if (errcode == E_EOF) {
1077 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001078 return E_EOF;
1079 }
Guido van Rossum82598051997-03-05 00:20:32 +00001080 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001081 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001082 }
Guido van Rossum82598051997-03-05 00:20:32 +00001083 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001084 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001085 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001086 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001087 }
Guido van Rossum82598051997-03-05 00:20:32 +00001088 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001089 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001090 PyArena_Free(arena);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001091 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001092 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001093 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001094 return -1;
1095 }
Guido van Rossum82598051997-03-05 00:20:32 +00001096 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001097 return 0;
1098}
1099
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001100/* Check whether a file maybe a pyc file: Look at the extension,
1101 the file type, and, if we may close it, at the first few bytes. */
1102
1103static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001104maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001105{
1106 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1107 return 1;
1108
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001109 /* Only look into the file if we are allowed to close it, since
1110 it then should also be seekable. */
1111 if (closeit) {
1112 /* Read only two bytes of the magic. If the file was opened in
1113 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1114 be read as they are on disk. */
1115 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1116 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +00001117 /* Mess: In case of -x, the stream is NOT at its start now,
1118 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001119 which makes the current stream position formally undefined,
1120 and a x-platform nightmare.
1121 Unfortunately, we have no direct way to know whether -x
1122 was specified. So we use a terrible hack: if the current
1123 stream position is not 0, we assume -x was specified, and
1124 give up. Bug 132850 on SourceForge spells out the
1125 hopelessness of trying anything else (fseek and ftell
1126 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +00001127 */
Tim Peters3e876562001-02-11 04:35:39 +00001128 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001129 if (ftell(fp) == 0) {
1130 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +00001131 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001132 ispyc = 1;
1133 rewind(fp);
1134 }
Tim Peters3e876562001-02-11 04:35:39 +00001135 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001136 }
1137 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001138}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001139
Guido van Rossum0df002c2000-08-27 19:21:52 +00001140int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001141PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001142 PyCompilerFlags *flags)
1143{
Guido van Rossum82598051997-03-05 00:20:32 +00001144 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001145 const char *ext;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001146 int set_file_name = 0, ret;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001147
Guido van Rossum82598051997-03-05 00:20:32 +00001148 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001149 if (m == NULL)
1150 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001151 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +00001152 if (PyDict_GetItemString(d, "__file__") == NULL) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001153 PyObject *f;
1154 f = PyUnicode_DecodeFSDefault(filename);
Fred Drake8ed02042002-10-17 21:24:58 +00001155 if (f == NULL)
1156 return -1;
1157 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1158 Py_DECREF(f);
1159 return -1;
1160 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001161 set_file_name = 1;
Fred Drake8ed02042002-10-17 21:24:58 +00001162 Py_DECREF(f);
1163 }
Guido van Rossumfdef2711994-09-14 13:31:04 +00001164 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001165 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001166 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +00001167 if (closeit)
1168 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +00001169 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001170 fprintf(stderr, "python: Can't reopen .pyc file\n");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001171 ret = -1;
1172 goto done;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001173 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +00001174 /* Turn on optimization if a .pyo file is given */
1175 if (strcmp(ext, ".pyo") == 0)
1176 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001177 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001178 } else {
Tim Petersd08e3822003-04-17 15:24:21 +00001179 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001180 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001181 }
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001182 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001183 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001184 PyErr_Print();
Guido van Rossumd8faa362007-04-27 19:54:29 +00001185 ret = -1;
1186 goto done;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001187 }
Guido van Rossum82598051997-03-05 00:20:32 +00001188 Py_DECREF(v);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001189 ret = 0;
1190 done:
1191 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1192 PyErr_Clear();
1193 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001194}
1195
1196int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001197PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001198{
Guido van Rossum82598051997-03-05 00:20:32 +00001199 PyObject *m, *d, *v;
1200 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001201 if (m == NULL)
1202 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001203 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +00001204 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001205 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001206 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001207 return -1;
1208 }
Guido van Rossum82598051997-03-05 00:20:32 +00001209 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001210 return 0;
1211}
1212
Barry Warsaw035574d1997-08-29 22:07:17 +00001213static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001214parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1215 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001216{
1217 long hold;
1218 PyObject *v;
1219
1220 /* old style errors */
1221 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +00001222 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001223 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001224
1225 /* new style errors. `err' is an instance */
1226
1227 if (! (v = PyObject_GetAttrString(err, "msg")))
1228 goto finally;
1229 *message = v;
1230
1231 if (!(v = PyObject_GetAttrString(err, "filename")))
1232 goto finally;
1233 if (v == Py_None)
1234 *filename = NULL;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001235 else if (! (*filename = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001236 goto finally;
1237
1238 Py_DECREF(v);
1239 if (!(v = PyObject_GetAttrString(err, "lineno")))
1240 goto finally;
Christian Heimes217cfd12007-12-02 14:31:20 +00001241 hold = PyLong_AsLong(v);
Barry Warsaw035574d1997-08-29 22:07:17 +00001242 Py_DECREF(v);
1243 v = NULL;
1244 if (hold < 0 && PyErr_Occurred())
1245 goto finally;
1246 *lineno = (int)hold;
1247
1248 if (!(v = PyObject_GetAttrString(err, "offset")))
1249 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001250 if (v == Py_None) {
1251 *offset = -1;
1252 Py_DECREF(v);
1253 v = NULL;
1254 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001255 hold = PyLong_AsLong(v);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001256 Py_DECREF(v);
1257 v = NULL;
1258 if (hold < 0 && PyErr_Occurred())
1259 goto finally;
1260 *offset = (int)hold;
1261 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001262
1263 if (!(v = PyObject_GetAttrString(err, "text")))
1264 goto finally;
1265 if (v == Py_None)
1266 *text = NULL;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001267 else if (!PyUnicode_Check(v) ||
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001268 !(*text = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001269 goto finally;
1270 Py_DECREF(v);
1271 return 1;
1272
1273finally:
1274 Py_XDECREF(v);
1275 return 0;
1276}
1277
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001278void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001279PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001280{
Guido van Rossuma61691e1998-02-06 22:27:24 +00001281 PyErr_PrintEx(1);
1282}
1283
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001284static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001285print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001286{
1287 char *nl;
1288 if (offset >= 0) {
1289 if (offset > 0 && offset == (int)strlen(text))
1290 offset--;
1291 for (;;) {
1292 nl = strchr(text, '\n');
1293 if (nl == NULL || nl-text >= offset)
1294 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001295 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001296 text = nl+1;
1297 }
1298 while (*text == ' ' || *text == '\t') {
1299 text++;
1300 offset--;
1301 }
1302 }
1303 PyFile_WriteString(" ", f);
1304 PyFile_WriteString(text, f);
1305 if (*text == '\0' || text[strlen(text)-1] != '\n')
1306 PyFile_WriteString("\n", f);
1307 if (offset == -1)
1308 return;
1309 PyFile_WriteString(" ", f);
1310 offset--;
1311 while (offset > 0) {
1312 PyFile_WriteString(" ", f);
1313 offset--;
1314 }
1315 PyFile_WriteString("^\n", f);
1316}
1317
Guido van Rossum66e8e862001-03-23 17:54:43 +00001318static void
1319handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001320{
Neal Norwitz9589ee22006-03-04 19:01:22 +00001321 PyObject *exception, *value, *tb;
1322 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001323
Guido van Rossumd8faa362007-04-27 19:54:29 +00001324 if (Py_InspectFlag)
1325 /* Don't exit if -i flag was given. This flag is set to 0
1326 * when entering interactive mode for inspecting. */
1327 return;
1328
Guido van Rossum66e8e862001-03-23 17:54:43 +00001329 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001330 fflush(stdout);
1331 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001332 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001333 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001334 /* The error code should be in the `code' attribute. */
1335 PyObject *code = PyObject_GetAttrString(value, "code");
1336 if (code) {
1337 Py_DECREF(value);
1338 value = code;
1339 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001340 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001341 }
1342 /* If we failed to dig out the 'code' attribute,
1343 just let the else clause below print the error. */
1344 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001345 if (PyLong_Check(value))
1346 exitcode = (int)PyLong_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001347 else {
1348 PyObject_Print(value, stderr, Py_PRINT_RAW);
1349 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001350 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001351 }
Tim Peterscf615b52003-04-19 18:47:02 +00001352 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001353 /* Restore and clear the exception info, in order to properly decref
1354 * the exception, value, and traceback. If we just exit instead,
1355 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1356 * some finalizers from running.
1357 */
Tim Peterscf615b52003-04-19 18:47:02 +00001358 PyErr_Restore(exception, value, tb);
1359 PyErr_Clear();
1360 Py_Exit(exitcode);
1361 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001362}
1363
1364void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001365PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001366{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001367 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001368
1369 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1370 handle_system_exit();
1371 }
Guido van Rossum82598051997-03-05 00:20:32 +00001372 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001373 if (exception == NULL)
1374 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001375 PyErr_NormalizeException(&exception, &v, &tb);
Antoine Pitroue2dffc02008-08-26 22:02:58 +00001376 if (tb == NULL) {
1377 tb = Py_None;
1378 Py_INCREF(tb);
1379 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001380 PyException_SetTraceback(v, tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001381 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001382 return;
Georg Brandl86b2fb92008-07-16 03:43:04 +00001383 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001384 if (set_sys_last_vars) {
1385 PySys_SetObject("last_type", exception);
1386 PySys_SetObject("last_value", v);
Benjamin Petersone6528212008-07-15 15:32:09 +00001387 PySys_SetObject("last_traceback", tb);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001388 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001389 hook = PySys_GetObject("excepthook");
1390 if (hook) {
Benjamin Petersone6528212008-07-15 15:32:09 +00001391 PyObject *args = PyTuple_Pack(3, exception, v, tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001392 PyObject *result = PyEval_CallObject(hook, args);
1393 if (result == NULL) {
1394 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001395 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1396 handle_system_exit();
1397 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001398 PyErr_Fetch(&exception2, &v2, &tb2);
1399 PyErr_NormalizeException(&exception2, &v2, &tb2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001400 /* It should not be possible for exception2 or v2
1401 to be NULL. However PyErr_Display() can't
1402 tolerate NULLs, so just be safe. */
1403 if (exception2 == NULL) {
1404 exception2 = Py_None;
1405 Py_INCREF(exception2);
1406 }
1407 if (v2 == NULL) {
1408 v2 = Py_None;
1409 Py_INCREF(v2);
1410 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001411 fflush(stdout);
1412 PySys_WriteStderr("Error in sys.excepthook:\n");
1413 PyErr_Display(exception2, v2, tb2);
1414 PySys_WriteStderr("\nOriginal exception was:\n");
1415 PyErr_Display(exception, v, tb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001416 Py_DECREF(exception2);
1417 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001418 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001419 }
1420 Py_XDECREF(result);
1421 Py_XDECREF(args);
1422 } else {
1423 PySys_WriteStderr("sys.excepthook is missing\n");
1424 PyErr_Display(exception, v, tb);
1425 }
1426 Py_XDECREF(exception);
1427 Py_XDECREF(v);
1428 Py_XDECREF(tb);
1429}
1430
Benjamin Petersone6528212008-07-15 15:32:09 +00001431static void
1432print_exception(PyObject *f, PyObject *value)
1433{
1434 int err = 0;
1435 PyObject *type, *tb;
1436
Benjamin Peterson26582602008-08-23 20:08:07 +00001437 if (!PyExceptionInstance_Check(value)) {
1438 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1439 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1440 PyFile_WriteString(" found\n", f);
1441 return;
1442 }
1443
Benjamin Petersone6528212008-07-15 15:32:09 +00001444 Py_INCREF(value);
1445 fflush(stdout);
1446 type = (PyObject *) Py_TYPE(value);
1447 tb = PyException_GetTraceback(value);
1448 if (tb && tb != Py_None)
1449 err = PyTraceBack_Print(tb, f);
1450 if (err == 0 &&
1451 PyObject_HasAttrString(value, "print_file_and_line"))
1452 {
1453 PyObject *message;
1454 const char *filename, *text;
1455 int lineno, offset;
1456 if (!parse_syntax_error(value, &message, &filename,
1457 &lineno, &offset, &text))
1458 PyErr_Clear();
1459 else {
1460 char buf[10];
1461 PyFile_WriteString(" File \"", f);
1462 if (filename == NULL)
1463 PyFile_WriteString("<string>", f);
1464 else
1465 PyFile_WriteString(filename, f);
1466 PyFile_WriteString("\", line ", f);
1467 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1468 PyFile_WriteString(buf, f);
1469 PyFile_WriteString("\n", f);
1470 if (text != NULL)
1471 print_error_text(f, offset, text);
1472 Py_DECREF(value);
1473 value = message;
1474 /* Can't be bothered to check all those
1475 PyFile_WriteString() calls */
1476 if (PyErr_Occurred())
1477 err = -1;
1478 }
1479 }
1480 if (err) {
1481 /* Don't do anything else */
1482 }
1483 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001484 PyObject* moduleName;
Thomas Hellerd88ddfa2008-07-15 17:14:51 +00001485 char* className;
1486 assert(PyExceptionClass_Check(type));
1487 className = PyExceptionClass_Name(type);
Benjamin Petersone6528212008-07-15 15:32:09 +00001488 if (className != NULL) {
1489 char *dot = strrchr(className, '.');
1490 if (dot != NULL)
1491 className = dot+1;
1492 }
1493
1494 moduleName = PyObject_GetAttrString(type, "__module__");
1495 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1496 {
1497 Py_DECREF(moduleName);
1498 err = PyFile_WriteString("<unknown>", f);
1499 }
1500 else {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001501 char* modstr = _PyUnicode_AsString(moduleName);
Benjamin Petersone6528212008-07-15 15:32:09 +00001502 if (modstr && strcmp(modstr, "builtins"))
1503 {
1504 err = PyFile_WriteString(modstr, f);
1505 err += PyFile_WriteString(".", f);
1506 }
1507 Py_DECREF(moduleName);
1508 }
1509 if (err == 0) {
1510 if (className == NULL)
1511 err = PyFile_WriteString("<unknown>", f);
1512 else
1513 err = PyFile_WriteString(className, f);
1514 }
1515 }
1516 if (err == 0 && (value != Py_None)) {
1517 PyObject *s = PyObject_Str(value);
1518 /* only print colon if the str() of the
1519 object is not the empty string
1520 */
1521 if (s == NULL)
1522 err = -1;
1523 else if (!PyUnicode_Check(s) ||
1524 PyUnicode_GetSize(s) != 0)
1525 err = PyFile_WriteString(": ", f);
1526 if (err == 0)
1527 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1528 Py_XDECREF(s);
1529 }
1530 /* try to write a newline in any case */
1531 err += PyFile_WriteString("\n", f);
1532 Py_XDECREF(tb);
1533 Py_DECREF(value);
1534 /* If an error happened here, don't show it.
1535 XXX This is wrong, but too many callers rely on this behavior. */
1536 if (err != 0)
1537 PyErr_Clear();
1538}
1539
1540static const char *cause_message =
1541 "\nThe above exception was the direct cause "
1542 "of the following exception:\n\n";
1543
1544static const char *context_message =
1545 "\nDuring handling of the above exception, "
1546 "another exception occurred:\n\n";
1547
1548static void
1549print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1550{
1551 int err = 0, res;
1552 PyObject *cause, *context;
1553
1554 if (seen != NULL) {
1555 /* Exception chaining */
1556 if (PySet_Add(seen, value) == -1)
1557 PyErr_Clear();
1558 else if (PyExceptionInstance_Check(value)) {
1559 cause = PyException_GetCause(value);
1560 context = PyException_GetContext(value);
1561 if (cause) {
1562 res = PySet_Contains(seen, cause);
1563 if (res == -1)
1564 PyErr_Clear();
1565 if (res == 0) {
1566 print_exception_recursive(
1567 f, cause, seen);
1568 err |= PyFile_WriteString(
1569 cause_message, f);
1570 }
1571 }
1572 if (context) {
1573 res = PySet_Contains(seen, context);
1574 if (res == -1)
1575 PyErr_Clear();
1576 if (res == 0) {
1577 print_exception_recursive(
1578 f, context, seen);
1579 err |= PyFile_WriteString(
1580 context_message, f);
1581 }
1582 }
1583 Py_XDECREF(context);
1584 Py_XDECREF(cause);
1585 }
1586 }
1587 print_exception(f, value);
1588 if (err != 0)
1589 PyErr_Clear();
1590}
1591
Thomas Wouters477c8d52006-05-27 19:21:47 +00001592void
1593PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001594{
Benjamin Petersone6528212008-07-15 15:32:09 +00001595 PyObject *seen;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001596 PyObject *f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +00001597 if (f == Py_None) {
1598 /* pass */
1599 }
1600 else if (f == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001601 _PyObject_Dump(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001602 fprintf(stderr, "lost sys.stderr\n");
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001603 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001604 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001605 /* We choose to ignore seen being possibly NULL, and report
1606 at least the main exception (it could be a MemoryError).
1607 */
1608 seen = PySet_New(NULL);
1609 if (seen == NULL)
1610 PyErr_Clear();
1611 print_exception_recursive(f, value, seen);
1612 Py_XDECREF(seen);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001613 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001614}
1615
Guido van Rossum82598051997-03-05 00:20:32 +00001616PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001617PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001618 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001619{
Neal Norwitze92fba02006-03-04 18:52:26 +00001620 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001621 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001622 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001623 if (arena == NULL)
1624 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001625
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001626 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001627 if (mod != NULL)
1628 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001629 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001630 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001631}
1632
1633PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001634PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001635 PyObject *locals, int closeit, PyCompilerFlags *flags)
1636{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001637 PyObject *ret;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001638 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001639 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001640 if (arena == NULL)
1641 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001642
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001643 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001644 flags, NULL, arena);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001645 if (closeit)
1646 fclose(fp);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001647 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001648 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001649 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001650 }
Neal Norwitze92fba02006-03-04 18:52:26 +00001651 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001652 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001653 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001654}
1655
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001656static void
1657flush_io(void)
1658{
1659 PyObject *f, *r;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001660 PyObject *type, *value, *traceback;
1661
1662 /* Save the current exception */
1663 PyErr_Fetch(&type, &value, &traceback);
1664
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001665 f = PySys_GetObject("stderr");
1666 if (f != NULL) {
1667 r = PyObject_CallMethod(f, "flush", "");
1668 if (r)
1669 Py_DECREF(r);
1670 else
1671 PyErr_Clear();
1672 }
1673 f = PySys_GetObject("stdout");
1674 if (f != NULL) {
1675 r = PyObject_CallMethod(f, "flush", "");
1676 if (r)
1677 Py_DECREF(r);
1678 else
1679 PyErr_Clear();
1680 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001681
1682 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001683}
1684
Guido van Rossum82598051997-03-05 00:20:32 +00001685static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001686run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001687 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001688{
Guido van Rossum82598051997-03-05 00:20:32 +00001689 PyCodeObject *co;
1690 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001691 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001692 if (co == NULL)
1693 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001694 v = PyEval_EvalCode(co, globals, locals);
1695 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001696 return v;
1697}
1698
Guido van Rossum82598051997-03-05 00:20:32 +00001699static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001700run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001701 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001702{
Guido van Rossum82598051997-03-05 00:20:32 +00001703 PyCodeObject *co;
1704 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001705 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001706 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001707
Guido van Rossum82598051997-03-05 00:20:32 +00001708 magic = PyMarshal_ReadLongFromFile(fp);
1709 if (magic != PyImport_GetMagicNumber()) {
1710 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001711 "Bad magic number in .pyc file");
1712 return NULL;
1713 }
Guido van Rossum82598051997-03-05 00:20:32 +00001714 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001715 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001716 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001717 if (v == NULL || !PyCode_Check(v)) {
1718 Py_XDECREF(v);
1719 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001720 "Bad code object in .pyc file");
1721 return NULL;
1722 }
Guido van Rossum82598051997-03-05 00:20:32 +00001723 co = (PyCodeObject *)v;
1724 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001725 if (v && flags)
1726 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001727 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001728 return v;
1729}
1730
Guido van Rossum82598051997-03-05 00:20:32 +00001731PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001732Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001733 PyCompilerFlags *flags)
1734{
Guido van Rossum82598051997-03-05 00:20:32 +00001735 PyCodeObject *co;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001736 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001737 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001738 if (arena == NULL)
1739 return NULL;
1740
1741 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001742 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001743 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001744 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001745 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001746 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001747 PyObject *result = PyAST_mod2obj(mod);
1748 PyArena_Free(arena);
1749 return result;
1750 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001751 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001752 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001753 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001754}
1755
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001756struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001757Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001758{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001759 struct symtable *st;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001760 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001761 PyCompilerFlags flags;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001762 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001763 if (arena == NULL)
1764 return NULL;
1765
Christian Heimesb1b3efc2008-03-26 23:24:27 +00001766 flags.cf_flags = 0;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001767 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001768 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001769 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001770 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001771 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001772 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001773 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001774 return st;
1775}
1776
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001777/* Preferred access to parser is through AST. */
1778mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001779PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001780 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001781{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001782 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001783 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001784 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001785 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001786
1787 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001788 &_PyParser_Grammar, start, &err,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001789 &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001790 if (flags == NULL) {
1791 localflags.cf_flags = 0;
1792 flags = &localflags;
1793 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001794 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001795 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001796 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001797 PyNode_Free(n);
1798 return mod;
1799 }
1800 else {
1801 err_input(&err);
1802 return NULL;
1803 }
1804}
1805
1806mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001807PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1808 int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001809 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001810 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001812 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001813 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001814 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001815 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001816
Christian Heimes4d6ec852008-03-26 22:34:47 +00001817 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001818 &_PyParser_Grammar,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001819 start, ps1, ps2, &err, &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001820 if (flags == NULL) {
1821 localflags.cf_flags = 0;
1822 flags = &localflags;
1823 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001824 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001825 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001826 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001827 PyNode_Free(n);
1828 return mod;
1829 }
1830 else {
1831 err_input(&err);
1832 if (errcode)
1833 *errcode = err.error;
1834 return NULL;
1835 }
1836}
1837
Guido van Rossuma110aa61994-08-29 12:50:44 +00001838/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001839
Guido van Rossuma110aa61994-08-29 12:50:44 +00001840node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001841PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001842{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001843 perrdetail err;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001844 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1845 &_PyParser_Grammar,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001846 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001847 if (n == NULL)
1848 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001849
Guido van Rossuma110aa61994-08-29 12:50:44 +00001850 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001851}
1852
Guido van Rossuma110aa61994-08-29 12:50:44 +00001853/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001854
Guido van Rossuma110aa61994-08-29 12:50:44 +00001855node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001856PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001857{
Tim Petersfe2127d2001-07-16 05:37:24 +00001858 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001859 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1860 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001861 if (n == NULL)
1862 err_input(&err);
1863 return n;
1864}
1865
1866node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001867PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001868 int start, int flags)
1869{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001870 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001871 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1872 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001873 if (n == NULL)
1874 err_input(&err);
1875 return n;
1876}
1877
1878node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001879PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001880{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001881 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001882}
1883
Guido van Rossum66ebd912003-04-17 16:02:26 +00001884/* May want to move a more generalized form of this to parsetok.c or
1885 even parser modules. */
1886
1887void
1888PyParser_SetError(perrdetail *err)
1889{
1890 err_input(err);
1891}
1892
Guido van Rossuma110aa61994-08-29 12:50:44 +00001893/* Set the error appropriate to the given input error code (see errcode.h) */
1894
1895static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001896err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001897{
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001898 PyObject *v, *w, *errtype, *errtext;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001899 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001900 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001901 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001902 switch (err->error) {
1903 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001904 errtype = PyExc_IndentationError;
1905 if (err->expected == INDENT)
1906 msg = "expected an indented block";
1907 else if (err->token == INDENT)
1908 msg = "unexpected indent";
1909 else if (err->token == DEDENT)
1910 msg = "unexpected unindent";
1911 else {
1912 errtype = PyExc_SyntaxError;
1913 msg = "invalid syntax";
1914 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001915 break;
1916 case E_TOKEN:
1917 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001918 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001919 case E_EOFS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001920 msg = "EOF while scanning triple-quoted string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001921 break;
1922 case E_EOLS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001923 msg = "EOL while scanning string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001924 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001925 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001926 if (!PyErr_Occurred())
1927 PyErr_SetNone(PyExc_KeyboardInterrupt);
Georg Brandl3dbca812008-07-23 16:10:53 +00001928 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001929 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001930 PyErr_NoMemory();
Georg Brandl3dbca812008-07-23 16:10:53 +00001931 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001932 case E_EOF:
1933 msg = "unexpected EOF while parsing";
1934 break;
Fred Drake85f36392000-07-11 17:53:00 +00001935 case E_TABSPACE:
1936 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001937 msg = "inconsistent use of tabs and spaces in indentation";
1938 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001939 case E_OVERFLOW:
1940 msg = "expression too long";
1941 break;
Fred Drake85f36392000-07-11 17:53:00 +00001942 case E_DEDENT:
1943 errtype = PyExc_IndentationError;
1944 msg = "unindent does not match any outer indentation level";
1945 break;
1946 case E_TOODEEP:
1947 errtype = PyExc_IndentationError;
1948 msg = "too many levels of indentation";
1949 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001950 case E_DECODE: {
1951 PyObject *type, *value, *tb;
1952 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001953 if (value != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001954 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001955 if (u != NULL) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001956 msg = _PyUnicode_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001957 }
1958 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001959 if (msg == NULL)
1960 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001961 Py_XDECREF(type);
1962 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001963 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001964 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001965 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001966 case E_LINECONT:
1967 msg = "unexpected character after line continuation character";
1968 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001969
1970 case E_IDENTIFIER:
1971 msg = "invalid character in identifier";
1972 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001973 default:
1974 fprintf(stderr, "error=%d\n", err->error);
1975 msg = "unknown parsing error";
1976 break;
1977 }
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001978 /* err->text may not be UTF-8 in case of decoding errors.
1979 Explicitly convert to an object. */
1980 if (!err->text) {
1981 errtext = Py_None;
1982 Py_INCREF(Py_None);
1983 } else {
1984 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1985 "replace");
1986 }
1987 v = Py_BuildValue("(ziiN)", err->filename,
1988 err->lineno, err->offset, errtext);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001989 w = NULL;
1990 if (v != NULL)
1991 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001992 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001993 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001994 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001995 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00001996cleanup:
1997 if (err->text != NULL) {
1998 PyObject_FREE(err->text);
1999 err->text = NULL;
2000 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002001}
2002
2003/* Print fatal error message and abort */
2004
2005void
Tim Peters7c321a82002-07-09 02:57:01 +00002006Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002007{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00002008 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00002009 if (PyErr_Occurred()) {
2010 PyErr_Print();
2011 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002012#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002013 {
2014 size_t len = strlen(msg);
2015 WCHAR* buffer;
2016 size_t i;
2017
2018 /* Convert the message to wchar_t. This uses a simple one-to-one
2019 conversion, assuming that the this error message actually uses ASCII
2020 only. If this ceases to be true, we will have to convert. */
2021 buffer = alloca( (len+1) * (sizeof *buffer));
2022 for( i=0; i<=len; ++i)
2023 buffer[i] = msg[i];
2024 OutputDebugStringW(L"Fatal Python error: ");
2025 OutputDebugStringW(buffer);
2026 OutputDebugStringW(L"\n");
2027 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002028#ifdef _DEBUG
2029 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002030#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002031#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002032 abort();
2033}
2034
2035/* Clean up and exit */
2036
Guido van Rossuma110aa61994-08-29 12:50:44 +00002037#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002038#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002039#endif
2040
Collin Winter670e6922007-03-21 02:57:17 +00002041static void (*pyexitfunc)(void) = NULL;
2042/* For the atexit module. */
2043void _Py_PyAtExit(void (*func)(void))
2044{
2045 pyexitfunc = func;
2046}
2047
2048static void
2049call_py_exitfuncs(void)
2050{
Guido van Rossum98297ee2007-11-06 21:34:58 +00002051 if (pyexitfunc == NULL)
Collin Winter670e6922007-03-21 02:57:17 +00002052 return;
2053
2054 (*pyexitfunc)();
2055 PyErr_Clear();
2056}
2057
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002058#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002059static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002060static int nexitfuncs = 0;
2061
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002062int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002063{
2064 if (nexitfuncs >= NEXITFUNCS)
2065 return -1;
2066 exitfuncs[nexitfuncs++] = func;
2067 return 0;
2068}
2069
Guido van Rossumcc283f51997-08-05 02:22:03 +00002070static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002071call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002072{
Guido van Rossum1662dd51994-09-07 14:38:28 +00002073 while (nexitfuncs > 0)
2074 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002075
2076 fflush(stdout);
2077 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002078}
2079
2080void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002081Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002082{
Guido van Rossumcc283f51997-08-05 02:22:03 +00002083 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002084
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002085 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002086}
2087
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002088static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002089initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002090{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002091#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002092 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002093#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002094#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002095 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002096#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002097#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002098 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002099#endif
Guido van Rossum82598051997-03-05 00:20:32 +00002100 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002101}
2102
Guido van Rossum7433b121997-02-14 19:45:36 +00002103
2104/*
2105 * The file descriptor fd is considered ``interactive'' if either
2106 * a) isatty(fd) is TRUE, or
2107 * b) the -i flag was given, and the filename associated with
2108 * the descriptor is NULL or "<stdin>" or "???".
2109 */
2110int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002111Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002112{
2113 if (isatty((int)fileno(fp)))
2114 return 1;
2115 if (!Py_InteractiveFlag)
2116 return 0;
2117 return (filename == NULL) ||
2118 (strcmp(filename, "<stdin>") == 0) ||
2119 (strcmp(filename, "???") == 0);
2120}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002121
2122
Tim Petersd08e3822003-04-17 15:24:21 +00002123#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002124#if defined(WIN32) && defined(_MSC_VER)
2125
2126/* Stack checking for Microsoft C */
2127
2128#include <malloc.h>
2129#include <excpt.h>
2130
Fred Drakee8de31c2000-08-31 05:38:39 +00002131/*
2132 * Return non-zero when we run out of memory on the stack; zero otherwise.
2133 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002134int
Fred Drake399739f2000-08-31 05:52:44 +00002135PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002136{
2137 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00002138 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002139 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00002140 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002141 return 0;
Christian Heimes7131fd92008-02-19 14:21:46 +00002142 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
Trent Nelson39e307e2008-03-19 06:45:48 +00002143 EXCEPTION_EXECUTE_HANDLER :
2144 EXCEPTION_CONTINUE_SEARCH) {
Christian Heimes7131fd92008-02-19 14:21:46 +00002145 int errcode = _resetstkoflw();
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +00002146 if (errcode == 0)
Christian Heimes7131fd92008-02-19 14:21:46 +00002147 {
2148 Py_FatalError("Could not reset the stack!");
2149 }
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002150 }
2151 return 1;
2152}
2153
2154#endif /* WIN32 && _MSC_VER */
2155
2156/* Alternate implementations can be added here... */
2157
2158#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002159
2160
2161/* Wrappers around sigaction() or signal(). */
2162
2163PyOS_sighandler_t
2164PyOS_getsig(int sig)
2165{
2166#ifdef HAVE_SIGACTION
2167 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002168 if (sigaction(sig, NULL, &context) == -1)
2169 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00002170 return context.sa_handler;
2171#else
2172 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002173/* Special signal handling for the secure CRT in Visual Studio 2005 */
2174#if defined(_MSC_VER) && _MSC_VER >= 1400
2175 switch (sig) {
2176 /* Only these signals are valid */
2177 case SIGINT:
2178 case SIGILL:
2179 case SIGFPE:
2180 case SIGSEGV:
2181 case SIGTERM:
2182 case SIGBREAK:
2183 case SIGABRT:
2184 break;
2185 /* Don't call signal() with other values or it will assert */
2186 default:
2187 return SIG_ERR;
2188 }
2189#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002190 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002191 if (handler != SIG_ERR)
2192 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00002193 return handler;
2194#endif
2195}
2196
2197PyOS_sighandler_t
2198PyOS_setsig(int sig, PyOS_sighandler_t handler)
2199{
2200#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002201 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00002202 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002203 sigemptyset(&context.sa_mask);
2204 context.sa_flags = 0;
2205 if (sigaction(sig, &context, &ocontext) == -1)
2206 return SIG_ERR;
2207 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002208#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002209 PyOS_sighandler_t oldhandler;
2210 oldhandler = signal(sig, handler);
2211#ifdef HAVE_SIGINTERRUPT
2212 siginterrupt(sig, 1);
2213#endif
2214 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002215#endif
2216}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002217
2218/* Deprecated C API functions still provided for binary compatiblity */
2219
2220#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002221PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002222PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2223{
2224 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2225}
2226
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002227#undef PyParser_SimpleParseString
2228PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002229PyParser_SimpleParseString(const char *str, int start)
2230{
2231 return PyParser_SimpleParseStringFlags(str, start, 0);
2232}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002233
2234#undef PyRun_AnyFile
2235PyAPI_FUNC(int)
2236PyRun_AnyFile(FILE *fp, const char *name)
2237{
2238 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
2239}
2240
2241#undef PyRun_AnyFileEx
2242PyAPI_FUNC(int)
2243PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2244{
2245 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
2246}
2247
2248#undef PyRun_AnyFileFlags
2249PyAPI_FUNC(int)
2250PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2251{
2252 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2253}
2254
2255#undef PyRun_File
2256PyAPI_FUNC(PyObject *)
2257PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2258{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002259 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002260}
2261
2262#undef PyRun_FileEx
2263PyAPI_FUNC(PyObject *)
2264PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2265{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002266 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002267}
2268
2269#undef PyRun_FileFlags
2270PyAPI_FUNC(PyObject *)
2271PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2272 PyCompilerFlags *flags)
2273{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002274 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002275}
2276
2277#undef PyRun_SimpleFile
2278PyAPI_FUNC(int)
2279PyRun_SimpleFile(FILE *f, const char *p)
2280{
2281 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
2282}
2283
2284#undef PyRun_SimpleFileEx
2285PyAPI_FUNC(int)
2286PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2287{
2288 return PyRun_SimpleFileExFlags(f, p, c, NULL);
2289}
2290
2291
2292#undef PyRun_String
2293PyAPI_FUNC(PyObject *)
2294PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2295{
2296 return PyRun_StringFlags(str, s, g, l, NULL);
2297}
2298
2299#undef PyRun_SimpleString
2300PyAPI_FUNC(int)
2301PyRun_SimpleString(const char *s)
2302{
2303 return PyRun_SimpleStringFlags(s, NULL);
2304}
2305
2306#undef Py_CompileString
2307PyAPI_FUNC(PyObject *)
2308Py_CompileString(const char *str, const char *p, int s)
2309{
2310 return Py_CompileStringFlags(str, p, s, NULL);
2311}
2312
2313#undef PyRun_InteractiveOne
2314PyAPI_FUNC(int)
2315PyRun_InteractiveOne(FILE *f, const char *p)
2316{
2317 return PyRun_InteractiveOneFlags(f, p, NULL);
2318}
2319
2320#undef PyRun_InteractiveLoop
2321PyAPI_FUNC(int)
2322PyRun_InteractiveLoop(FILE *f, const char *p)
2323{
2324 return PyRun_InteractiveLoopFlags(f, p, NULL);
2325}
2326
2327#ifdef __cplusplus
2328}
2329#endif