blob: 6819be55477949c254a22844de0c8278ab2a30f2 [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
742 if (Py_UnbufferedStdioFlag)
743 buffering = 0;
744 else
745 buffering = -1;
746 if (write_mode)
747 mode = "wb";
748 else
749 mode = "rb";
750 buf = PyObject_CallMethod(io, "open", "isiOOOi",
751 fd, mode, buffering,
752 Py_None, Py_None, Py_None, 0);
753 if (buf == NULL)
754 goto error;
755
756 if (!Py_UnbufferedStdioFlag) {
757 raw = PyObject_GetAttrString(buf, "raw");
758 if (raw == NULL)
759 goto error;
760 }
761 else {
762 raw = buf;
763 Py_INCREF(raw);
764 }
765
766 text = PyUnicode_FromString(name);
767 if (text == NULL || PyObject_SetAttrString(raw, "_name", text) < 0)
768 goto error;
Antoine Pitrou91696412009-01-09 22:12:30 +0000769 res = PyObject_CallMethod(raw, "isatty", "");
770 if (res == NULL)
771 goto error;
772 isatty = PyObject_IsTrue(res);
773 Py_DECREF(res);
774 if (isatty == -1)
775 goto error;
776 if (isatty || Py_UnbufferedStdioFlag)
Antoine Pitrou05608432009-01-09 18:53:14 +0000777 line_buffering = Py_True;
778 else
779 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000780
781 Py_CLEAR(raw);
782 Py_CLEAR(text);
783
Antoine Pitrou05608432009-01-09 18:53:14 +0000784 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
785 buf, encoding, errors,
786 "\n", line_buffering);
787 Py_CLEAR(buf);
788 if (stream == NULL)
789 goto error;
790
791 if (write_mode)
792 mode = "w";
793 else
794 mode = "r";
795 text = PyUnicode_FromString(mode);
796 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
797 goto error;
798 Py_CLEAR(text);
799 return stream;
800
801error:
802 Py_XDECREF(buf);
803 Py_XDECREF(stream);
804 Py_XDECREF(text);
805 Py_XDECREF(raw);
806 return NULL;
807}
808
Georg Brandl1a3284e2007-12-02 09:40:06 +0000809/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000810static int
811initstdio(void)
812{
813 PyObject *iomod = NULL, *wrapper;
814 PyObject *bimod = NULL;
815 PyObject *m;
816 PyObject *std = NULL;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000817 int status = 0, fd;
Trent Nelson39e307e2008-03-19 06:45:48 +0000818 PyObject * encoding_attr;
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +0000819 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000820
821 /* Hack to avoid a nasty recursion issue when Python is invoked
822 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
823 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
824 goto error;
825 }
826 Py_DECREF(m);
827
828 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
829 goto error;
830 }
831 Py_DECREF(m);
832
Georg Brandl1a3284e2007-12-02 09:40:06 +0000833 if (!(bimod = PyImport_ImportModule("builtins"))) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000834 goto error;
835 }
836
837 if (!(iomod = PyImport_ImportModule("io"))) {
838 goto error;
839 }
840 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
841 goto error;
842 }
843
Georg Brandl1a3284e2007-12-02 09:40:06 +0000844 /* Set builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000845 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
846 goto error;
847 }
848
Martin v. Löwis0f599892008-06-02 11:13:03 +0000849 encoding = Py_GETENV("PYTHONIOENCODING");
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000850 errors = NULL;
Martin v. Löwis0f599892008-06-02 11:13:03 +0000851 if (encoding) {
852 encoding = strdup(encoding);
853 errors = strchr(encoding, ':');
854 if (errors) {
855 *errors = '\0';
856 errors++;
857 }
858 }
859
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000860 /* Set sys.stdin */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000861 fd = fileno(stdin);
862 /* Under some conditions stdin, stdout and stderr may not be connected
863 * and fileno() may point to an invalid file descriptor. For example
864 * GUI apps don't have valid standard streams by default.
865 */
866 if (fd < 0) {
867#ifdef MS_WINDOWS
868 std = Py_None;
869 Py_INCREF(std);
870#else
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000871 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000872#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000873 }
Christian Heimes58cb1b82007-11-13 02:19:40 +0000874 else {
Antoine Pitrou05608432009-01-09 18:53:14 +0000875 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
876 if (std == NULL)
Christian Heimes58cb1b82007-11-13 02:19:40 +0000877 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000878 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000879 PySys_SetObject("__stdin__", std);
880 PySys_SetObject("stdin", std);
881 Py_DECREF(std);
882
883 /* Set sys.stdout */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000884 fd = fileno(stdout);
885 if (fd < 0) {
886#ifdef MS_WINDOWS
887 std = Py_None;
888 Py_INCREF(std);
889#else
890 goto error;
891#endif
892 }
893 else {
Antoine Pitrou05608432009-01-09 18:53:14 +0000894 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
895 if (std == NULL)
Christian Heimes58cb1b82007-11-13 02:19:40 +0000896 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000897 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000898 PySys_SetObject("__stdout__", std);
899 PySys_SetObject("stdout", std);
900 Py_DECREF(std);
901
Guido van Rossum98297ee2007-11-06 21:34:58 +0000902#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000903 /* Set sys.stderr, replaces the preliminary stderr */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000904 fd = fileno(stderr);
905 if (fd < 0) {
906#ifdef MS_WINDOWS
907 std = Py_None;
908 Py_INCREF(std);
909#else
910 goto error;
911#endif
912 }
913 else {
Antoine Pitrou05608432009-01-09 18:53:14 +0000914 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
915 if (std == NULL)
Christian Heimes58cb1b82007-11-13 02:19:40 +0000916 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000917 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000918
919 /* Same as hack above, pre-import stderr's codec to avoid recursion
920 when import.c tries to write to stderr in verbose mode. */
921 encoding_attr = PyObject_GetAttrString(std, "encoding");
922 if (encoding_attr != NULL) {
923 const char * encoding;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000924 encoding = _PyUnicode_AsString(encoding_attr);
Trent Nelson39e307e2008-03-19 06:45:48 +0000925 if (encoding != NULL) {
926 _PyCodec_Lookup(encoding);
927 }
928 }
929 PyErr_Clear(); /* Not a fatal error if codec isn't available */
930
Christian Heimesdb233082007-11-13 02:34:21 +0000931 PySys_SetObject("__stderr__", std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000932 PySys_SetObject("stderr", std);
933 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000934#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000935
Christian Heimes58cb1b82007-11-13 02:19:40 +0000936 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000937 error:
Christian Heimesdb233082007-11-13 02:34:21 +0000938 status = -1;
939 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000940
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000941 if (encoding)
942 free(encoding);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000943 Py_XDECREF(bimod);
944 Py_XDECREF(iomod);
945 return status;
946}
947
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000948/* Parse input from a file and execute it */
949
950int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000951PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000952 PyCompilerFlags *flags)
953{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000954 if (filename == NULL)
955 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000956 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000957 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000958 if (closeit)
959 fclose(fp);
960 return err;
961 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000962 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000963 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000964}
965
966int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000967PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000968{
Guido van Rossum82598051997-03-05 00:20:32 +0000969 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000970 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000971 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000972
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000973 if (flags == NULL) {
974 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000975 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000976 }
Guido van Rossum82598051997-03-05 00:20:32 +0000977 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000978 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000979 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
Guido van Rossum82598051997-03-05 00:20:32 +0000980 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000981 }
Guido van Rossum82598051997-03-05 00:20:32 +0000982 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000983 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000984 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
Guido van Rossum82598051997-03-05 00:20:32 +0000985 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000986 }
987 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000988 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000989 PRINT_TOTAL_REFS();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000990 if (ret == E_EOF)
991 return 0;
992 /*
993 if (ret == E_NOMEM)
994 return -1;
995 */
996 }
997}
998
Neil Schemenauerc24ea082002-03-22 23:53:36 +0000999/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001000#define PARSER_FLAGS(flags) \
Thomas Wouters34aa7ba2006-02-28 19:02:24 +00001001 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
Guido van Rossum45aecf42006-03-15 04:58:47 +00001002 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001003
Thomas Wouters89f507f2006-12-13 04:49:30 +00001004#if 0
1005/* Keep an example of flags with future keyword support. */
1006#define PARSER_FLAGS(flags) \
1007 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1008 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1009 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1010 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
1011#endif
1012
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001013int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001014PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001015{
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001016 PyObject *m, *d, *v, *w, *oenc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001017 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001018 PyArena *arena;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001019 char *ps1 = "", *ps2 = "", *enc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001020 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001021
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001022 if (fp == stdin) {
1023 /* Fetch encoding from sys.stdin */
1024 v = PySys_GetObject("stdin");
Christian Heimes2be03732007-11-15 02:26:46 +00001025 if (v == NULL || v == Py_None)
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001026 return -1;
1027 oenc = PyObject_GetAttrString(v, "encoding");
1028 if (!oenc)
1029 return -1;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001030 enc = _PyUnicode_AsString(oenc);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001031 }
Guido van Rossum82598051997-03-05 00:20:32 +00001032 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001033 if (v != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001034 v = PyObject_Str(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001035 if (v == NULL)
1036 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +00001037 else if (PyUnicode_Check(v))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001038 ps1 = _PyUnicode_AsString(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001039 }
Guido van Rossum82598051997-03-05 00:20:32 +00001040 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001041 if (w != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001042 w = PyObject_Str(w);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001043 if (w == NULL)
1044 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +00001045 else if (PyUnicode_Check(w))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001046 ps2 = _PyUnicode_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001047 }
Neal Norwitz9589ee22006-03-04 19:01:22 +00001048 arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001049 if (arena == NULL) {
1050 Py_XDECREF(v);
1051 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001052 Py_XDECREF(oenc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001053 return -1;
1054 }
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001055 mod = PyParser_ASTFromFile(fp, filename, enc,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001056 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001057 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001058 Py_XDECREF(v);
1059 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001060 Py_XDECREF(oenc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001061 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001062 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001063 if (errcode == E_EOF) {
1064 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001065 return E_EOF;
1066 }
Guido van Rossum82598051997-03-05 00:20:32 +00001067 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001068 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001069 }
Guido van Rossum82598051997-03-05 00:20:32 +00001070 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001071 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001072 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001073 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001074 }
Guido van Rossum82598051997-03-05 00:20:32 +00001075 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001076 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001077 PyArena_Free(arena);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001078 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001079 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001080 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001081 return -1;
1082 }
Guido van Rossum82598051997-03-05 00:20:32 +00001083 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001084 return 0;
1085}
1086
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001087/* Check whether a file maybe a pyc file: Look at the extension,
1088 the file type, and, if we may close it, at the first few bytes. */
1089
1090static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001091maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001092{
1093 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1094 return 1;
1095
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001096 /* Only look into the file if we are allowed to close it, since
1097 it then should also be seekable. */
1098 if (closeit) {
1099 /* Read only two bytes of the magic. If the file was opened in
1100 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1101 be read as they are on disk. */
1102 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1103 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +00001104 /* Mess: In case of -x, the stream is NOT at its start now,
1105 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001106 which makes the current stream position formally undefined,
1107 and a x-platform nightmare.
1108 Unfortunately, we have no direct way to know whether -x
1109 was specified. So we use a terrible hack: if the current
1110 stream position is not 0, we assume -x was specified, and
1111 give up. Bug 132850 on SourceForge spells out the
1112 hopelessness of trying anything else (fseek and ftell
1113 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +00001114 */
Tim Peters3e876562001-02-11 04:35:39 +00001115 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001116 if (ftell(fp) == 0) {
1117 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +00001118 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001119 ispyc = 1;
1120 rewind(fp);
1121 }
Tim Peters3e876562001-02-11 04:35:39 +00001122 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001123 }
1124 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001125}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001126
Guido van Rossum0df002c2000-08-27 19:21:52 +00001127int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001128PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001129 PyCompilerFlags *flags)
1130{
Guido van Rossum82598051997-03-05 00:20:32 +00001131 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001132 const char *ext;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001133 int set_file_name = 0, ret;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001134
Guido van Rossum82598051997-03-05 00:20:32 +00001135 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001136 if (m == NULL)
1137 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001138 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +00001139 if (PyDict_GetItemString(d, "__file__") == NULL) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001140 PyObject *f;
1141 f = PyUnicode_DecodeFSDefault(filename);
Fred Drake8ed02042002-10-17 21:24:58 +00001142 if (f == NULL)
1143 return -1;
1144 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1145 Py_DECREF(f);
1146 return -1;
1147 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001148 set_file_name = 1;
Fred Drake8ed02042002-10-17 21:24:58 +00001149 Py_DECREF(f);
1150 }
Guido van Rossumfdef2711994-09-14 13:31:04 +00001151 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001152 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001153 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +00001154 if (closeit)
1155 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +00001156 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001157 fprintf(stderr, "python: Can't reopen .pyc file\n");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001158 ret = -1;
1159 goto done;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001160 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +00001161 /* Turn on optimization if a .pyo file is given */
1162 if (strcmp(ext, ".pyo") == 0)
1163 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001164 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001165 } else {
Tim Petersd08e3822003-04-17 15:24:21 +00001166 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001167 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001168 }
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001169 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001170 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001171 PyErr_Print();
Guido van Rossumd8faa362007-04-27 19:54:29 +00001172 ret = -1;
1173 goto done;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001174 }
Guido van Rossum82598051997-03-05 00:20:32 +00001175 Py_DECREF(v);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001176 ret = 0;
1177 done:
1178 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1179 PyErr_Clear();
1180 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001181}
1182
1183int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001184PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001185{
Guido van Rossum82598051997-03-05 00:20:32 +00001186 PyObject *m, *d, *v;
1187 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001188 if (m == NULL)
1189 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001190 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +00001191 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001192 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001193 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001194 return -1;
1195 }
Guido van Rossum82598051997-03-05 00:20:32 +00001196 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001197 return 0;
1198}
1199
Barry Warsaw035574d1997-08-29 22:07:17 +00001200static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001201parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1202 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001203{
1204 long hold;
1205 PyObject *v;
1206
1207 /* old style errors */
1208 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +00001209 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001210 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001211
1212 /* new style errors. `err' is an instance */
1213
1214 if (! (v = PyObject_GetAttrString(err, "msg")))
1215 goto finally;
1216 *message = v;
1217
1218 if (!(v = PyObject_GetAttrString(err, "filename")))
1219 goto finally;
1220 if (v == Py_None)
1221 *filename = NULL;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001222 else if (! (*filename = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001223 goto finally;
1224
1225 Py_DECREF(v);
1226 if (!(v = PyObject_GetAttrString(err, "lineno")))
1227 goto finally;
Christian Heimes217cfd12007-12-02 14:31:20 +00001228 hold = PyLong_AsLong(v);
Barry Warsaw035574d1997-08-29 22:07:17 +00001229 Py_DECREF(v);
1230 v = NULL;
1231 if (hold < 0 && PyErr_Occurred())
1232 goto finally;
1233 *lineno = (int)hold;
1234
1235 if (!(v = PyObject_GetAttrString(err, "offset")))
1236 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001237 if (v == Py_None) {
1238 *offset = -1;
1239 Py_DECREF(v);
1240 v = NULL;
1241 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001242 hold = PyLong_AsLong(v);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001243 Py_DECREF(v);
1244 v = NULL;
1245 if (hold < 0 && PyErr_Occurred())
1246 goto finally;
1247 *offset = (int)hold;
1248 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001249
1250 if (!(v = PyObject_GetAttrString(err, "text")))
1251 goto finally;
1252 if (v == Py_None)
1253 *text = NULL;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001254 else if (!PyUnicode_Check(v) ||
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001255 !(*text = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001256 goto finally;
1257 Py_DECREF(v);
1258 return 1;
1259
1260finally:
1261 Py_XDECREF(v);
1262 return 0;
1263}
1264
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001265void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001266PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001267{
Guido van Rossuma61691e1998-02-06 22:27:24 +00001268 PyErr_PrintEx(1);
1269}
1270
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001271static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001272print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001273{
1274 char *nl;
1275 if (offset >= 0) {
1276 if (offset > 0 && offset == (int)strlen(text))
1277 offset--;
1278 for (;;) {
1279 nl = strchr(text, '\n');
1280 if (nl == NULL || nl-text >= offset)
1281 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001282 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001283 text = nl+1;
1284 }
1285 while (*text == ' ' || *text == '\t') {
1286 text++;
1287 offset--;
1288 }
1289 }
1290 PyFile_WriteString(" ", f);
1291 PyFile_WriteString(text, f);
1292 if (*text == '\0' || text[strlen(text)-1] != '\n')
1293 PyFile_WriteString("\n", f);
1294 if (offset == -1)
1295 return;
1296 PyFile_WriteString(" ", f);
1297 offset--;
1298 while (offset > 0) {
1299 PyFile_WriteString(" ", f);
1300 offset--;
1301 }
1302 PyFile_WriteString("^\n", f);
1303}
1304
Guido van Rossum66e8e862001-03-23 17:54:43 +00001305static void
1306handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001307{
Neal Norwitz9589ee22006-03-04 19:01:22 +00001308 PyObject *exception, *value, *tb;
1309 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001310
Guido van Rossumd8faa362007-04-27 19:54:29 +00001311 if (Py_InspectFlag)
1312 /* Don't exit if -i flag was given. This flag is set to 0
1313 * when entering interactive mode for inspecting. */
1314 return;
1315
Guido van Rossum66e8e862001-03-23 17:54:43 +00001316 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001317 fflush(stdout);
1318 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001319 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001320 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001321 /* The error code should be in the `code' attribute. */
1322 PyObject *code = PyObject_GetAttrString(value, "code");
1323 if (code) {
1324 Py_DECREF(value);
1325 value = code;
1326 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001327 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001328 }
1329 /* If we failed to dig out the 'code' attribute,
1330 just let the else clause below print the error. */
1331 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001332 if (PyLong_Check(value))
1333 exitcode = (int)PyLong_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001334 else {
1335 PyObject_Print(value, stderr, Py_PRINT_RAW);
1336 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001337 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001338 }
Tim Peterscf615b52003-04-19 18:47:02 +00001339 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001340 /* Restore and clear the exception info, in order to properly decref
1341 * the exception, value, and traceback. If we just exit instead,
1342 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1343 * some finalizers from running.
1344 */
Tim Peterscf615b52003-04-19 18:47:02 +00001345 PyErr_Restore(exception, value, tb);
1346 PyErr_Clear();
1347 Py_Exit(exitcode);
1348 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001349}
1350
1351void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001352PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001353{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001354 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001355
1356 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1357 handle_system_exit();
1358 }
Guido van Rossum82598051997-03-05 00:20:32 +00001359 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001360 if (exception == NULL)
1361 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001362 PyErr_NormalizeException(&exception, &v, &tb);
Antoine Pitroue2dffc02008-08-26 22:02:58 +00001363 if (tb == NULL) {
1364 tb = Py_None;
1365 Py_INCREF(tb);
1366 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001367 PyException_SetTraceback(v, tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001368 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001369 return;
Georg Brandl86b2fb92008-07-16 03:43:04 +00001370 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001371 if (set_sys_last_vars) {
1372 PySys_SetObject("last_type", exception);
1373 PySys_SetObject("last_value", v);
Benjamin Petersone6528212008-07-15 15:32:09 +00001374 PySys_SetObject("last_traceback", tb);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001375 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001376 hook = PySys_GetObject("excepthook");
1377 if (hook) {
Benjamin Petersone6528212008-07-15 15:32:09 +00001378 PyObject *args = PyTuple_Pack(3, exception, v, tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001379 PyObject *result = PyEval_CallObject(hook, args);
1380 if (result == NULL) {
1381 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001382 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1383 handle_system_exit();
1384 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001385 PyErr_Fetch(&exception2, &v2, &tb2);
1386 PyErr_NormalizeException(&exception2, &v2, &tb2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001387 /* It should not be possible for exception2 or v2
1388 to be NULL. However PyErr_Display() can't
1389 tolerate NULLs, so just be safe. */
1390 if (exception2 == NULL) {
1391 exception2 = Py_None;
1392 Py_INCREF(exception2);
1393 }
1394 if (v2 == NULL) {
1395 v2 = Py_None;
1396 Py_INCREF(v2);
1397 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001398 fflush(stdout);
1399 PySys_WriteStderr("Error in sys.excepthook:\n");
1400 PyErr_Display(exception2, v2, tb2);
1401 PySys_WriteStderr("\nOriginal exception was:\n");
1402 PyErr_Display(exception, v, tb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001403 Py_DECREF(exception2);
1404 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001405 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001406 }
1407 Py_XDECREF(result);
1408 Py_XDECREF(args);
1409 } else {
1410 PySys_WriteStderr("sys.excepthook is missing\n");
1411 PyErr_Display(exception, v, tb);
1412 }
1413 Py_XDECREF(exception);
1414 Py_XDECREF(v);
1415 Py_XDECREF(tb);
1416}
1417
Benjamin Petersone6528212008-07-15 15:32:09 +00001418static void
1419print_exception(PyObject *f, PyObject *value)
1420{
1421 int err = 0;
1422 PyObject *type, *tb;
1423
Benjamin Peterson26582602008-08-23 20:08:07 +00001424 if (!PyExceptionInstance_Check(value)) {
1425 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1426 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1427 PyFile_WriteString(" found\n", f);
1428 return;
1429 }
1430
Benjamin Petersone6528212008-07-15 15:32:09 +00001431 Py_INCREF(value);
1432 fflush(stdout);
1433 type = (PyObject *) Py_TYPE(value);
1434 tb = PyException_GetTraceback(value);
1435 if (tb && tb != Py_None)
1436 err = PyTraceBack_Print(tb, f);
1437 if (err == 0 &&
1438 PyObject_HasAttrString(value, "print_file_and_line"))
1439 {
1440 PyObject *message;
1441 const char *filename, *text;
1442 int lineno, offset;
1443 if (!parse_syntax_error(value, &message, &filename,
1444 &lineno, &offset, &text))
1445 PyErr_Clear();
1446 else {
1447 char buf[10];
1448 PyFile_WriteString(" File \"", f);
1449 if (filename == NULL)
1450 PyFile_WriteString("<string>", f);
1451 else
1452 PyFile_WriteString(filename, f);
1453 PyFile_WriteString("\", line ", f);
1454 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1455 PyFile_WriteString(buf, f);
1456 PyFile_WriteString("\n", f);
1457 if (text != NULL)
1458 print_error_text(f, offset, text);
1459 Py_DECREF(value);
1460 value = message;
1461 /* Can't be bothered to check all those
1462 PyFile_WriteString() calls */
1463 if (PyErr_Occurred())
1464 err = -1;
1465 }
1466 }
1467 if (err) {
1468 /* Don't do anything else */
1469 }
1470 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001471 PyObject* moduleName;
Thomas Hellerd88ddfa2008-07-15 17:14:51 +00001472 char* className;
1473 assert(PyExceptionClass_Check(type));
1474 className = PyExceptionClass_Name(type);
Benjamin Petersone6528212008-07-15 15:32:09 +00001475 if (className != NULL) {
1476 char *dot = strrchr(className, '.');
1477 if (dot != NULL)
1478 className = dot+1;
1479 }
1480
1481 moduleName = PyObject_GetAttrString(type, "__module__");
1482 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1483 {
1484 Py_DECREF(moduleName);
1485 err = PyFile_WriteString("<unknown>", f);
1486 }
1487 else {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001488 char* modstr = _PyUnicode_AsString(moduleName);
Benjamin Petersone6528212008-07-15 15:32:09 +00001489 if (modstr && strcmp(modstr, "builtins"))
1490 {
1491 err = PyFile_WriteString(modstr, f);
1492 err += PyFile_WriteString(".", f);
1493 }
1494 Py_DECREF(moduleName);
1495 }
1496 if (err == 0) {
1497 if (className == NULL)
1498 err = PyFile_WriteString("<unknown>", f);
1499 else
1500 err = PyFile_WriteString(className, f);
1501 }
1502 }
1503 if (err == 0 && (value != Py_None)) {
1504 PyObject *s = PyObject_Str(value);
1505 /* only print colon if the str() of the
1506 object is not the empty string
1507 */
1508 if (s == NULL)
1509 err = -1;
1510 else if (!PyUnicode_Check(s) ||
1511 PyUnicode_GetSize(s) != 0)
1512 err = PyFile_WriteString(": ", f);
1513 if (err == 0)
1514 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1515 Py_XDECREF(s);
1516 }
1517 /* try to write a newline in any case */
1518 err += PyFile_WriteString("\n", f);
1519 Py_XDECREF(tb);
1520 Py_DECREF(value);
1521 /* If an error happened here, don't show it.
1522 XXX This is wrong, but too many callers rely on this behavior. */
1523 if (err != 0)
1524 PyErr_Clear();
1525}
1526
1527static const char *cause_message =
1528 "\nThe above exception was the direct cause "
1529 "of the following exception:\n\n";
1530
1531static const char *context_message =
1532 "\nDuring handling of the above exception, "
1533 "another exception occurred:\n\n";
1534
1535static void
1536print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1537{
1538 int err = 0, res;
1539 PyObject *cause, *context;
1540
1541 if (seen != NULL) {
1542 /* Exception chaining */
1543 if (PySet_Add(seen, value) == -1)
1544 PyErr_Clear();
1545 else if (PyExceptionInstance_Check(value)) {
1546 cause = PyException_GetCause(value);
1547 context = PyException_GetContext(value);
1548 if (cause) {
1549 res = PySet_Contains(seen, cause);
1550 if (res == -1)
1551 PyErr_Clear();
1552 if (res == 0) {
1553 print_exception_recursive(
1554 f, cause, seen);
1555 err |= PyFile_WriteString(
1556 cause_message, f);
1557 }
1558 }
1559 if (context) {
1560 res = PySet_Contains(seen, context);
1561 if (res == -1)
1562 PyErr_Clear();
1563 if (res == 0) {
1564 print_exception_recursive(
1565 f, context, seen);
1566 err |= PyFile_WriteString(
1567 context_message, f);
1568 }
1569 }
1570 Py_XDECREF(context);
1571 Py_XDECREF(cause);
1572 }
1573 }
1574 print_exception(f, value);
1575 if (err != 0)
1576 PyErr_Clear();
1577}
1578
Thomas Wouters477c8d52006-05-27 19:21:47 +00001579void
1580PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001581{
Benjamin Petersone6528212008-07-15 15:32:09 +00001582 PyObject *seen;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001583 PyObject *f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +00001584 if (f == Py_None) {
1585 /* pass */
1586 }
1587 else if (f == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001588 _PyObject_Dump(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001589 fprintf(stderr, "lost sys.stderr\n");
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001590 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001591 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001592 /* We choose to ignore seen being possibly NULL, and report
1593 at least the main exception (it could be a MemoryError).
1594 */
1595 seen = PySet_New(NULL);
1596 if (seen == NULL)
1597 PyErr_Clear();
1598 print_exception_recursive(f, value, seen);
1599 Py_XDECREF(seen);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001600 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001601}
1602
Guido van Rossum82598051997-03-05 00:20:32 +00001603PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001604PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001605 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001606{
Neal Norwitze92fba02006-03-04 18:52:26 +00001607 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001608 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001609 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001610 if (arena == NULL)
1611 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001612
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001613 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001614 if (mod != NULL)
1615 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001616 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001617 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001618}
1619
1620PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001621PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001622 PyObject *locals, int closeit, PyCompilerFlags *flags)
1623{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001624 PyObject *ret;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001625 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001626 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001627 if (arena == NULL)
1628 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001629
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001630 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001631 flags, NULL, arena);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001632 if (closeit)
1633 fclose(fp);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001634 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001635 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001636 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001637 }
Neal Norwitze92fba02006-03-04 18:52:26 +00001638 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001639 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001640 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001641}
1642
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001643static void
1644flush_io(void)
1645{
1646 PyObject *f, *r;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001647 PyObject *type, *value, *traceback;
1648
1649 /* Save the current exception */
1650 PyErr_Fetch(&type, &value, &traceback);
1651
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001652 f = PySys_GetObject("stderr");
1653 if (f != NULL) {
1654 r = PyObject_CallMethod(f, "flush", "");
1655 if (r)
1656 Py_DECREF(r);
1657 else
1658 PyErr_Clear();
1659 }
1660 f = PySys_GetObject("stdout");
1661 if (f != NULL) {
1662 r = PyObject_CallMethod(f, "flush", "");
1663 if (r)
1664 Py_DECREF(r);
1665 else
1666 PyErr_Clear();
1667 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001668
1669 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001670}
1671
Guido van Rossum82598051997-03-05 00:20:32 +00001672static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001673run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001674 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001675{
Guido van Rossum82598051997-03-05 00:20:32 +00001676 PyCodeObject *co;
1677 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001678 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001679 if (co == NULL)
1680 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001681 v = PyEval_EvalCode(co, globals, locals);
1682 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001683 return v;
1684}
1685
Guido van Rossum82598051997-03-05 00:20:32 +00001686static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001687run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001688 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001689{
Guido van Rossum82598051997-03-05 00:20:32 +00001690 PyCodeObject *co;
1691 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001692 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001693 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001694
Guido van Rossum82598051997-03-05 00:20:32 +00001695 magic = PyMarshal_ReadLongFromFile(fp);
1696 if (magic != PyImport_GetMagicNumber()) {
1697 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001698 "Bad magic number in .pyc file");
1699 return NULL;
1700 }
Guido van Rossum82598051997-03-05 00:20:32 +00001701 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001702 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001703 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001704 if (v == NULL || !PyCode_Check(v)) {
1705 Py_XDECREF(v);
1706 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001707 "Bad code object in .pyc file");
1708 return NULL;
1709 }
Guido van Rossum82598051997-03-05 00:20:32 +00001710 co = (PyCodeObject *)v;
1711 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001712 if (v && flags)
1713 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001714 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001715 return v;
1716}
1717
Guido van Rossum82598051997-03-05 00:20:32 +00001718PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001719Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001720 PyCompilerFlags *flags)
1721{
Guido van Rossum82598051997-03-05 00:20:32 +00001722 PyCodeObject *co;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001723 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001724 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001725 if (arena == NULL)
1726 return NULL;
1727
1728 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001729 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001730 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001731 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001732 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001733 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001734 PyObject *result = PyAST_mod2obj(mod);
1735 PyArena_Free(arena);
1736 return result;
1737 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001738 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001739 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001740 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001741}
1742
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001743struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001744Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001745{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001746 struct symtable *st;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001747 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001748 PyCompilerFlags flags;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001749 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001750 if (arena == NULL)
1751 return NULL;
1752
Christian Heimesb1b3efc2008-03-26 23:24:27 +00001753 flags.cf_flags = 0;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001754 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001755 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001756 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001757 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001758 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001759 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001760 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001761 return st;
1762}
1763
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001764/* Preferred access to parser is through AST. */
1765mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001766PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001767 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001768{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001769 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001770 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001771 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001772 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001773
1774 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001775 &_PyParser_Grammar, start, &err,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001776 &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001777 if (flags == NULL) {
1778 localflags.cf_flags = 0;
1779 flags = &localflags;
1780 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001781 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001782 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001783 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001784 PyNode_Free(n);
1785 return mod;
1786 }
1787 else {
1788 err_input(&err);
1789 return NULL;
1790 }
1791}
1792
1793mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001794PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1795 int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001796 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001797 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001798{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001799 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001800 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001801 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001802 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001803
Christian Heimes4d6ec852008-03-26 22:34:47 +00001804 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001805 &_PyParser_Grammar,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001806 start, ps1, ps2, &err, &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001807 if (flags == NULL) {
1808 localflags.cf_flags = 0;
1809 flags = &localflags;
1810 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001811 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001812 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001813 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001814 PyNode_Free(n);
1815 return mod;
1816 }
1817 else {
1818 err_input(&err);
1819 if (errcode)
1820 *errcode = err.error;
1821 return NULL;
1822 }
1823}
1824
Guido van Rossuma110aa61994-08-29 12:50:44 +00001825/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001826
Guido van Rossuma110aa61994-08-29 12:50:44 +00001827node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001828PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001829{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001830 perrdetail err;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001831 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1832 &_PyParser_Grammar,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001833 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001834 if (n == NULL)
1835 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001836
Guido van Rossuma110aa61994-08-29 12:50:44 +00001837 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001838}
1839
Guido van Rossuma110aa61994-08-29 12:50:44 +00001840/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001841
Guido van Rossuma110aa61994-08-29 12:50:44 +00001842node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001843PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001844{
Tim Petersfe2127d2001-07-16 05:37:24 +00001845 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001846 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1847 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001848 if (n == NULL)
1849 err_input(&err);
1850 return n;
1851}
1852
1853node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001854PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001855 int start, int flags)
1856{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001857 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001858 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1859 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001860 if (n == NULL)
1861 err_input(&err);
1862 return n;
1863}
1864
1865node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001866PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001867{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001868 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001869}
1870
Guido van Rossum66ebd912003-04-17 16:02:26 +00001871/* May want to move a more generalized form of this to parsetok.c or
1872 even parser modules. */
1873
1874void
1875PyParser_SetError(perrdetail *err)
1876{
1877 err_input(err);
1878}
1879
Guido van Rossuma110aa61994-08-29 12:50:44 +00001880/* Set the error appropriate to the given input error code (see errcode.h) */
1881
1882static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001883err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001884{
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001885 PyObject *v, *w, *errtype, *errtext;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001886 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001887 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001888 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001889 switch (err->error) {
1890 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001891 errtype = PyExc_IndentationError;
1892 if (err->expected == INDENT)
1893 msg = "expected an indented block";
1894 else if (err->token == INDENT)
1895 msg = "unexpected indent";
1896 else if (err->token == DEDENT)
1897 msg = "unexpected unindent";
1898 else {
1899 errtype = PyExc_SyntaxError;
1900 msg = "invalid syntax";
1901 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001902 break;
1903 case E_TOKEN:
1904 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001905 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001906 case E_EOFS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001907 msg = "EOF while scanning triple-quoted string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001908 break;
1909 case E_EOLS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001910 msg = "EOL while scanning string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001911 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001912 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001913 if (!PyErr_Occurred())
1914 PyErr_SetNone(PyExc_KeyboardInterrupt);
Georg Brandl3dbca812008-07-23 16:10:53 +00001915 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001916 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001917 PyErr_NoMemory();
Georg Brandl3dbca812008-07-23 16:10:53 +00001918 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001919 case E_EOF:
1920 msg = "unexpected EOF while parsing";
1921 break;
Fred Drake85f36392000-07-11 17:53:00 +00001922 case E_TABSPACE:
1923 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001924 msg = "inconsistent use of tabs and spaces in indentation";
1925 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001926 case E_OVERFLOW:
1927 msg = "expression too long";
1928 break;
Fred Drake85f36392000-07-11 17:53:00 +00001929 case E_DEDENT:
1930 errtype = PyExc_IndentationError;
1931 msg = "unindent does not match any outer indentation level";
1932 break;
1933 case E_TOODEEP:
1934 errtype = PyExc_IndentationError;
1935 msg = "too many levels of indentation";
1936 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001937 case E_DECODE: {
1938 PyObject *type, *value, *tb;
1939 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001940 if (value != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001941 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001942 if (u != NULL) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001943 msg = _PyUnicode_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001944 }
1945 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001946 if (msg == NULL)
1947 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001948 Py_XDECREF(type);
1949 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001950 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001951 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001952 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001953 case E_LINECONT:
1954 msg = "unexpected character after line continuation character";
1955 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001956
1957 case E_IDENTIFIER:
1958 msg = "invalid character in identifier";
1959 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001960 default:
1961 fprintf(stderr, "error=%d\n", err->error);
1962 msg = "unknown parsing error";
1963 break;
1964 }
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001965 /* err->text may not be UTF-8 in case of decoding errors.
1966 Explicitly convert to an object. */
1967 if (!err->text) {
1968 errtext = Py_None;
1969 Py_INCREF(Py_None);
1970 } else {
1971 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1972 "replace");
1973 }
1974 v = Py_BuildValue("(ziiN)", err->filename,
1975 err->lineno, err->offset, errtext);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001976 w = NULL;
1977 if (v != NULL)
1978 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001979 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001980 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001981 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001982 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00001983cleanup:
1984 if (err->text != NULL) {
1985 PyObject_FREE(err->text);
1986 err->text = NULL;
1987 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001988}
1989
1990/* Print fatal error message and abort */
1991
1992void
Tim Peters7c321a82002-07-09 02:57:01 +00001993Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001994{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00001995 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001996 if (PyErr_Occurred()) {
1997 PyErr_Print();
1998 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00001999#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002000 {
2001 size_t len = strlen(msg);
2002 WCHAR* buffer;
2003 size_t i;
2004
2005 /* Convert the message to wchar_t. This uses a simple one-to-one
2006 conversion, assuming that the this error message actually uses ASCII
2007 only. If this ceases to be true, we will have to convert. */
2008 buffer = alloca( (len+1) * (sizeof *buffer));
2009 for( i=0; i<=len; ++i)
2010 buffer[i] = msg[i];
2011 OutputDebugStringW(L"Fatal Python error: ");
2012 OutputDebugStringW(buffer);
2013 OutputDebugStringW(L"\n");
2014 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002015#ifdef _DEBUG
2016 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002017#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002018#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002019 abort();
2020}
2021
2022/* Clean up and exit */
2023
Guido van Rossuma110aa61994-08-29 12:50:44 +00002024#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002025#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002026#endif
2027
Collin Winter670e6922007-03-21 02:57:17 +00002028static void (*pyexitfunc)(void) = NULL;
2029/* For the atexit module. */
2030void _Py_PyAtExit(void (*func)(void))
2031{
2032 pyexitfunc = func;
2033}
2034
2035static void
2036call_py_exitfuncs(void)
2037{
Guido van Rossum98297ee2007-11-06 21:34:58 +00002038 if (pyexitfunc == NULL)
Collin Winter670e6922007-03-21 02:57:17 +00002039 return;
2040
2041 (*pyexitfunc)();
2042 PyErr_Clear();
2043}
2044
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002045#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002046static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002047static int nexitfuncs = 0;
2048
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002049int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002050{
2051 if (nexitfuncs >= NEXITFUNCS)
2052 return -1;
2053 exitfuncs[nexitfuncs++] = func;
2054 return 0;
2055}
2056
Guido van Rossumcc283f51997-08-05 02:22:03 +00002057static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002058call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002059{
Guido van Rossum1662dd51994-09-07 14:38:28 +00002060 while (nexitfuncs > 0)
2061 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002062
2063 fflush(stdout);
2064 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002065}
2066
2067void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002068Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002069{
Guido van Rossumcc283f51997-08-05 02:22:03 +00002070 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002071
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002072 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002073}
2074
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002075static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002076initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002077{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002078#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002079 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002080#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002081#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002082 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002083#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002084#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002085 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002086#endif
Guido van Rossum82598051997-03-05 00:20:32 +00002087 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002088}
2089
Guido van Rossum7433b121997-02-14 19:45:36 +00002090
2091/*
2092 * The file descriptor fd is considered ``interactive'' if either
2093 * a) isatty(fd) is TRUE, or
2094 * b) the -i flag was given, and the filename associated with
2095 * the descriptor is NULL or "<stdin>" or "???".
2096 */
2097int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002098Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002099{
2100 if (isatty((int)fileno(fp)))
2101 return 1;
2102 if (!Py_InteractiveFlag)
2103 return 0;
2104 return (filename == NULL) ||
2105 (strcmp(filename, "<stdin>") == 0) ||
2106 (strcmp(filename, "???") == 0);
2107}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002108
2109
Tim Petersd08e3822003-04-17 15:24:21 +00002110#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002111#if defined(WIN32) && defined(_MSC_VER)
2112
2113/* Stack checking for Microsoft C */
2114
2115#include <malloc.h>
2116#include <excpt.h>
2117
Fred Drakee8de31c2000-08-31 05:38:39 +00002118/*
2119 * Return non-zero when we run out of memory on the stack; zero otherwise.
2120 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002121int
Fred Drake399739f2000-08-31 05:52:44 +00002122PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002123{
2124 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00002125 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002126 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00002127 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002128 return 0;
Christian Heimes7131fd92008-02-19 14:21:46 +00002129 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
Trent Nelson39e307e2008-03-19 06:45:48 +00002130 EXCEPTION_EXECUTE_HANDLER :
2131 EXCEPTION_CONTINUE_SEARCH) {
Christian Heimes7131fd92008-02-19 14:21:46 +00002132 int errcode = _resetstkoflw();
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +00002133 if (errcode == 0)
Christian Heimes7131fd92008-02-19 14:21:46 +00002134 {
2135 Py_FatalError("Could not reset the stack!");
2136 }
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002137 }
2138 return 1;
2139}
2140
2141#endif /* WIN32 && _MSC_VER */
2142
2143/* Alternate implementations can be added here... */
2144
2145#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002146
2147
2148/* Wrappers around sigaction() or signal(). */
2149
2150PyOS_sighandler_t
2151PyOS_getsig(int sig)
2152{
2153#ifdef HAVE_SIGACTION
2154 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002155 if (sigaction(sig, NULL, &context) == -1)
2156 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00002157 return context.sa_handler;
2158#else
2159 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002160/* Special signal handling for the secure CRT in Visual Studio 2005 */
2161#if defined(_MSC_VER) && _MSC_VER >= 1400
2162 switch (sig) {
2163 /* Only these signals are valid */
2164 case SIGINT:
2165 case SIGILL:
2166 case SIGFPE:
2167 case SIGSEGV:
2168 case SIGTERM:
2169 case SIGBREAK:
2170 case SIGABRT:
2171 break;
2172 /* Don't call signal() with other values or it will assert */
2173 default:
2174 return SIG_ERR;
2175 }
2176#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002177 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002178 if (handler != SIG_ERR)
2179 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00002180 return handler;
2181#endif
2182}
2183
2184PyOS_sighandler_t
2185PyOS_setsig(int sig, PyOS_sighandler_t handler)
2186{
2187#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002188 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00002189 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002190 sigemptyset(&context.sa_mask);
2191 context.sa_flags = 0;
2192 if (sigaction(sig, &context, &ocontext) == -1)
2193 return SIG_ERR;
2194 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002195#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002196 PyOS_sighandler_t oldhandler;
2197 oldhandler = signal(sig, handler);
2198#ifdef HAVE_SIGINTERRUPT
2199 siginterrupt(sig, 1);
2200#endif
2201 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002202#endif
2203}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002204
2205/* Deprecated C API functions still provided for binary compatiblity */
2206
2207#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002208PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002209PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2210{
2211 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2212}
2213
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002214#undef PyParser_SimpleParseString
2215PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002216PyParser_SimpleParseString(const char *str, int start)
2217{
2218 return PyParser_SimpleParseStringFlags(str, start, 0);
2219}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002220
2221#undef PyRun_AnyFile
2222PyAPI_FUNC(int)
2223PyRun_AnyFile(FILE *fp, const char *name)
2224{
2225 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
2226}
2227
2228#undef PyRun_AnyFileEx
2229PyAPI_FUNC(int)
2230PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2231{
2232 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
2233}
2234
2235#undef PyRun_AnyFileFlags
2236PyAPI_FUNC(int)
2237PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2238{
2239 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2240}
2241
2242#undef PyRun_File
2243PyAPI_FUNC(PyObject *)
2244PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2245{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002246 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002247}
2248
2249#undef PyRun_FileEx
2250PyAPI_FUNC(PyObject *)
2251PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2252{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002253 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002254}
2255
2256#undef PyRun_FileFlags
2257PyAPI_FUNC(PyObject *)
2258PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2259 PyCompilerFlags *flags)
2260{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002261 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002262}
2263
2264#undef PyRun_SimpleFile
2265PyAPI_FUNC(int)
2266PyRun_SimpleFile(FILE *f, const char *p)
2267{
2268 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
2269}
2270
2271#undef PyRun_SimpleFileEx
2272PyAPI_FUNC(int)
2273PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2274{
2275 return PyRun_SimpleFileExFlags(f, p, c, NULL);
2276}
2277
2278
2279#undef PyRun_String
2280PyAPI_FUNC(PyObject *)
2281PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2282{
2283 return PyRun_StringFlags(str, s, g, l, NULL);
2284}
2285
2286#undef PyRun_SimpleString
2287PyAPI_FUNC(int)
2288PyRun_SimpleString(const char *s)
2289{
2290 return PyRun_SimpleStringFlags(s, NULL);
2291}
2292
2293#undef Py_CompileString
2294PyAPI_FUNC(PyObject *)
2295Py_CompileString(const char *str, const char *p, int s)
2296{
2297 return Py_CompileStringFlags(str, p, s, NULL);
2298}
2299
2300#undef PyRun_InteractiveOne
2301PyAPI_FUNC(int)
2302PyRun_InteractiveOne(FILE *f, const char *p)
2303{
2304 return PyRun_InteractiveOneFlags(f, p, NULL);
2305}
2306
2307#undef PyRun_InteractiveLoop
2308PyAPI_FUNC(int)
2309PyRun_InteractiveLoop(FILE *f, const char *p)
2310{
2311 return PyRun_InteractiveLoopFlags(f, p, NULL);
2312}
2313
2314#ifdef __cplusplus
2315}
2316#endif