blob: 65c6f5f2da14598055728f2d7c2f51d5547a7784 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Python interpreter top-level routines, including init/exit */
3
Guido van Rossum82598051997-03-05 00:20:32 +00004#include "Python.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00008#include "grammar.h"
9#include "node.h"
Fred Drake85f36392000-07-11 17:53:00 +000010#include "token.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000011#include "parsetok.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000012#include "errcode.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000013#include "code.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000014#include "compile.h"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000015#include "symtable.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +000016#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000017#include "ast.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000018#include "eval.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000019#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000020#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000021
Thomas Wouters0e3f5912006-08-11 14:57:12 +000022#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000023#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000024#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000025
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000026#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000027#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000028#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000029
Martin v. Löwis73d538b2003-03-05 15:13:47 +000030#ifdef HAVE_LANGINFO_H
31#include <locale.h>
32#include <langinfo.h>
33#endif
34
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000035#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#undef BYTE
37#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000038#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000039#endif
40
Neal Norwitz4281cef2006-03-04 19:58:13 +000041#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000042#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000043#else /* Py_REF_DEBUG */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000044#define PRINT_TOTAL_REFS() fprintf(stderr, \
45 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
46 _Py_GetRefTotal())
47#endif
48
49#ifdef __cplusplus
50extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000051#endif
52
Martin v. Löwis790465f2008-04-05 20:41:37 +000053extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000054
Guido van Rossum82598051997-03-05 00:20:32 +000055extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000056
Guido van Rossumb73cc041993-11-01 16:28:59 +000057/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000058static void initmain(void);
59static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000060static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000061static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000062static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Neal Norwitzadb69fc2005-12-17 20:54:49 +000063 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000064static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Jeremy Hyltonbc320242001-03-22 02:47:58 +000065 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000066static void err_input(perrdetail *);
67static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000068static void call_py_exitfuncs(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000069static void call_ll_exitfuncs(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000070extern void _PyUnicode_Init(void);
71extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000072extern int _PyLong_Init(void);
73extern void PyLong_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000074
Mark Hammond8d98d2c2003-04-19 15:41:53 +000075#ifdef WITH_THREAD
76extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
77extern void _PyGILState_Fini(void);
78#endif /* WITH_THREAD */
79
Guido van Rossum82598051997-03-05 00:20:32 +000080int Py_DebugFlag; /* Needed by parser.c */
81int Py_VerboseFlag; /* Needed by import.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000082int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Guido van Rossumd8faa362007-04-27 19:54:29 +000083int Py_InspectFlag; /* Needed to determine whether to exit at SystemError */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000084int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000085int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000086int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000087int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000088int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000089int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000090int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000091int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000092
Christian Heimes33fe8092008-04-13 13:53:33 +000093/* PyModule_GetWarningsModule is no longer necessary as of 2.6
94since _warnings is builtin. This API should not be used. */
95PyObject *
96PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +000097{
Christian Heimes33fe8092008-04-13 13:53:33 +000098 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +000099}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000100
Guido van Rossum25ce5661997-08-02 03:10:38 +0000101static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000102
Thomas Wouters7e474022000-07-16 12:04:32 +0000103/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000104
105int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000106Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000107{
108 return initialized;
109}
110
Guido van Rossum25ce5661997-08-02 03:10:38 +0000111/* Global initializations. Can be undone by Py_Finalize(). Don't
112 call this twice without an intervening Py_Finalize() call. When
113 initializations fail, a fatal error is issued and the function does
114 not return. On return, the first thread and interpreter state have
115 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000116
Guido van Rossum25ce5661997-08-02 03:10:38 +0000117 Locking: you must hold the interpreter lock while calling this.
118 (If the lock has not yet been initialized, that's equivalent to
119 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000120
Guido van Rossum25ce5661997-08-02 03:10:38 +0000121*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000122
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000123static int
124add_flag(int flag, const char *envs)
125{
126 int env = atoi(envs);
127 if (flag < env)
128 flag = env;
129 if (flag < 1)
130 flag = 1;
131 return flag;
132}
133
Christian Heimes5833a2f2008-10-30 21:40:04 +0000134#if defined(HAVE_LANGINFO_H) && defined(CODESET)
135static char*
136get_codeset(void)
137{
138 char* codeset;
139 PyObject *codec, *name;
140
141 codeset = nl_langinfo(CODESET);
142 if (!codeset || codeset[0] == '\0')
143 return NULL;
144
145 codec = _PyCodec_Lookup(codeset);
146 if (!codec)
147 goto error;
148
149 name = PyObject_GetAttrString(codec, "name");
150 Py_CLEAR(codec);
151 if (!name)
152 goto error;
153
154 codeset = strdup(_PyUnicode_AsString(name));
155 Py_DECREF(name);
156 return codeset;
157
158error:
159 Py_XDECREF(codec);
160 PyErr_Clear();
161 return NULL;
162}
163#endif
164
Guido van Rossuma027efa1997-05-05 20:56:21 +0000165void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000166Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000167{
Guido van Rossuma027efa1997-05-05 20:56:21 +0000168 PyInterpreterState *interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000169 PyThreadState *tstate;
Guido van Rossum826d8972007-10-30 18:34:07 +0000170 PyObject *bimod, *sysmod, *pstderr;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000171 char *p;
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000172#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000173 char *codeset;
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000174#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +0000175 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000176
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000177 if (initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000178 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000179 initialized = 1;
Tim Petersd08e3822003-04-17 15:24:21 +0000180
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000181#ifdef HAVE_SETLOCALE
182 /* Set up the LC_CTYPE locale, so we can obtain
183 the locale's charset without having to switch
184 locales. */
185 setlocale(LC_CTYPE, "");
186#endif
187
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000188 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000189 Py_DebugFlag = add_flag(Py_DebugFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000190 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000191 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +0000192 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000193 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
Christian Heimes790c8232008-01-07 21:14:23 +0000194 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
195 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000196
Guido van Rossuma027efa1997-05-05 20:56:21 +0000197 interp = PyInterpreterState_New();
198 if (interp == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000199 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000200
Guido van Rossuma027efa1997-05-05 20:56:21 +0000201 tstate = PyThreadState_New(interp);
202 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000203 Py_FatalError("Py_Initialize: can't make first thread");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000204 (void) PyThreadState_Swap(tstate);
205
Guido van Rossum70d893a2001-08-16 08:21:42 +0000206 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000207
Neal Norwitzb2501f42002-12-31 03:42:13 +0000208 if (!_PyFrame_Init())
Neal Norwitzc91ed402002-12-30 22:29:22 +0000209 Py_FatalError("Py_Initialize: can't init frames");
210
Guido van Rossumddefaf32007-01-14 03:31:43 +0000211 if (!_PyLong_Init())
212 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000213
Christian Heimes9c4756e2008-05-26 13:22:05 +0000214 if (!PyByteArray_Init())
Neal Norwitz6968b052007-02-27 19:02:19 +0000215 Py_FatalError("Py_Initialize: can't init bytes");
216
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000217 _PyFloat_Init();
218
Guido van Rossum25ce5661997-08-02 03:10:38 +0000219 interp->modules = PyDict_New();
220 if (interp->modules == NULL)
221 Py_FatalError("Py_Initialize: can't make modules dictionary");
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222 interp->modules_reloading = PyDict_New();
223 if (interp->modules_reloading == NULL)
224 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000225
Guido van Rossumc94044c2000-03-10 23:03:54 +0000226 /* Init Unicode implementation; relies on the codec registry */
227 _PyUnicode_Init();
228
Barry Warsawf242aa02000-05-25 23:09:49 +0000229 bimod = _PyBuiltin_Init();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000230 if (bimod == NULL)
Georg Brandl1a3284e2007-12-02 09:40:06 +0000231 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Martin v. Löwis1a214512008-06-11 05:26:20 +0000232 _PyImport_FixupExtension(bimod, "builtins", "builtins");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000233 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000234 if (interp->builtins == NULL)
235 Py_FatalError("Py_Initialize: can't initialize builtins dict");
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000236 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000237
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000238 /* initialize builtin exceptions */
239 _PyExc_Init();
240
Guido van Rossum25ce5661997-08-02 03:10:38 +0000241 sysmod = _PySys_Init();
242 if (sysmod == NULL)
243 Py_FatalError("Py_Initialize: can't initialize sys");
244 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000245 if (interp->sysdict == NULL)
246 Py_FatalError("Py_Initialize: can't initialize sys dict");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000247 Py_INCREF(interp->sysdict);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000248 _PyImport_FixupExtension(sysmod, "sys", "sys");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000249 PySys_SetPath(Py_GetPath());
Guido van Rossum25ce5661997-08-02 03:10:38 +0000250 PyDict_SetItemString(interp->sysdict, "modules",
251 interp->modules);
252
Guido van Rossum826d8972007-10-30 18:34:07 +0000253 /* Set up a preliminary stderr printer until we have enough
254 infrastructure for the io module in place. */
255 pstderr = PyFile_NewStdPrinter(fileno(stderr));
256 if (pstderr == NULL)
257 Py_FatalError("Py_Initialize: can't set preliminary stderr");
258 PySys_SetObject("stderr", pstderr);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000259 PySys_SetObject("__stderr__", pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000260
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000261 _PyImport_Init();
262
Just van Rossum52e14d62002-12-30 22:08:05 +0000263 _PyImportHooks_Init();
264
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000265 if (install_sigs)
266 initsigs(); /* Signal handling stuff, including initintr() */
Christian Heimes33fe8092008-04-13 13:53:33 +0000267
Georg Brandl86b2fb92008-07-16 03:43:04 +0000268 /* Initialize warnings. */
269 _PyWarnings_Init();
270 if (PySys_HasWarnOptions()) {
271 PyObject *warnings_module = PyImport_ImportModule("warnings");
272 if (!warnings_module)
273 PyErr_Clear();
274 Py_XDECREF(warnings_module);
275 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000276
277 initmain(); /* Module __main__ */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000278 if (initstdio() < 0)
279 Py_FatalError(
280 "Py_Initialize: can't initialize sys standard streams");
Benjamin Peterson791dc2f2008-09-05 23:27:15 +0000281 if (!Py_NoSiteFlag)
282 initsite(); /* Module site */
Just van Rossum5bfba3a2003-02-25 20:25:12 +0000283
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000284 /* auto-thread-state API, if available */
285#ifdef WITH_THREAD
286 _PyGILState_Init(interp, tstate);
287#endif /* WITH_THREAD */
288
Guido van Rossum8d30cc02007-05-03 17:49:24 +0000289#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000290 /* On Unix, set the file system encoding according to the
291 user's preference, if the CODESET names a well-known
292 Python codec, and Py_FileSystemDefaultEncoding isn't
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000293 initialized by other means. Also set the encoding of
294 stdin and stdout if these are terminals. */
295
Christian Heimes5833a2f2008-10-30 21:40:04 +0000296 codeset = get_codeset();
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000297 if (codeset) {
Martin v. Löwisa2c17c52003-08-09 09:47:11 +0000298 if (!Py_FileSystemDefaultEncoding)
299 Py_FileSystemDefaultEncoding = codeset;
300 else
301 free(codeset);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000302 }
303#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000304}
305
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000306void
307Py_Initialize(void)
308{
309 Py_InitializeEx(1);
310}
311
312
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000313#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000314extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000315#endif
316
Guido van Rossume8432ac2007-07-09 15:04:50 +0000317/* Flush stdout and stderr */
318
Neal Norwitz2bad9702007-08-27 06:19:22 +0000319static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000320flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000321{
322 PyObject *fout = PySys_GetObject("stdout");
323 PyObject *ferr = PySys_GetObject("stderr");
324 PyObject *tmp;
325
Christian Heimes2be03732007-11-15 02:26:46 +0000326 if (fout != NULL && fout != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000327 tmp = PyObject_CallMethod(fout, "flush", "");
328 if (tmp == NULL)
329 PyErr_Clear();
330 else
331 Py_DECREF(tmp);
332 }
333
Christian Heimes2be03732007-11-15 02:26:46 +0000334 if (ferr != NULL || ferr != Py_None) {
Guido van Rossume8432ac2007-07-09 15:04:50 +0000335 tmp = PyObject_CallMethod(ferr, "flush", "");
336 if (tmp == NULL)
337 PyErr_Clear();
338 else
339 Py_DECREF(tmp);
340 }
341}
342
Guido van Rossum25ce5661997-08-02 03:10:38 +0000343/* Undo the effect of Py_Initialize().
344
345 Beware: if multiple interpreter and/or thread states exist, these
346 are not wiped out; only the current thread and interpreter state
347 are deleted. But since everything else is deleted, those other
348 interpreter and thread states should no longer be used.
349
350 (XXX We should do better, e.g. wipe out all interpreters and
351 threads.)
352
353 Locking: as above.
354
355*/
356
357void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000358Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000359{
360 PyInterpreterState *interp;
361 PyThreadState *tstate;
362
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000363 if (!initialized)
Guido van Rossumaa615051997-08-20 22:40:18 +0000364 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000365
Tim Peters384fd102001-01-21 03:40:37 +0000366 /* The interpreter is still entirely intact at this point, and the
367 * exit funcs may be relying on that. In particular, if some thread
368 * or exit func is still waiting to do an import, the import machinery
369 * expects Py_IsInitialized() to return true. So don't say the
370 * interpreter is uninitialized until after the exit funcs have run.
371 * Note that Threading.py uses an exit func to do a join on all the
372 * threads created thru it, so this also protects pending imports in
373 * the threads created via Threading.
374 */
Collin Winter670e6922007-03-21 02:57:17 +0000375 call_py_exitfuncs();
Tim Peters384fd102001-01-21 03:40:37 +0000376 initialized = 0;
Guido van Rossum4cc462e1998-01-19 22:00:38 +0000377
Guido van Rossume8432ac2007-07-09 15:04:50 +0000378 /* Flush stdout+stderr */
379 flush_std_files();
380
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000381 /* Get current thread state and interpreter pointer */
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000382 tstate = PyThreadState_GET();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000383 interp = tstate->interp;
384
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000385 /* Disable signal handling */
386 PyOS_FiniInterrupts();
387
Christian Heimes26855632008-01-27 23:50:43 +0000388 /* Clear type lookup cache */
389 PyType_ClearCache();
390
Guido van Rossume13ddc92003-04-17 17:29:22 +0000391 /* Collect garbage. This may call finalizers; it's nice to call these
Tim Peters1d7323e2003-12-01 21:35:27 +0000392 * before all modules are destroyed.
393 * XXX If a __del__ or weakref callback is triggered here, and tries to
394 * XXX import a module, bad things can happen, because Python no
395 * XXX longer believes it's initialized.
396 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
397 * XXX is easy to provoke that way. I've also seen, e.g.,
398 * XXX Exception exceptions.ImportError: 'No module named sha'
399 * XXX in <function callback at 0x008F5718> ignored
400 * XXX but I'm unclear on exactly how that one happens. In any case,
401 * XXX I haven't seen a real-life report of either of these.
Neal Norwitz9589ee22006-03-04 19:01:22 +0000402 */
Guido van Rossume13ddc92003-04-17 17:29:22 +0000403 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000404#ifdef COUNT_ALLOCS
405 /* With COUNT_ALLOCS, it helps to run GC multiple times:
406 each collection might release some types from the type
407 list, so they become garbage. */
408 while (PyGC_Collect() > 0)
409 /* nothing */;
410#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000411
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000412 /* Destroy all modules */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000413 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000414
Guido van Rossume8432ac2007-07-09 15:04:50 +0000415 /* Flush stdout+stderr (again, in case more was printed) */
416 flush_std_files();
417
Guido van Rossume13ddc92003-04-17 17:29:22 +0000418 /* Collect final garbage. This disposes of cycles created by
Tim Peters1d7323e2003-12-01 21:35:27 +0000419 * new-style class definitions, for example.
420 * XXX This is disabled because it caused too many problems. If
421 * XXX a __del__ or weakref callback triggers here, Python code has
422 * XXX a hard time running, because even the sys module has been
423 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
424 * XXX One symptom is a sequence of information-free messages
425 * XXX coming from threads (if a __del__ or callback is invoked,
426 * XXX other threads can execute too, and any exception they encounter
427 * XXX triggers a comedy of errors as subsystem after subsystem
428 * XXX fails to find what it *expects* to find in sys to help report
429 * XXX the exception and consequent unexpected failures). I've also
430 * XXX seen segfaults then, after adding print statements to the
431 * XXX Python code getting called.
432 */
433#if 0
Guido van Rossume13ddc92003-04-17 17:29:22 +0000434 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000435#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000436
Guido van Rossum1707aad1997-12-08 23:43:45 +0000437 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
438 _PyImport_Fini();
439
440 /* Debugging stuff */
441#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000442 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000443#endif
444
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000445 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000446
Tim Peters9cf25ce2003-04-17 15:21:01 +0000447#ifdef Py_TRACE_REFS
448 /* Display all objects still alive -- this can invoke arbitrary
449 * __repr__ overrides, so requires a mostly-intact interpreter.
450 * Alas, a lot of stuff may still be alive now that will be cleaned
451 * up later.
452 */
Tim Peters269b2a62003-04-17 19:52:29 +0000453 if (Py_GETENV("PYTHONDUMPREFS"))
Tim Peters9cf25ce2003-04-17 15:21:01 +0000454 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000455#endif /* Py_TRACE_REFS */
456
Guido van Rossumd922fa42003-04-15 14:10:09 +0000457 /* Clear interpreter state */
Barry Warsawf242aa02000-05-25 23:09:49 +0000458 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000459
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000460 /* Now we decref the exception classes. After this point nothing
461 can raise an exception. That's okay, because each Fini() method
462 below has been checked to make sure no exceptions are ever
463 raised.
464 */
465
466 _PyExc_Fini();
467
Christian Heimes7d2ff882007-11-30 14:35:04 +0000468 /* Cleanup auto-thread-state */
469#ifdef WITH_THREAD
470 _PyGILState_Fini();
471#endif /* WITH_THREAD */
472
Guido van Rossumd922fa42003-04-15 14:10:09 +0000473 /* Delete current thread */
Barry Warsawf242aa02000-05-25 23:09:49 +0000474 PyThreadState_Swap(NULL);
475 PyInterpreterState_Delete(interp);
476
Guido van Rossumd922fa42003-04-15 14:10:09 +0000477 /* Sundry finalizers */
Guido van Rossumcc283f51997-08-05 02:22:03 +0000478 PyMethod_Fini();
479 PyFrame_Fini();
480 PyCFunction_Fini();
481 PyTuple_Fini();
Raymond Hettingerfb09f0e2004-10-07 03:58:07 +0000482 PyList_Fini();
Raymond Hettingerd7946662005-08-01 21:39:29 +0000483 PySet_Fini();
Christian Heimes72b710a2008-05-26 13:28:38 +0000484 PyBytes_Fini();
Christian Heimes9c4756e2008-05-26 13:22:05 +0000485 PyByteArray_Fini();
Guido van Rossumddefaf32007-01-14 03:31:43 +0000486 PyLong_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000487 PyFloat_Fini();
Christian Heimes77c02eb2008-02-09 02:18:51 +0000488 PyDict_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000489
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000490 /* Cleanup Unicode implementation */
491 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000492
Christian Heimesc8967002007-11-30 10:18:26 +0000493 /* reset file system default encoding */
494 if (!Py_HasFileSystemDefaultEncoding) {
495 free((char*)Py_FileSystemDefaultEncoding);
Trent Nelson39e307e2008-03-19 06:45:48 +0000496 Py_FileSystemDefaultEncoding = NULL;
Christian Heimesc8967002007-11-30 10:18:26 +0000497 }
498
Guido van Rossumcc283f51997-08-05 02:22:03 +0000499 /* XXX Still allocated:
500 - various static ad-hoc pointers to interned strings
501 - int and float free list blocks
502 - whatever various modules and libraries allocate
503 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000504
505 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000506
Tim Peters269b2a62003-04-17 19:52:29 +0000507#ifdef Py_TRACE_REFS
508 /* Display addresses (& refcnts) of all objects still alive.
509 * An address can be used to find the repr of the object, printed
510 * above by _Py_PrintReferences.
511 */
512 if (Py_GETENV("PYTHONDUMPREFS"))
513 _Py_PrintReferenceAddresses(stderr);
514#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000515#ifdef PYMALLOC_DEBUG
516 if (Py_GETENV("PYTHONMALLOCSTATS"))
517 _PyObject_DebugMallocStats();
518#endif
519
Guido van Rossumcc283f51997-08-05 02:22:03 +0000520 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000521}
522
523/* Create and initialize a new interpreter and thread, and return the
524 new thread. This requires that Py_Initialize() has been called
525 first.
526
527 Unsuccessful initialization yields a NULL pointer. Note that *no*
528 exception information is available even in this case -- the
529 exception information is held in the thread, and there is no
530 thread.
531
532 Locking: as above.
533
534*/
535
536PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000537Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000538{
539 PyInterpreterState *interp;
540 PyThreadState *tstate, *save_tstate;
541 PyObject *bimod, *sysmod;
542
543 if (!initialized)
544 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
545
546 interp = PyInterpreterState_New();
547 if (interp == NULL)
548 return NULL;
549
550 tstate = PyThreadState_New(interp);
551 if (tstate == NULL) {
552 PyInterpreterState_Delete(interp);
553 return NULL;
554 }
555
556 save_tstate = PyThreadState_Swap(tstate);
557
558 /* XXX The following is lax in error checking */
559
560 interp->modules = PyDict_New();
Guido van Rossumd8faa362007-04-27 19:54:29 +0000561 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562
Georg Brandl1a3284e2007-12-02 09:40:06 +0000563 bimod = _PyImport_FindExtension("builtins", "builtins");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564 if (bimod != NULL) {
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000565 interp->builtins = PyModule_GetDict(bimod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000566 if (interp->builtins == NULL)
567 goto handle_error;
Guido van Rossum4a1f39a1997-11-04 19:36:18 +0000568 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000569 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000570
571 /* initialize builtin exceptions */
572 _PyExc_Init();
573
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574 sysmod = _PyImport_FindExtension("sys", "sys");
575 if (bimod != NULL && sysmod != NULL) {
Christian Heimes6a27efa2008-10-30 21:48:26 +0000576 PyObject *pstderr;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000577 interp->sysdict = PyModule_GetDict(sysmod);
Thomas Wouters89f507f2006-12-13 04:49:30 +0000578 if (interp->sysdict == NULL)
579 goto handle_error;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000580 Py_INCREF(interp->sysdict);
581 PySys_SetPath(Py_GetPath());
582 PyDict_SetItemString(interp->sysdict, "modules",
583 interp->modules);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000584 /* Set up a preliminary stderr printer until we have enough
585 infrastructure for the io module in place. */
586 pstderr = PyFile_NewStdPrinter(fileno(stderr));
587 if (pstderr == NULL)
588 Py_FatalError("Py_Initialize: can't set preliminary stderr");
589 PySys_SetObject("stderr", pstderr);
590 PySys_SetObject("__stderr__", pstderr);
591
Martin v. Löwisd7ceb222003-01-22 09:00:38 +0000592 _PyImportHooks_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000593 if (initstdio() < 0)
594 Py_FatalError(
595 "Py_Initialize: can't initialize sys standard streams");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000596 initmain();
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000597 if (!Py_NoSiteFlag)
598 initsite();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000599 }
600
601 if (!PyErr_Occurred())
602 return tstate;
603
Thomas Wouters89f507f2006-12-13 04:49:30 +0000604handle_error:
Guido van Rossum25ce5661997-08-02 03:10:38 +0000605 /* Oops, it didn't work. Undo it all. */
606
607 PyErr_Print();
608 PyThreadState_Clear(tstate);
609 PyThreadState_Swap(save_tstate);
610 PyThreadState_Delete(tstate);
611 PyInterpreterState_Delete(interp);
612
613 return NULL;
614}
615
616/* Delete an interpreter and its last thread. This requires that the
617 given thread state is current, that the thread has no remaining
618 frames, and that it is its interpreter's only remaining thread.
619 It is a fatal error to violate these constraints.
620
621 (Py_Finalize() doesn't have these constraints -- it zaps
622 everything, regardless.)
623
624 Locking: as above.
625
626*/
627
628void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000629Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000630{
631 PyInterpreterState *interp = tstate->interp;
632
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000633 if (tstate != PyThreadState_GET())
Guido van Rossum25ce5661997-08-02 03:10:38 +0000634 Py_FatalError("Py_EndInterpreter: thread is not current");
635 if (tstate->frame != NULL)
636 Py_FatalError("Py_EndInterpreter: thread still has a frame");
637 if (tstate != interp->tstate_head || tstate->next != NULL)
638 Py_FatalError("Py_EndInterpreter: not the last thread");
639
640 PyImport_Cleanup();
641 PyInterpreterState_Clear(interp);
642 PyThreadState_Swap(NULL);
643 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000644}
645
Martin v. Löwis790465f2008-04-05 20:41:37 +0000646static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000647
648void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000649Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000650{
651 if (pn && *pn)
652 progname = pn;
653}
654
Martin v. Löwis790465f2008-04-05 20:41:37 +0000655wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000656Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000657{
658 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000659}
660
Martin v. Löwis790465f2008-04-05 20:41:37 +0000661static wchar_t *default_home = NULL;
662static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000663
664void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000665Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000666{
667 default_home = home;
668}
669
Martin v. Löwis790465f2008-04-05 20:41:37 +0000670wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000671Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000672{
Martin v. Löwis790465f2008-04-05 20:41:37 +0000673 wchar_t *home = default_home;
674 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
675 char* chome = Py_GETENV("PYTHONHOME");
676 if (chome) {
677 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
678 if (r != (size_t)-1 && r <= PATH_MAX)
679 home = env_home;
680 }
681
682 }
Guido van Rossuma61691e1998-02-06 22:27:24 +0000683 return home;
684}
685
Guido van Rossum6135a871995-01-09 17:53:26 +0000686/* Create __main__ module */
687
688static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000689initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000690{
Guido van Rossum82598051997-03-05 00:20:32 +0000691 PyObject *m, *d;
692 m = PyImport_AddModule("__main__");
Guido van Rossum6135a871995-01-09 17:53:26 +0000693 if (m == NULL)
Guido van Rossum82598051997-03-05 00:20:32 +0000694 Py_FatalError("can't create __main__ module");
695 d = PyModule_GetDict(m);
696 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
Georg Brandl1a3284e2007-12-02 09:40:06 +0000697 PyObject *bimod = PyImport_ImportModule("builtins");
Guido van Rossum858cb731997-11-19 16:15:37 +0000698 if (bimod == NULL ||
699 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
Guido van Rossum82598051997-03-05 00:20:32 +0000700 Py_FatalError("can't add __builtins__ to __main__");
Barry Warsaw3d05b1a1999-01-29 21:30:22 +0000701 Py_DECREF(bimod);
Guido van Rossum6135a871995-01-09 17:53:26 +0000702 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000703}
704
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000705/* Import the site module (not into __main__ though) */
706
707static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000708initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000709{
710 PyObject *m, *f;
711 m = PyImport_ImportModule("site");
712 if (m == NULL) {
713 f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +0000714 if (f == NULL || f == Py_None)
715 return;
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000716 if (Py_VerboseFlag) {
717 PyFile_WriteString(
718 "'import site' failed; traceback:\n", f);
719 PyErr_Print();
720 }
721 else {
722 PyFile_WriteString(
723 "'import site' failed; use -v for traceback\n", f);
724 PyErr_Clear();
725 }
726 }
727 else {
728 Py_DECREF(m);
729 }
730}
731
Antoine Pitrou05608432009-01-09 18:53:14 +0000732static PyObject*
733create_stdio(PyObject* io,
734 int fd, int write_mode, char* name,
735 char* encoding, char* errors)
736{
Antoine Pitrou91696412009-01-09 22:12:30 +0000737 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
Antoine Pitrou05608432009-01-09 18:53:14 +0000738 const char* mode;
Antoine Pitrou91696412009-01-09 22:12:30 +0000739 PyObject *line_buffering;
740 int buffering, isatty;
Antoine Pitrou05608432009-01-09 18:53:14 +0000741
Antoine Pitrou27fe9fc2009-01-26 21:48:00 +0000742 /* stdin is always opened in buffered mode, first because it shouldn't
743 make a difference in common use cases, second because TextIOWrapper
744 depends on the presence of a read1() method which only exists on
745 buffered streams.
746 */
747 if (Py_UnbufferedStdioFlag && write_mode)
Antoine Pitrou05608432009-01-09 18:53:14 +0000748 buffering = 0;
749 else
750 buffering = -1;
751 if (write_mode)
752 mode = "wb";
753 else
754 mode = "rb";
755 buf = PyObject_CallMethod(io, "open", "isiOOOi",
756 fd, mode, buffering,
757 Py_None, Py_None, Py_None, 0);
758 if (buf == NULL)
759 goto error;
760
Antoine Pitrou27fe9fc2009-01-26 21:48:00 +0000761 if (buffering) {
Antoine Pitrou05608432009-01-09 18:53:14 +0000762 raw = PyObject_GetAttrString(buf, "raw");
763 if (raw == NULL)
764 goto error;
765 }
766 else {
767 raw = buf;
768 Py_INCREF(raw);
769 }
770
771 text = PyUnicode_FromString(name);
772 if (text == NULL || PyObject_SetAttrString(raw, "_name", text) < 0)
773 goto error;
Antoine Pitrou91696412009-01-09 22:12:30 +0000774 res = PyObject_CallMethod(raw, "isatty", "");
775 if (res == NULL)
776 goto error;
777 isatty = PyObject_IsTrue(res);
778 Py_DECREF(res);
779 if (isatty == -1)
780 goto error;
781 if (isatty || Py_UnbufferedStdioFlag)
Antoine Pitrou05608432009-01-09 18:53:14 +0000782 line_buffering = Py_True;
783 else
784 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000785
786 Py_CLEAR(raw);
787 Py_CLEAR(text);
788
Antoine Pitrou05608432009-01-09 18:53:14 +0000789 stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
790 buf, encoding, errors,
791 "\n", line_buffering);
792 Py_CLEAR(buf);
793 if (stream == NULL)
794 goto error;
795
796 if (write_mode)
797 mode = "w";
798 else
799 mode = "r";
800 text = PyUnicode_FromString(mode);
801 if (!text || PyObject_SetAttrString(stream, "mode", text) < 0)
802 goto error;
803 Py_CLEAR(text);
804 return stream;
805
806error:
807 Py_XDECREF(buf);
808 Py_XDECREF(stream);
809 Py_XDECREF(text);
810 Py_XDECREF(raw);
811 return NULL;
812}
813
Georg Brandl1a3284e2007-12-02 09:40:06 +0000814/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000815static int
816initstdio(void)
817{
818 PyObject *iomod = NULL, *wrapper;
819 PyObject *bimod = NULL;
820 PyObject *m;
821 PyObject *std = NULL;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000822 int status = 0, fd;
Trent Nelson39e307e2008-03-19 06:45:48 +0000823 PyObject * encoding_attr;
Amaury Forgeot d'Arcf1ca0b12008-06-11 17:40:47 +0000824 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000825
826 /* Hack to avoid a nasty recursion issue when Python is invoked
827 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
828 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
829 goto error;
830 }
831 Py_DECREF(m);
832
833 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
834 goto error;
835 }
836 Py_DECREF(m);
837
Georg Brandl1a3284e2007-12-02 09:40:06 +0000838 if (!(bimod = PyImport_ImportModule("builtins"))) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000839 goto error;
840 }
841
842 if (!(iomod = PyImport_ImportModule("io"))) {
843 goto error;
844 }
845 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
846 goto error;
847 }
848
Georg Brandl1a3284e2007-12-02 09:40:06 +0000849 /* Set builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000850 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
851 goto error;
852 }
853
Martin v. Löwis0f599892008-06-02 11:13:03 +0000854 encoding = Py_GETENV("PYTHONIOENCODING");
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000855 errors = NULL;
Martin v. Löwis0f599892008-06-02 11:13:03 +0000856 if (encoding) {
857 encoding = strdup(encoding);
858 errors = strchr(encoding, ':');
859 if (errors) {
860 *errors = '\0';
861 errors++;
862 }
863 }
864
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000865 /* Set sys.stdin */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000866 fd = fileno(stdin);
867 /* Under some conditions stdin, stdout and stderr may not be connected
868 * and fileno() may point to an invalid file descriptor. For example
869 * GUI apps don't have valid standard streams by default.
870 */
871 if (fd < 0) {
872#ifdef MS_WINDOWS
873 std = Py_None;
874 Py_INCREF(std);
875#else
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000876 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000877#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000878 }
Christian Heimes58cb1b82007-11-13 02:19:40 +0000879 else {
Antoine Pitrou05608432009-01-09 18:53:14 +0000880 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
881 if (std == NULL)
Christian Heimes58cb1b82007-11-13 02:19:40 +0000882 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000883 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000884 PySys_SetObject("__stdin__", std);
885 PySys_SetObject("stdin", std);
886 Py_DECREF(std);
887
888 /* Set sys.stdout */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000889 fd = fileno(stdout);
890 if (fd < 0) {
891#ifdef MS_WINDOWS
892 std = Py_None;
893 Py_INCREF(std);
894#else
895 goto error;
896#endif
897 }
898 else {
Antoine Pitrou05608432009-01-09 18:53:14 +0000899 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
900 if (std == NULL)
Christian Heimes58cb1b82007-11-13 02:19:40 +0000901 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000902 } /* if (fd < 0) */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000903 PySys_SetObject("__stdout__", std);
904 PySys_SetObject("stdout", std);
905 Py_DECREF(std);
906
Guido van Rossum98297ee2007-11-06 21:34:58 +0000907#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Guido van Rossum2dced8b2007-10-30 17:27:30 +0000908 /* Set sys.stderr, replaces the preliminary stderr */
Christian Heimes58cb1b82007-11-13 02:19:40 +0000909 fd = fileno(stderr);
910 if (fd < 0) {
911#ifdef MS_WINDOWS
912 std = Py_None;
913 Py_INCREF(std);
914#else
915 goto error;
916#endif
917 }
918 else {
Antoine Pitrou05608432009-01-09 18:53:14 +0000919 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
920 if (std == NULL)
Christian Heimes58cb1b82007-11-13 02:19:40 +0000921 goto error;
Christian Heimes58cb1b82007-11-13 02:19:40 +0000922 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +0000923
924 /* Same as hack above, pre-import stderr's codec to avoid recursion
925 when import.c tries to write to stderr in verbose mode. */
926 encoding_attr = PyObject_GetAttrString(std, "encoding");
927 if (encoding_attr != NULL) {
928 const char * encoding;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +0000929 encoding = _PyUnicode_AsString(encoding_attr);
Trent Nelson39e307e2008-03-19 06:45:48 +0000930 if (encoding != NULL) {
931 _PyCodec_Lookup(encoding);
932 }
933 }
934 PyErr_Clear(); /* Not a fatal error if codec isn't available */
935
Christian Heimesdb233082007-11-13 02:34:21 +0000936 PySys_SetObject("__stderr__", std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000937 PySys_SetObject("stderr", std);
938 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +0000939#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000940
Christian Heimes58cb1b82007-11-13 02:19:40 +0000941 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000942 error:
Christian Heimesdb233082007-11-13 02:34:21 +0000943 status = -1;
944 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000945
Martin v. Löwis7cd068b2008-06-02 12:33:47 +0000946 if (encoding)
947 free(encoding);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000948 Py_XDECREF(bimod);
949 Py_XDECREF(iomod);
950 return status;
951}
952
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000953/* Parse input from a file and execute it */
954
955int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000956PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000957 PyCompilerFlags *flags)
958{
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000959 if (filename == NULL)
960 filename = "???";
Guido van Rossum0df002c2000-08-27 19:21:52 +0000961 if (Py_FdIsInteractive(fp, filename)) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000962 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
Guido van Rossum0df002c2000-08-27 19:21:52 +0000963 if (closeit)
964 fclose(fp);
965 return err;
966 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000967 else
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000968 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000969}
970
971int
Martin v. Löwis95292d62002-12-11 14:04:59 +0000972PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000973{
Guido van Rossum82598051997-03-05 00:20:32 +0000974 PyObject *v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000975 int ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000976 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +0000977
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000978 if (flags == NULL) {
979 flags = &local_flags;
Tim Peters5ba58662001-07-16 02:29:45 +0000980 local_flags.cf_flags = 0;
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000981 }
Guido van Rossum82598051997-03-05 00:20:32 +0000982 v = PySys_GetObject("ps1");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000983 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000984 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
Guido van Rossum82598051997-03-05 00:20:32 +0000985 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000986 }
Guido van Rossum82598051997-03-05 00:20:32 +0000987 v = PySys_GetObject("ps2");
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000988 if (v == NULL) {
Neal Norwitza369c5a2007-08-25 07:41:59 +0000989 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
Guido van Rossum82598051997-03-05 00:20:32 +0000990 Py_XDECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000991 }
992 for (;;) {
Jeremy Hyltonbc320242001-03-22 02:47:58 +0000993 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000994 PRINT_TOTAL_REFS();
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000995 if (ret == E_EOF)
996 return 0;
997 /*
998 if (ret == E_NOMEM)
999 return -1;
1000 */
1001 }
1002}
1003
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001004/* compute parser flags based on compiler flags */
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001005#define PARSER_FLAGS(flags) \
Thomas Wouters34aa7ba2006-02-28 19:02:24 +00001006 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
Guido van Rossum45aecf42006-03-15 04:58:47 +00001007 PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001008
Thomas Wouters89f507f2006-12-13 04:49:30 +00001009#if 0
1010/* Keep an example of flags with future keyword support. */
1011#define PARSER_FLAGS(flags) \
1012 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1013 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1014 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1015 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
1016#endif
1017
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001018int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001019PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001020{
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001021 PyObject *m, *d, *v, *w, *oenc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001022 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001023 PyArena *arena;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001024 char *ps1 = "", *ps2 = "", *enc = NULL;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001025 int errcode = 0;
Tim Petersfe2127d2001-07-16 05:37:24 +00001026
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001027 if (fp == stdin) {
1028 /* Fetch encoding from sys.stdin */
1029 v = PySys_GetObject("stdin");
Christian Heimes2be03732007-11-15 02:26:46 +00001030 if (v == NULL || v == Py_None)
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001031 return -1;
1032 oenc = PyObject_GetAttrString(v, "encoding");
1033 if (!oenc)
1034 return -1;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001035 enc = _PyUnicode_AsString(oenc);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001036 }
Guido van Rossum82598051997-03-05 00:20:32 +00001037 v = PySys_GetObject("ps1");
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001038 if (v != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001039 v = PyObject_Str(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001040 if (v == NULL)
1041 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +00001042 else if (PyUnicode_Check(v))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001043 ps1 = _PyUnicode_AsString(v);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001044 }
Guido van Rossum82598051997-03-05 00:20:32 +00001045 w = PySys_GetObject("ps2");
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001046 if (w != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001047 w = PyObject_Str(w);
Guido van Rossumddc3fb51997-11-25 20:58:13 +00001048 if (w == NULL)
1049 PyErr_Clear();
Guido van Rossumc5724de2007-10-10 21:38:59 +00001050 else if (PyUnicode_Check(w))
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001051 ps2 = _PyUnicode_AsString(w);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001052 }
Neal Norwitz9589ee22006-03-04 19:01:22 +00001053 arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001054 if (arena == NULL) {
1055 Py_XDECREF(v);
1056 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001057 Py_XDECREF(oenc);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001058 return -1;
1059 }
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001060 mod = PyParser_ASTFromFile(fp, filename, enc,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001061 Py_single_input, ps1, ps2,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001062 flags, &errcode, arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001063 Py_XDECREF(v);
1064 Py_XDECREF(w);
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001065 Py_XDECREF(oenc);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001066 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001067 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001068 if (errcode == E_EOF) {
1069 PyErr_Clear();
Guido van Rossuma110aa61994-08-29 12:50:44 +00001070 return E_EOF;
1071 }
Guido van Rossum82598051997-03-05 00:20:32 +00001072 PyErr_Print();
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001073 return -1;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001074 }
Guido van Rossum82598051997-03-05 00:20:32 +00001075 m = PyImport_AddModule("__main__");
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001076 if (m == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001077 PyArena_Free(arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001078 return -1;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001079 }
Guido van Rossum82598051997-03-05 00:20:32 +00001080 d = PyModule_GetDict(m);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001081 v = run_mod(mod, filename, d, d, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001082 PyArena_Free(arena);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001083 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001084 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001085 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001086 return -1;
1087 }
Guido van Rossum82598051997-03-05 00:20:32 +00001088 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001089 return 0;
1090}
1091
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001092/* Check whether a file maybe a pyc file: Look at the extension,
1093 the file type, and, if we may close it, at the first few bytes. */
1094
1095static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001096maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001097{
1098 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1099 return 1;
1100
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001101 /* Only look into the file if we are allowed to close it, since
1102 it then should also be seekable. */
1103 if (closeit) {
1104 /* Read only two bytes of the magic. If the file was opened in
1105 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1106 be read as they are on disk. */
1107 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1108 unsigned char buf[2];
Tim Peters3e876562001-02-11 04:35:39 +00001109 /* Mess: In case of -x, the stream is NOT at its start now,
1110 and ungetc() was used to push back the first newline,
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001111 which makes the current stream position formally undefined,
1112 and a x-platform nightmare.
1113 Unfortunately, we have no direct way to know whether -x
1114 was specified. So we use a terrible hack: if the current
1115 stream position is not 0, we assume -x was specified, and
1116 give up. Bug 132850 on SourceForge spells out the
1117 hopelessness of trying anything else (fseek and ftell
1118 don't work predictably x-platform for text-mode files).
Tim Peters3e876562001-02-11 04:35:39 +00001119 */
Tim Peters3e876562001-02-11 04:35:39 +00001120 int ispyc = 0;
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001121 if (ftell(fp) == 0) {
1122 if (fread(buf, 1, 2, fp) == 2 &&
Tim Petersd08e3822003-04-17 15:24:21 +00001123 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
Tim Peters6f5a4ef2001-02-17 22:02:34 +00001124 ispyc = 1;
1125 rewind(fp);
1126 }
Tim Peters3e876562001-02-11 04:35:39 +00001127 return ispyc;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001128 }
1129 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001130}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001131
Guido van Rossum0df002c2000-08-27 19:21:52 +00001132int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001133PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001134 PyCompilerFlags *flags)
1135{
Guido van Rossum82598051997-03-05 00:20:32 +00001136 PyObject *m, *d, *v;
Martin v. Löwis95292d62002-12-11 14:04:59 +00001137 const char *ext;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001138 int set_file_name = 0, ret;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001139
Guido van Rossum82598051997-03-05 00:20:32 +00001140 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001141 if (m == NULL)
1142 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001143 d = PyModule_GetDict(m);
Fred Drake8ed02042002-10-17 21:24:58 +00001144 if (PyDict_GetItemString(d, "__file__") == NULL) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +00001145 PyObject *f;
1146 f = PyUnicode_DecodeFSDefault(filename);
Fred Drake8ed02042002-10-17 21:24:58 +00001147 if (f == NULL)
1148 return -1;
1149 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1150 Py_DECREF(f);
1151 return -1;
1152 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00001153 set_file_name = 1;
Fred Drake8ed02042002-10-17 21:24:58 +00001154 Py_DECREF(f);
1155 }
Guido van Rossumfdef2711994-09-14 13:31:04 +00001156 ext = filename + strlen(filename) - 4;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001157 if (maybe_pyc_file(fp, filename, ext, closeit)) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001158 /* Try to run a pyc file. First, re-open in binary */
Guido van Rossum0df002c2000-08-27 19:21:52 +00001159 if (closeit)
1160 fclose(fp);
Fred Drake8ed02042002-10-17 21:24:58 +00001161 if ((fp = fopen(filename, "rb")) == NULL) {
Guido van Rossumfdef2711994-09-14 13:31:04 +00001162 fprintf(stderr, "python: Can't reopen .pyc file\n");
Guido van Rossumd8faa362007-04-27 19:54:29 +00001163 ret = -1;
1164 goto done;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001165 }
Guido van Rossum2a7f58d1997-04-02 05:28:38 +00001166 /* Turn on optimization if a .pyo file is given */
1167 if (strcmp(ext, ".pyo") == 0)
1168 Py_OptimizeFlag = 1;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001169 v = run_pyc_file(fp, filename, d, d, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001170 } else {
Tim Petersd08e3822003-04-17 15:24:21 +00001171 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001172 closeit, flags);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001173 }
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +00001174 flush_io();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001175 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001176 PyErr_Print();
Guido van Rossumd8faa362007-04-27 19:54:29 +00001177 ret = -1;
1178 goto done;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001179 }
Guido van Rossum82598051997-03-05 00:20:32 +00001180 Py_DECREF(v);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001181 ret = 0;
1182 done:
1183 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1184 PyErr_Clear();
1185 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001186}
1187
1188int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001189PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001190{
Guido van Rossum82598051997-03-05 00:20:32 +00001191 PyObject *m, *d, *v;
1192 m = PyImport_AddModule("__main__");
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001193 if (m == NULL)
1194 return -1;
Guido van Rossum82598051997-03-05 00:20:32 +00001195 d = PyModule_GetDict(m);
Guido van Rossum393661d2001-08-31 17:40:15 +00001196 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001197 if (v == NULL) {
Guido van Rossum82598051997-03-05 00:20:32 +00001198 PyErr_Print();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001199 return -1;
1200 }
Guido van Rossum82598051997-03-05 00:20:32 +00001201 Py_DECREF(v);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001202 return 0;
1203}
1204
Barry Warsaw035574d1997-08-29 22:07:17 +00001205static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001206parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
1207 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001208{
1209 long hold;
1210 PyObject *v;
1211
1212 /* old style errors */
1213 if (PyTuple_Check(err))
Neal Norwitz78293352002-04-01 01:41:20 +00001214 return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001215 lineno, offset, text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001216
1217 /* new style errors. `err' is an instance */
1218
1219 if (! (v = PyObject_GetAttrString(err, "msg")))
1220 goto finally;
1221 *message = v;
1222
1223 if (!(v = PyObject_GetAttrString(err, "filename")))
1224 goto finally;
1225 if (v == Py_None)
1226 *filename = NULL;
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001227 else if (! (*filename = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001228 goto finally;
1229
1230 Py_DECREF(v);
1231 if (!(v = PyObject_GetAttrString(err, "lineno")))
1232 goto finally;
Christian Heimes217cfd12007-12-02 14:31:20 +00001233 hold = PyLong_AsLong(v);
Barry Warsaw035574d1997-08-29 22:07:17 +00001234 Py_DECREF(v);
1235 v = NULL;
1236 if (hold < 0 && PyErr_Occurred())
1237 goto finally;
1238 *lineno = (int)hold;
1239
1240 if (!(v = PyObject_GetAttrString(err, "offset")))
1241 goto finally;
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001242 if (v == Py_None) {
1243 *offset = -1;
1244 Py_DECREF(v);
1245 v = NULL;
1246 } else {
Christian Heimes217cfd12007-12-02 14:31:20 +00001247 hold = PyLong_AsLong(v);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001248 Py_DECREF(v);
1249 v = NULL;
1250 if (hold < 0 && PyErr_Occurred())
1251 goto finally;
1252 *offset = (int)hold;
1253 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001254
1255 if (!(v = PyObject_GetAttrString(err, "text")))
1256 goto finally;
1257 if (v == Py_None)
1258 *text = NULL;
Guido van Rossumc5724de2007-10-10 21:38:59 +00001259 else if (!PyUnicode_Check(v) ||
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001260 !(*text = _PyUnicode_AsString(v)))
Barry Warsaw035574d1997-08-29 22:07:17 +00001261 goto finally;
1262 Py_DECREF(v);
1263 return 1;
1264
1265finally:
1266 Py_XDECREF(v);
1267 return 0;
1268}
1269
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001270void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001271PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001272{
Guido van Rossuma61691e1998-02-06 22:27:24 +00001273 PyErr_PrintEx(1);
1274}
1275
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001276static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001277print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001278{
1279 char *nl;
1280 if (offset >= 0) {
1281 if (offset > 0 && offset == (int)strlen(text))
1282 offset--;
1283 for (;;) {
1284 nl = strchr(text, '\n');
1285 if (nl == NULL || nl-text >= offset)
1286 break;
Martin v. Löwis18e16552006-02-15 17:27:45 +00001287 offset -= (int)(nl+1-text);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001288 text = nl+1;
1289 }
1290 while (*text == ' ' || *text == '\t') {
1291 text++;
1292 offset--;
1293 }
1294 }
1295 PyFile_WriteString(" ", f);
1296 PyFile_WriteString(text, f);
1297 if (*text == '\0' || text[strlen(text)-1] != '\n')
1298 PyFile_WriteString("\n", f);
1299 if (offset == -1)
1300 return;
1301 PyFile_WriteString(" ", f);
1302 offset--;
1303 while (offset > 0) {
1304 PyFile_WriteString(" ", f);
1305 offset--;
1306 }
1307 PyFile_WriteString("^\n", f);
1308}
1309
Guido van Rossum66e8e862001-03-23 17:54:43 +00001310static void
1311handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001312{
Neal Norwitz9589ee22006-03-04 19:01:22 +00001313 PyObject *exception, *value, *tb;
1314 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001315
Guido van Rossumd8faa362007-04-27 19:54:29 +00001316 if (Py_InspectFlag)
1317 /* Don't exit if -i flag was given. This flag is set to 0
1318 * when entering interactive mode for inspecting. */
1319 return;
1320
Guido van Rossum66e8e862001-03-23 17:54:43 +00001321 PyErr_Fetch(&exception, &value, &tb);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001322 fflush(stdout);
1323 if (value == NULL || value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001324 goto done;
Brett Cannonbf364092006-03-01 04:25:17 +00001325 if (PyExceptionInstance_Check(value)) {
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001326 /* The error code should be in the `code' attribute. */
1327 PyObject *code = PyObject_GetAttrString(value, "code");
1328 if (code) {
1329 Py_DECREF(value);
1330 value = code;
1331 if (value == Py_None)
Tim Peterscf615b52003-04-19 18:47:02 +00001332 goto done;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001333 }
1334 /* If we failed to dig out the 'code' attribute,
1335 just let the else clause below print the error. */
1336 }
Christian Heimes217cfd12007-12-02 14:31:20 +00001337 if (PyLong_Check(value))
1338 exitcode = (int)PyLong_AsLong(value);
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001339 else {
1340 PyObject_Print(value, stderr, Py_PRINT_RAW);
1341 PySys_WriteStderr("\n");
Tim Peterscf615b52003-04-19 18:47:02 +00001342 exitcode = 1;
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001343 }
Tim Peterscf615b52003-04-19 18:47:02 +00001344 done:
Neal Norwitz9589ee22006-03-04 19:01:22 +00001345 /* Restore and clear the exception info, in order to properly decref
1346 * the exception, value, and traceback. If we just exit instead,
1347 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1348 * some finalizers from running.
1349 */
Tim Peterscf615b52003-04-19 18:47:02 +00001350 PyErr_Restore(exception, value, tb);
1351 PyErr_Clear();
1352 Py_Exit(exitcode);
1353 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001354}
1355
1356void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001357PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001358{
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001359 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001360
1361 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1362 handle_system_exit();
1363 }
Guido van Rossum82598051997-03-05 00:20:32 +00001364 PyErr_Fetch(&exception, &v, &tb);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001365 if (exception == NULL)
1366 return;
Barry Warsaw035574d1997-08-29 22:07:17 +00001367 PyErr_NormalizeException(&exception, &v, &tb);
Antoine Pitroue2dffc02008-08-26 22:02:58 +00001368 if (tb == NULL) {
1369 tb = Py_None;
1370 Py_INCREF(tb);
1371 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001372 PyException_SetTraceback(v, tb);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001373 if (exception == NULL)
Guido van Rossum296b4751997-05-23 00:19:20 +00001374 return;
Georg Brandl86b2fb92008-07-16 03:43:04 +00001375 /* Now we know v != NULL too */
Guido van Rossuma61691e1998-02-06 22:27:24 +00001376 if (set_sys_last_vars) {
1377 PySys_SetObject("last_type", exception);
1378 PySys_SetObject("last_value", v);
Benjamin Petersone6528212008-07-15 15:32:09 +00001379 PySys_SetObject("last_traceback", tb);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001380 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001381 hook = PySys_GetObject("excepthook");
1382 if (hook) {
Benjamin Petersone6528212008-07-15 15:32:09 +00001383 PyObject *args = PyTuple_Pack(3, exception, v, tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001384 PyObject *result = PyEval_CallObject(hook, args);
1385 if (result == NULL) {
1386 PyObject *exception2, *v2, *tb2;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001387 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1388 handle_system_exit();
1389 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001390 PyErr_Fetch(&exception2, &v2, &tb2);
1391 PyErr_NormalizeException(&exception2, &v2, &tb2);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001392 /* It should not be possible for exception2 or v2
1393 to be NULL. However PyErr_Display() can't
1394 tolerate NULLs, so just be safe. */
1395 if (exception2 == NULL) {
1396 exception2 = Py_None;
1397 Py_INCREF(exception2);
1398 }
1399 if (v2 == NULL) {
1400 v2 = Py_None;
1401 Py_INCREF(v2);
1402 }
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001403 fflush(stdout);
1404 PySys_WriteStderr("Error in sys.excepthook:\n");
1405 PyErr_Display(exception2, v2, tb2);
1406 PySys_WriteStderr("\nOriginal exception was:\n");
1407 PyErr_Display(exception, v, tb);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001408 Py_DECREF(exception2);
1409 Py_DECREF(v2);
Jeremy Hylton07028582001-12-07 15:35:35 +00001410 Py_XDECREF(tb2);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001411 }
1412 Py_XDECREF(result);
1413 Py_XDECREF(args);
1414 } else {
1415 PySys_WriteStderr("sys.excepthook is missing\n");
1416 PyErr_Display(exception, v, tb);
1417 }
1418 Py_XDECREF(exception);
1419 Py_XDECREF(v);
1420 Py_XDECREF(tb);
1421}
1422
Benjamin Petersone6528212008-07-15 15:32:09 +00001423static void
1424print_exception(PyObject *f, PyObject *value)
1425{
1426 int err = 0;
1427 PyObject *type, *tb;
1428
Benjamin Peterson26582602008-08-23 20:08:07 +00001429 if (!PyExceptionInstance_Check(value)) {
1430 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1431 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1432 PyFile_WriteString(" found\n", f);
1433 return;
1434 }
1435
Benjamin Petersone6528212008-07-15 15:32:09 +00001436 Py_INCREF(value);
1437 fflush(stdout);
1438 type = (PyObject *) Py_TYPE(value);
1439 tb = PyException_GetTraceback(value);
1440 if (tb && tb != Py_None)
1441 err = PyTraceBack_Print(tb, f);
1442 if (err == 0 &&
1443 PyObject_HasAttrString(value, "print_file_and_line"))
1444 {
1445 PyObject *message;
1446 const char *filename, *text;
1447 int lineno, offset;
1448 if (!parse_syntax_error(value, &message, &filename,
1449 &lineno, &offset, &text))
1450 PyErr_Clear();
1451 else {
1452 char buf[10];
1453 PyFile_WriteString(" File \"", f);
1454 if (filename == NULL)
1455 PyFile_WriteString("<string>", f);
1456 else
1457 PyFile_WriteString(filename, f);
1458 PyFile_WriteString("\", line ", f);
1459 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1460 PyFile_WriteString(buf, f);
1461 PyFile_WriteString("\n", f);
1462 if (text != NULL)
1463 print_error_text(f, offset, text);
1464 Py_DECREF(value);
1465 value = message;
1466 /* Can't be bothered to check all those
1467 PyFile_WriteString() calls */
1468 if (PyErr_Occurred())
1469 err = -1;
1470 }
1471 }
1472 if (err) {
1473 /* Don't do anything else */
1474 }
1475 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001476 PyObject* moduleName;
Thomas Hellerd88ddfa2008-07-15 17:14:51 +00001477 char* className;
1478 assert(PyExceptionClass_Check(type));
1479 className = PyExceptionClass_Name(type);
Benjamin Petersone6528212008-07-15 15:32:09 +00001480 if (className != NULL) {
1481 char *dot = strrchr(className, '.');
1482 if (dot != NULL)
1483 className = dot+1;
1484 }
1485
1486 moduleName = PyObject_GetAttrString(type, "__module__");
1487 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1488 {
1489 Py_DECREF(moduleName);
1490 err = PyFile_WriteString("<unknown>", f);
1491 }
1492 else {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001493 char* modstr = _PyUnicode_AsString(moduleName);
Benjamin Petersone6528212008-07-15 15:32:09 +00001494 if (modstr && strcmp(modstr, "builtins"))
1495 {
1496 err = PyFile_WriteString(modstr, f);
1497 err += PyFile_WriteString(".", f);
1498 }
1499 Py_DECREF(moduleName);
1500 }
1501 if (err == 0) {
1502 if (className == NULL)
1503 err = PyFile_WriteString("<unknown>", f);
1504 else
1505 err = PyFile_WriteString(className, f);
1506 }
1507 }
1508 if (err == 0 && (value != Py_None)) {
1509 PyObject *s = PyObject_Str(value);
1510 /* only print colon if the str() of the
1511 object is not the empty string
1512 */
1513 if (s == NULL)
1514 err = -1;
1515 else if (!PyUnicode_Check(s) ||
1516 PyUnicode_GetSize(s) != 0)
1517 err = PyFile_WriteString(": ", f);
1518 if (err == 0)
1519 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1520 Py_XDECREF(s);
1521 }
1522 /* try to write a newline in any case */
1523 err += PyFile_WriteString("\n", f);
1524 Py_XDECREF(tb);
1525 Py_DECREF(value);
1526 /* If an error happened here, don't show it.
1527 XXX This is wrong, but too many callers rely on this behavior. */
1528 if (err != 0)
1529 PyErr_Clear();
1530}
1531
1532static const char *cause_message =
1533 "\nThe above exception was the direct cause "
1534 "of the following exception:\n\n";
1535
1536static const char *context_message =
1537 "\nDuring handling of the above exception, "
1538 "another exception occurred:\n\n";
1539
1540static void
1541print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1542{
1543 int err = 0, res;
1544 PyObject *cause, *context;
1545
1546 if (seen != NULL) {
1547 /* Exception chaining */
1548 if (PySet_Add(seen, value) == -1)
1549 PyErr_Clear();
1550 else if (PyExceptionInstance_Check(value)) {
1551 cause = PyException_GetCause(value);
1552 context = PyException_GetContext(value);
1553 if (cause) {
1554 res = PySet_Contains(seen, cause);
1555 if (res == -1)
1556 PyErr_Clear();
1557 if (res == 0) {
1558 print_exception_recursive(
1559 f, cause, seen);
1560 err |= PyFile_WriteString(
1561 cause_message, f);
1562 }
1563 }
1564 if (context) {
1565 res = PySet_Contains(seen, context);
1566 if (res == -1)
1567 PyErr_Clear();
1568 if (res == 0) {
1569 print_exception_recursive(
1570 f, context, seen);
1571 err |= PyFile_WriteString(
1572 context_message, f);
1573 }
1574 }
1575 Py_XDECREF(context);
1576 Py_XDECREF(cause);
1577 }
1578 }
1579 print_exception(f, value);
1580 if (err != 0)
1581 PyErr_Clear();
1582}
1583
Thomas Wouters477c8d52006-05-27 19:21:47 +00001584void
1585PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001586{
Benjamin Petersone6528212008-07-15 15:32:09 +00001587 PyObject *seen;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001588 PyObject *f = PySys_GetObject("stderr");
Christian Heimes2be03732007-11-15 02:26:46 +00001589 if (f == Py_None) {
1590 /* pass */
1591 }
1592 else if (f == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00001593 _PyObject_Dump(value);
Guido van Rossum3165fe61992-09-25 21:59:05 +00001594 fprintf(stderr, "lost sys.stderr\n");
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001595 }
Guido van Rossum3165fe61992-09-25 21:59:05 +00001596 else {
Benjamin Petersone6528212008-07-15 15:32:09 +00001597 /* We choose to ignore seen being possibly NULL, and report
1598 at least the main exception (it could be a MemoryError).
1599 */
1600 seen = PySet_New(NULL);
1601 if (seen == NULL)
1602 PyErr_Clear();
1603 print_exception_recursive(f, value, seen);
1604 Py_XDECREF(seen);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001605 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001606}
1607
Guido van Rossum82598051997-03-05 00:20:32 +00001608PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001609PyRun_StringFlags(const char *str, int start, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001610 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001611{
Neal Norwitze92fba02006-03-04 18:52:26 +00001612 PyObject *ret = NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001613 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001614 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001615 if (arena == NULL)
1616 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001617
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001618 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
Neal Norwitze92fba02006-03-04 18:52:26 +00001619 if (mod != NULL)
1620 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001621 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001622 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001623}
1624
1625PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001626PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001627 PyObject *locals, int closeit, PyCompilerFlags *flags)
1628{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001629 PyObject *ret;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001630 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001631 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001632 if (arena == NULL)
1633 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001634
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001635 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001636 flags, NULL, arena);
Guido van Rossumd8faa362007-04-27 19:54:29 +00001637 if (closeit)
1638 fclose(fp);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001639 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001640 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001641 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001642 }
Neal Norwitze92fba02006-03-04 18:52:26 +00001643 ret = run_mod(mod, filename, globals, locals, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001644 PyArena_Free(arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001645 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001646}
1647
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001648static void
1649flush_io(void)
1650{
1651 PyObject *f, *r;
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001652 PyObject *type, *value, *traceback;
1653
1654 /* Save the current exception */
1655 PyErr_Fetch(&type, &value, &traceback);
1656
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001657 f = PySys_GetObject("stderr");
1658 if (f != NULL) {
1659 r = PyObject_CallMethod(f, "flush", "");
1660 if (r)
1661 Py_DECREF(r);
1662 else
1663 PyErr_Clear();
1664 }
1665 f = PySys_GetObject("stdout");
1666 if (f != NULL) {
1667 r = PyObject_CallMethod(f, "flush", "");
1668 if (r)
1669 Py_DECREF(r);
1670 else
1671 PyErr_Clear();
1672 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001673
1674 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001675}
1676
Guido van Rossum82598051997-03-05 00:20:32 +00001677static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001678run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001679 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001680{
Guido van Rossum82598051997-03-05 00:20:32 +00001681 PyCodeObject *co;
1682 PyObject *v;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001683 co = PyAST_Compile(mod, filename, flags, arena);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001684 if (co == NULL)
1685 return NULL;
Guido van Rossum82598051997-03-05 00:20:32 +00001686 v = PyEval_EvalCode(co, globals, locals);
1687 Py_DECREF(co);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001688 return v;
1689}
1690
Guido van Rossum82598051997-03-05 00:20:32 +00001691static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001692run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001693 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001694{
Guido van Rossum82598051997-03-05 00:20:32 +00001695 PyCodeObject *co;
1696 PyObject *v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001697 long magic;
Fred Drakee8de31c2000-08-31 05:38:39 +00001698 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001699
Guido van Rossum82598051997-03-05 00:20:32 +00001700 magic = PyMarshal_ReadLongFromFile(fp);
1701 if (magic != PyImport_GetMagicNumber()) {
1702 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001703 "Bad magic number in .pyc file");
1704 return NULL;
1705 }
Guido van Rossum82598051997-03-05 00:20:32 +00001706 (void) PyMarshal_ReadLongFromFile(fp);
Tim Petersd9b9ac82001-01-28 00:27:39 +00001707 v = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001708 fclose(fp);
Guido van Rossum82598051997-03-05 00:20:32 +00001709 if (v == NULL || !PyCode_Check(v)) {
1710 Py_XDECREF(v);
1711 PyErr_SetString(PyExc_RuntimeError,
Guido van Rossumfdef2711994-09-14 13:31:04 +00001712 "Bad code object in .pyc file");
1713 return NULL;
1714 }
Guido van Rossum82598051997-03-05 00:20:32 +00001715 co = (PyCodeObject *)v;
1716 v = PyEval_EvalCode(co, globals, locals);
Jeremy Hyltonb857ba22001-08-10 21:41:33 +00001717 if (v && flags)
1718 flags->cf_flags |= (co->co_flags & PyCF_MASK);
Guido van Rossum82598051997-03-05 00:20:32 +00001719 Py_DECREF(co);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001720 return v;
1721}
1722
Guido van Rossum82598051997-03-05 00:20:32 +00001723PyObject *
Tim Petersd08e3822003-04-17 15:24:21 +00001724Py_CompileStringFlags(const char *str, const char *filename, int start,
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001725 PyCompilerFlags *flags)
1726{
Guido van Rossum82598051997-03-05 00:20:32 +00001727 PyCodeObject *co;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001728 mod_ty mod;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001729 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001730 if (arena == NULL)
1731 return NULL;
1732
1733 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001734 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001735 PyArena_Free(arena);
Guido van Rossum5b722181993-03-30 17:46:03 +00001736 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001737 }
Martin v. Löwis2b366e42006-02-26 22:12:35 +00001738 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
Martin v. Löwisbd260da2006-02-26 19:42:26 +00001739 PyObject *result = PyAST_mod2obj(mod);
1740 PyArena_Free(arena);
1741 return result;
1742 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001743 co = PyAST_Compile(mod, filename, flags, arena);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001744 PyArena_Free(arena);
Guido van Rossum82598051997-03-05 00:20:32 +00001745 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001746}
1747
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001748struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001749Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001750{
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001751 struct symtable *st;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001752 mod_ty mod;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001753 PyCompilerFlags flags;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001754 PyArena *arena = PyArena_New();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001755 if (arena == NULL)
1756 return NULL;
1757
Christian Heimesb1b3efc2008-03-26 23:24:27 +00001758 flags.cf_flags = 0;
Christian Heimes4d6ec852008-03-26 22:34:47 +00001759 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001760 if (mod == NULL) {
Neal Norwitz9589ee22006-03-04 19:01:22 +00001761 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001762 return NULL;
Neal Norwitz9589ee22006-03-04 19:01:22 +00001763 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001764 st = PySymtable_Build(mod, filename, 0);
Neal Norwitz9589ee22006-03-04 19:01:22 +00001765 PyArena_Free(arena);
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001766 return st;
1767}
1768
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001769/* Preferred access to parser is through AST. */
1770mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001771PyParser_ASTFromString(const char *s, const char *filename, int start,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001772 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001773{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001774 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001775 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001776 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001777 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001778
1779 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001780 &_PyParser_Grammar, start, &err,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001781 &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001782 if (flags == NULL) {
1783 localflags.cf_flags = 0;
1784 flags = &localflags;
1785 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001786 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001787 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001788 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001789 PyNode_Free(n);
1790 return mod;
1791 }
1792 else {
1793 err_input(&err);
1794 return NULL;
1795 }
1796}
1797
1798mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001799PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
1800 int start, char *ps1,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001801 char *ps2, PyCompilerFlags *flags, int *errcode,
Neal Norwitz9589ee22006-03-04 19:01:22 +00001802 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001803{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001804 mod_ty mod;
Benjamin Petersonf216c942008-10-31 02:28:05 +00001805 PyCompilerFlags localflags;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001806 perrdetail err;
Christian Heimes3a932122008-03-26 23:25:24 +00001807 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001808
Christian Heimes4d6ec852008-03-26 22:34:47 +00001809 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001810 &_PyParser_Grammar,
Christian Heimes4d6ec852008-03-26 22:34:47 +00001811 start, ps1, ps2, &err, &iflags);
Benjamin Petersonf216c942008-10-31 02:28:05 +00001812 if (flags == NULL) {
1813 localflags.cf_flags = 0;
1814 flags = &localflags;
1815 }
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001816 if (n) {
Benjamin Petersonf216c942008-10-31 02:28:05 +00001817 flags->cf_flags |= iflags & PyCF_MASK;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001818 mod = PyAST_FromNode(n, flags, filename, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001819 PyNode_Free(n);
1820 return mod;
1821 }
1822 else {
1823 err_input(&err);
1824 if (errcode)
1825 *errcode = err.error;
1826 return NULL;
1827 }
1828}
1829
Guido van Rossuma110aa61994-08-29 12:50:44 +00001830/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001831
Guido van Rossuma110aa61994-08-29 12:50:44 +00001832node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001833PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001834{
Guido van Rossuma110aa61994-08-29 12:50:44 +00001835 perrdetail err;
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001836 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
1837 &_PyParser_Grammar,
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001838 start, NULL, NULL, &err, flags);
Guido van Rossuma110aa61994-08-29 12:50:44 +00001839 if (n == NULL)
1840 err_input(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001841
Guido van Rossuma110aa61994-08-29 12:50:44 +00001842 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001843}
1844
Guido van Rossuma110aa61994-08-29 12:50:44 +00001845/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001846
Guido van Rossuma110aa61994-08-29 12:50:44 +00001847node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001848PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00001849{
Tim Petersfe2127d2001-07-16 05:37:24 +00001850 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001851 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
1852 start, &err, flags);
Tim Petersfe2127d2001-07-16 05:37:24 +00001853 if (n == NULL)
1854 err_input(&err);
1855 return n;
1856}
1857
1858node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001859PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Thomas Heller6b17abf2002-07-09 09:23:27 +00001860 int start, int flags)
1861{
Thomas Heller6b17abf2002-07-09 09:23:27 +00001862 perrdetail err;
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001863 node *n = PyParser_ParseStringFlagsFilename(str, filename,
1864 &_PyParser_Grammar, start, &err, flags);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001865 if (n == NULL)
1866 err_input(&err);
1867 return n;
1868}
1869
1870node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001871PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00001872{
Neal Norwitzadb69fc2005-12-17 20:54:49 +00001873 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00001874}
1875
Guido van Rossum66ebd912003-04-17 16:02:26 +00001876/* May want to move a more generalized form of this to parsetok.c or
1877 even parser modules. */
1878
1879void
1880PyParser_SetError(perrdetail *err)
1881{
1882 err_input(err);
1883}
1884
Guido van Rossuma110aa61994-08-29 12:50:44 +00001885/* Set the error appropriate to the given input error code (see errcode.h) */
1886
1887static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001888err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00001889{
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001890 PyObject *v, *w, *errtype, *errtext;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001891 PyObject* u = NULL;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001892 char *msg = NULL;
Fred Drake85f36392000-07-11 17:53:00 +00001893 errtype = PyExc_SyntaxError;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001894 switch (err->error) {
1895 case E_SYNTAX:
Fred Drake85f36392000-07-11 17:53:00 +00001896 errtype = PyExc_IndentationError;
1897 if (err->expected == INDENT)
1898 msg = "expected an indented block";
1899 else if (err->token == INDENT)
1900 msg = "unexpected indent";
1901 else if (err->token == DEDENT)
1902 msg = "unexpected unindent";
1903 else {
1904 errtype = PyExc_SyntaxError;
1905 msg = "invalid syntax";
1906 }
Guido van Rossuma110aa61994-08-29 12:50:44 +00001907 break;
1908 case E_TOKEN:
1909 msg = "invalid token";
Guido van Rossuma110aa61994-08-29 12:50:44 +00001910 break;
Skip Montanaro118ec702002-08-15 01:20:16 +00001911 case E_EOFS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001912 msg = "EOF while scanning triple-quoted string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001913 break;
1914 case E_EOLS:
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +00001915 msg = "EOL while scanning string literal";
Skip Montanaro118ec702002-08-15 01:20:16 +00001916 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001917 case E_INTR:
Michael W. Hudson30ea2f22004-07-07 17:44:12 +00001918 if (!PyErr_Occurred())
1919 PyErr_SetNone(PyExc_KeyboardInterrupt);
Georg Brandl3dbca812008-07-23 16:10:53 +00001920 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001921 case E_NOMEM:
Guido van Rossum82598051997-03-05 00:20:32 +00001922 PyErr_NoMemory();
Georg Brandl3dbca812008-07-23 16:10:53 +00001923 goto cleanup;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001924 case E_EOF:
1925 msg = "unexpected EOF while parsing";
1926 break;
Fred Drake85f36392000-07-11 17:53:00 +00001927 case E_TABSPACE:
1928 errtype = PyExc_TabError;
Guido van Rossum560e8ad1998-04-10 19:43:42 +00001929 msg = "inconsistent use of tabs and spaces in indentation";
1930 break;
Jeremy Hylton94988062000-06-20 19:10:44 +00001931 case E_OVERFLOW:
1932 msg = "expression too long";
1933 break;
Fred Drake85f36392000-07-11 17:53:00 +00001934 case E_DEDENT:
1935 errtype = PyExc_IndentationError;
1936 msg = "unindent does not match any outer indentation level";
1937 break;
1938 case E_TOODEEP:
1939 errtype = PyExc_IndentationError;
1940 msg = "too many levels of indentation";
1941 break;
Martin v. Löwisd35edda2005-08-24 08:39:24 +00001942 case E_DECODE: {
1943 PyObject *type, *value, *tb;
1944 PyErr_Fetch(&type, &value, &tb);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001945 if (value != NULL) {
Thomas Heller519a0422007-11-15 20:48:54 +00001946 u = PyObject_Str(value);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001947 if (u != NULL) {
Marc-André Lemburg4cc0f242008-08-07 18:54:33 +00001948 msg = _PyUnicode_AsString(u);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001949 }
1950 }
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001951 if (msg == NULL)
1952 msg = "unknown decode error";
Neal Norwitzdb83eb32005-12-18 05:29:30 +00001953 Py_XDECREF(type);
1954 Py_XDECREF(value);
Neal Norwitz40d37812005-10-02 01:48:49 +00001955 Py_XDECREF(tb);
Martin v. Löwisc2632a52004-07-21 05:35:02 +00001956 break;
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001957 }
Martin v. Löwis4bf108d2005-03-03 11:45:45 +00001958 case E_LINECONT:
1959 msg = "unexpected character after line continuation character";
1960 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00001961
1962 case E_IDENTIFIER:
1963 msg = "invalid character in identifier";
1964 break;
Guido van Rossuma110aa61994-08-29 12:50:44 +00001965 default:
1966 fprintf(stderr, "error=%d\n", err->error);
1967 msg = "unknown parsing error";
1968 break;
1969 }
Martin v. Löwis5deb2102007-08-31 11:17:42 +00001970 /* err->text may not be UTF-8 in case of decoding errors.
1971 Explicitly convert to an object. */
1972 if (!err->text) {
1973 errtext = Py_None;
1974 Py_INCREF(Py_None);
1975 } else {
1976 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
1977 "replace");
1978 }
1979 v = Py_BuildValue("(ziiN)", err->filename,
1980 err->lineno, err->offset, errtext);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001981 w = NULL;
1982 if (v != NULL)
1983 w = Py_BuildValue("(sO)", msg, v);
Martin v. Löwis00f1e3f2002-08-04 17:29:52 +00001984 Py_XDECREF(u);
Guido van Rossum41318302001-03-23 04:01:07 +00001985 Py_XDECREF(v);
Fred Drake85f36392000-07-11 17:53:00 +00001986 PyErr_SetObject(errtype, w);
Guido van Rossum82598051997-03-05 00:20:32 +00001987 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00001988cleanup:
1989 if (err->text != NULL) {
1990 PyObject_FREE(err->text);
1991 err->text = NULL;
1992 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001993}
1994
1995/* Print fatal error message and abort */
1996
1997void
Tim Peters7c321a82002-07-09 02:57:01 +00001998Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001999{
Guido van Rossum83dd6c31994-09-29 09:38:33 +00002000 fprintf(stderr, "Fatal Python error: %s\n", msg);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00002001 if (PyErr_Occurred()) {
2002 PyErr_Print();
2003 }
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002004#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002005 {
2006 size_t len = strlen(msg);
2007 WCHAR* buffer;
2008 size_t i;
2009
2010 /* Convert the message to wchar_t. This uses a simple one-to-one
2011 conversion, assuming that the this error message actually uses ASCII
2012 only. If this ceases to be true, we will have to convert. */
2013 buffer = alloca( (len+1) * (sizeof *buffer));
2014 for( i=0; i<=len; ++i)
2015 buffer[i] = msg[i];
2016 OutputDebugStringW(L"Fatal Python error: ");
2017 OutputDebugStringW(buffer);
2018 OutputDebugStringW(L"\n");
2019 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002020#ifdef _DEBUG
2021 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002022#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002023#endif /* MS_WINDOWS */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002024 abort();
2025}
2026
2027/* Clean up and exit */
2028
Guido van Rossuma110aa61994-08-29 12:50:44 +00002029#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002030#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002031#endif
2032
Collin Winter670e6922007-03-21 02:57:17 +00002033static void (*pyexitfunc)(void) = NULL;
2034/* For the atexit module. */
2035void _Py_PyAtExit(void (*func)(void))
2036{
2037 pyexitfunc = func;
2038}
2039
2040static void
2041call_py_exitfuncs(void)
2042{
Guido van Rossum98297ee2007-11-06 21:34:58 +00002043 if (pyexitfunc == NULL)
Collin Winter670e6922007-03-21 02:57:17 +00002044 return;
2045
2046 (*pyexitfunc)();
2047 PyErr_Clear();
2048}
2049
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002050#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002051static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002052static int nexitfuncs = 0;
2053
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002054int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002055{
2056 if (nexitfuncs >= NEXITFUNCS)
2057 return -1;
2058 exitfuncs[nexitfuncs++] = func;
2059 return 0;
2060}
2061
Guido van Rossumcc283f51997-08-05 02:22:03 +00002062static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002063call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002064{
Guido van Rossum1662dd51994-09-07 14:38:28 +00002065 while (nexitfuncs > 0)
2066 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002067
2068 fflush(stdout);
2069 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002070}
2071
2072void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002073Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002074{
Guido van Rossumcc283f51997-08-05 02:22:03 +00002075 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002076
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002077 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002078}
2079
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002080static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002081initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002082{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002083#ifdef SIGPIPE
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002084 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002085#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002086#ifdef SIGXFZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002087 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002088#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002089#ifdef SIGXFSZ
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002090 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002091#endif
Guido van Rossum82598051997-03-05 00:20:32 +00002092 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002093}
2094
Guido van Rossum7433b121997-02-14 19:45:36 +00002095
2096/*
2097 * The file descriptor fd is considered ``interactive'' if either
2098 * a) isatty(fd) is TRUE, or
2099 * b) the -i flag was given, and the filename associated with
2100 * the descriptor is NULL or "<stdin>" or "???".
2101 */
2102int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002103Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002104{
2105 if (isatty((int)fileno(fp)))
2106 return 1;
2107 if (!Py_InteractiveFlag)
2108 return 0;
2109 return (filename == NULL) ||
2110 (strcmp(filename, "<stdin>") == 0) ||
2111 (strcmp(filename, "???") == 0);
2112}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002113
2114
Tim Petersd08e3822003-04-17 15:24:21 +00002115#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002116#if defined(WIN32) && defined(_MSC_VER)
2117
2118/* Stack checking for Microsoft C */
2119
2120#include <malloc.h>
2121#include <excpt.h>
2122
Fred Drakee8de31c2000-08-31 05:38:39 +00002123/*
2124 * Return non-zero when we run out of memory on the stack; zero otherwise.
2125 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002126int
Fred Drake399739f2000-08-31 05:52:44 +00002127PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002128{
2129 __try {
Tim Peters92e4dd82002-10-05 01:47:34 +00002130 /* alloca throws a stack overflow exception if there's
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002131 not enough space left on the stack */
Tim Peters92e4dd82002-10-05 01:47:34 +00002132 alloca(PYOS_STACK_MARGIN * sizeof(void*));
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002133 return 0;
Christian Heimes7131fd92008-02-19 14:21:46 +00002134 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
Trent Nelson39e307e2008-03-19 06:45:48 +00002135 EXCEPTION_EXECUTE_HANDLER :
2136 EXCEPTION_CONTINUE_SEARCH) {
Christian Heimes7131fd92008-02-19 14:21:46 +00002137 int errcode = _resetstkoflw();
Amaury Forgeot d'Arcb0c29162008-11-22 22:18:04 +00002138 if (errcode == 0)
Christian Heimes7131fd92008-02-19 14:21:46 +00002139 {
2140 Py_FatalError("Could not reset the stack!");
2141 }
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002142 }
2143 return 1;
2144}
2145
2146#endif /* WIN32 && _MSC_VER */
2147
2148/* Alternate implementations can be added here... */
2149
2150#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002151
2152
2153/* Wrappers around sigaction() or signal(). */
2154
2155PyOS_sighandler_t
2156PyOS_getsig(int sig)
2157{
2158#ifdef HAVE_SIGACTION
2159 struct sigaction context;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002160 if (sigaction(sig, NULL, &context) == -1)
2161 return SIG_ERR;
Guido van Rossum6f256182000-09-16 16:32:19 +00002162 return context.sa_handler;
2163#else
2164 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002165/* Special signal handling for the secure CRT in Visual Studio 2005 */
2166#if defined(_MSC_VER) && _MSC_VER >= 1400
2167 switch (sig) {
2168 /* Only these signals are valid */
2169 case SIGINT:
2170 case SIGILL:
2171 case SIGFPE:
2172 case SIGSEGV:
2173 case SIGTERM:
2174 case SIGBREAK:
2175 case SIGABRT:
2176 break;
2177 /* Don't call signal() with other values or it will assert */
2178 default:
2179 return SIG_ERR;
2180 }
2181#endif /* _MSC_VER && _MSC_VER >= 1400 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002182 handler = signal(sig, SIG_IGN);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002183 if (handler != SIG_ERR)
2184 signal(sig, handler);
Guido van Rossum6f256182000-09-16 16:32:19 +00002185 return handler;
2186#endif
2187}
2188
2189PyOS_sighandler_t
2190PyOS_setsig(int sig, PyOS_sighandler_t handler)
2191{
2192#ifdef HAVE_SIGACTION
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002193 struct sigaction context, ocontext;
Guido van Rossum6f256182000-09-16 16:32:19 +00002194 context.sa_handler = handler;
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002195 sigemptyset(&context.sa_mask);
2196 context.sa_flags = 0;
2197 if (sigaction(sig, &context, &ocontext) == -1)
2198 return SIG_ERR;
2199 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002200#else
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002201 PyOS_sighandler_t oldhandler;
2202 oldhandler = signal(sig, handler);
2203#ifdef HAVE_SIGINTERRUPT
2204 siginterrupt(sig, 1);
2205#endif
2206 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002207#endif
2208}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002209
2210/* Deprecated C API functions still provided for binary compatiblity */
2211
2212#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002213PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002214PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2215{
2216 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
2217}
2218
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002219#undef PyParser_SimpleParseString
2220PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002221PyParser_SimpleParseString(const char *str, int start)
2222{
2223 return PyParser_SimpleParseStringFlags(str, start, 0);
2224}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002225
2226#undef PyRun_AnyFile
2227PyAPI_FUNC(int)
2228PyRun_AnyFile(FILE *fp, const char *name)
2229{
2230 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
2231}
2232
2233#undef PyRun_AnyFileEx
2234PyAPI_FUNC(int)
2235PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2236{
2237 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
2238}
2239
2240#undef PyRun_AnyFileFlags
2241PyAPI_FUNC(int)
2242PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2243{
2244 return PyRun_AnyFileExFlags(fp, name, 0, flags);
2245}
2246
2247#undef PyRun_File
2248PyAPI_FUNC(PyObject *)
2249PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2250{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002251 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002252}
2253
2254#undef PyRun_FileEx
2255PyAPI_FUNC(PyObject *)
2256PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2257{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002258 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002259}
2260
2261#undef PyRun_FileFlags
2262PyAPI_FUNC(PyObject *)
2263PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
2264 PyCompilerFlags *flags)
2265{
Georg Brandl86b2fb92008-07-16 03:43:04 +00002266 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002267}
2268
2269#undef PyRun_SimpleFile
2270PyAPI_FUNC(int)
2271PyRun_SimpleFile(FILE *f, const char *p)
2272{
2273 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
2274}
2275
2276#undef PyRun_SimpleFileEx
2277PyAPI_FUNC(int)
2278PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2279{
2280 return PyRun_SimpleFileExFlags(f, p, c, NULL);
2281}
2282
2283
2284#undef PyRun_String
2285PyAPI_FUNC(PyObject *)
2286PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2287{
2288 return PyRun_StringFlags(str, s, g, l, NULL);
2289}
2290
2291#undef PyRun_SimpleString
2292PyAPI_FUNC(int)
2293PyRun_SimpleString(const char *s)
2294{
2295 return PyRun_SimpleStringFlags(s, NULL);
2296}
2297
2298#undef Py_CompileString
2299PyAPI_FUNC(PyObject *)
2300Py_CompileString(const char *str, const char *p, int s)
2301{
2302 return Py_CompileStringFlags(str, p, s, NULL);
2303}
2304
2305#undef PyRun_InteractiveOne
2306PyAPI_FUNC(int)
2307PyRun_InteractiveOne(FILE *f, const char *p)
2308{
2309 return PyRun_InteractiveOneFlags(f, p, NULL);
2310}
2311
2312#undef PyRun_InteractiveLoop
2313PyAPI_FUNC(int)
2314PyRun_InteractiveLoop(FILE *f, const char *p)
2315{
2316 return PyRun_InteractiveLoopFlags(f, p, NULL);
2317}
2318
2319#ifdef __cplusplus
2320}
2321#endif