blob: f4e7e7b9b253138631a1be46798632b6335fe74f [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"
Jeremy Hylton4b38da62001-02-02 18:19:15 +000014#include "symtable.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000015#include "ast.h"
Guido van Rossumfdef2711994-09-14 13:31:04 +000016#include "marshal.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000017#include "osdefs.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000018
Thomas Wouters0e3f5912006-08-11 14:57:12 +000019#ifdef HAVE_SIGNAL_H
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000020#include <signal.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +000021#endif
Guido van Rossuma9e7dc11992-10-18 18:53:57 +000022
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000023#ifdef MS_WINDOWS
Martin v. Löwis5c88d812009-01-02 20:47:48 +000024#include "malloc.h" /* for alloca */
Benjamin Peterson80a50ac2009-01-02 21:24:04 +000025#endif
Martin v. Löwis5c88d812009-01-02 20:47:48 +000026
Martin v. Löwis73d538b2003-03-05 15:13:47 +000027#ifdef HAVE_LANGINFO_H
28#include <locale.h>
29#include <langinfo.h>
30#endif
31
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000032#ifdef MS_WINDOWS
Guido van Rossuma44823b1995-03-14 15:01:17 +000033#undef BYTE
34#include "windows.h"
Martin v. Löwis790465f2008-04-05 20:41:37 +000035#define PATH_MAX MAXPATHLEN
Guido van Rossuma44823b1995-03-14 15:01:17 +000036#endif
37
Neal Norwitz4281cef2006-03-04 19:58:13 +000038#ifndef Py_REF_DEBUG
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000039#define PRINT_TOTAL_REFS()
Neal Norwitz4281cef2006-03-04 19:58:13 +000040#else /* Py_REF_DEBUG */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000041#define PRINT_TOTAL_REFS() fprintf(stderr, \
42 "[%" PY_FORMAT_SIZE_T "d refs]\n", \
43 _Py_GetRefTotal())
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000044#endif
45
46#ifdef __cplusplus
47extern "C" {
Neal Norwitz4281cef2006-03-04 19:58:13 +000048#endif
49
Martin v. Löwis790465f2008-04-05 20:41:37 +000050extern wchar_t *Py_GetPath(void);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000051
Guido van Rossum82598051997-03-05 00:20:32 +000052extern grammar _PyParser_Grammar; /* From graminit.c */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000053
Guido van Rossumb73cc041993-11-01 16:28:59 +000054/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +000055static void initmain(void);
Victor Stinner793b5312011-04-27 00:24:21 +020056static int initfsencoding(PyInterpreterState *interp);
Tim Petersdbd9ba62000-07-09 03:09:57 +000057static void initsite(void);
Guido van Rossumce3a72a2007-10-19 23:16:50 +000058static int initstdio(void);
Amaury Forgeot d'Arc7fedbe52008-04-10 21:03:09 +000059static void flush_io(void);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000060static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000061 PyCompilerFlags *, PyArena *);
Martin v. Löwis95292d62002-12-11 14:04:59 +000062static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyCompilerFlags *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000064static void err_input(perrdetail *);
Victor Stinner7f2fee32011-04-05 00:39:01 +020065static void err_free(perrdetail *);
Tim Petersdbd9ba62000-07-09 03:09:57 +000066static void initsigs(void);
Collin Winter670e6922007-03-21 02:57:17 +000067static void call_py_exitfuncs(void);
Antoine Pitrou011bd622009-10-20 21:52:47 +000068static void wait_for_thread_shutdown(void);
Tim Petersdbd9ba62000-07-09 03:09:57 +000069static void call_ll_exitfuncs(void);
Victor Stinner3a50e702011-10-18 21:21:00 +020070extern int _PyUnicode_Init(void);
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000071extern void _PyUnicode_Fini(void);
Guido van Rossumddefaf32007-01-14 03:31:43 +000072extern int _PyLong_Init(void);
73extern void PyLong_Fini(void);
Victor Stinner024e37a2011-03-31 01:31:06 +020074extern int _PyFaulthandler_Init(void);
75extern void _PyFaulthandler_Fini(void);
Guido van Rossumc94044c2000-03-10 23:03:54 +000076
Mark Hammond8d98d2c2003-04-19 15:41:53 +000077#ifdef WITH_THREAD
78extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
79extern void _PyGILState_Fini(void);
80#endif /* WITH_THREAD */
81
Guido van Rossum82598051997-03-05 00:20:32 +000082int Py_DebugFlag; /* Needed by parser.c */
83int Py_VerboseFlag; /* Needed by import.c */
Georg Brandl8aa7e992010-12-28 18:30:18 +000084int Py_QuietFlag; /* Needed by sysmodule.c */
Guido van Rossum7433b121997-02-14 19:45:36 +000085int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
Georg Brandl0b2489e2011-05-15 08:49:12 +020086int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
Guido van Rossumdcc0c131997-08-29 22:32:42 +000087int Py_NoSiteFlag; /* Suppress 'import site' */
Guido van Rossum98297ee2007-11-06 21:34:58 +000088int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Christian Heimes790c8232008-01-07 21:14:23 +000089int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
Barry Warsaw3ce09642000-05-02 19:18:59 +000090int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
Guido van Rossuma61691e1998-02-06 22:27:24 +000091int Py_FrozenFlag; /* Needed by getpath.c */
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +000092int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Christian Heimes8dc226f2008-05-06 23:45:46 +000093int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
Antoine Pitrou05608432009-01-09 18:53:14 +000094int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
Georg Brandl2daf6ae2012-02-20 19:54:16 +010095int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000096
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +020097PyThreadState *_Py_Finalizing = NULL;
98
Christian Heimes33fe8092008-04-13 13:53:33 +000099/* PyModule_GetWarningsModule is no longer necessary as of 2.6
100since _warnings is builtin. This API should not be used. */
101PyObject *
102PyModule_GetWarningsModule(void)
Mark Hammondedd07732003-07-15 23:03:55 +0000103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 return PyImport_ImportModule("warnings");
Mark Hammondedd07732003-07-15 23:03:55 +0000105}
Mark Hammonda43fd0c2003-02-19 00:33:33 +0000106
Guido van Rossum25ce5661997-08-02 03:10:38 +0000107static int initialized = 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000108
Thomas Wouters7e474022000-07-16 12:04:32 +0000109/* API to access the initialized flag -- useful for esoteric use */
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000110
111int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000112Py_IsInitialized(void)
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000114 return initialized;
Guido van Rossume3c0d5e1997-08-22 04:20:13 +0000115}
116
Guido van Rossum25ce5661997-08-02 03:10:38 +0000117/* Global initializations. Can be undone by Py_Finalize(). Don't
118 call this twice without an intervening Py_Finalize() call. When
119 initializations fail, a fatal error is issued and the function does
120 not return. On return, the first thread and interpreter state have
121 been created.
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000122
Guido van Rossum25ce5661997-08-02 03:10:38 +0000123 Locking: you must hold the interpreter lock while calling this.
124 (If the lock has not yet been initialized, that's equivalent to
125 having the lock, but you cannot use multiple threads.)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +0000126
Guido van Rossum25ce5661997-08-02 03:10:38 +0000127*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000128
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000129static int
130add_flag(int flag, const char *envs)
131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000132 int env = atoi(envs);
133 if (flag < env)
134 flag = env;
135 if (flag < 1)
136 flag = 1;
137 return flag;
Guido van Rossum9abaf4d2001-10-12 22:17:56 +0000138}
139
Christian Heimes5833a2f2008-10-30 21:40:04 +0000140static char*
Victor Stinner94908bb2010-08-18 21:23:25 +0000141get_codec_name(const char *encoding)
Christian Heimes5833a2f2008-10-30 21:40:04 +0000142{
Victor Stinner94908bb2010-08-18 21:23:25 +0000143 char *name_utf8, *name_str;
Victor Stinner386fe712010-05-19 00:34:15 +0000144 PyObject *codec, *name = NULL;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200145 _Py_IDENTIFIER(name);
Christian Heimes5833a2f2008-10-30 21:40:04 +0000146
Victor Stinner94908bb2010-08-18 21:23:25 +0000147 codec = _PyCodec_Lookup(encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 if (!codec)
149 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000150
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200151 name = _PyObject_GetAttrId(codec, &PyId_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 Py_CLEAR(codec);
153 if (!name)
154 goto error;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000155
Victor Stinner94908bb2010-08-18 21:23:25 +0000156 name_utf8 = _PyUnicode_AsString(name);
Victor Stinner4ca28092011-03-20 23:09:03 +0100157 if (name_utf8 == NULL)
Victor Stinner386fe712010-05-19 00:34:15 +0000158 goto error;
Victor Stinner94908bb2010-08-18 21:23:25 +0000159 name_str = strdup(name_utf8);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000160 Py_DECREF(name);
Victor Stinner94908bb2010-08-18 21:23:25 +0000161 if (name_str == NULL) {
162 PyErr_NoMemory();
163 return NULL;
164 }
165 return name_str;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000166
167error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 Py_XDECREF(codec);
Victor Stinner386fe712010-05-19 00:34:15 +0000169 Py_XDECREF(name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000171}
Victor Stinner94908bb2010-08-18 21:23:25 +0000172
Victor Stinner94908bb2010-08-18 21:23:25 +0000173static char*
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200174get_locale_encoding(void)
Victor Stinner94908bb2010-08-18 21:23:25 +0000175{
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200176#ifdef MS_WINDOWS
177 char codepage[100];
178 PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
179 return get_codec_name(codepage);
180#elif defined(HAVE_LANGINFO_H) && defined(CODESET)
Victor Stinner94908bb2010-08-18 21:23:25 +0000181 char* codeset = nl_langinfo(CODESET);
182 if (!codeset || codeset[0] == '\0') {
183 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
184 return NULL;
185 }
186 return get_codec_name(codeset);
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200187#else
188 PyErr_SetNone(PyExc_NotImplementedError);
189 return NULL;
Christian Heimes5833a2f2008-10-30 21:40:04 +0000190#endif
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200191}
Christian Heimes5833a2f2008-10-30 21:40:04 +0000192
Guido van Rossuma027efa1997-05-05 20:56:21 +0000193void
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000194Py_InitializeEx(int install_sigs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000195{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 PyInterpreterState *interp;
197 PyThreadState *tstate;
198 PyObject *bimod, *sysmod, *pstderr;
199 char *p;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 extern void _Py_ReadyTypes(void);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 if (initialized)
203 return;
204 initialized = 1;
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200205 _Py_Finalizing = NULL;
Tim Petersd08e3822003-04-17 15:24:21 +0000206
Andrew M. Kuchlingb2ceb3a2010-02-22 23:26:10 +0000207#if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 /* Set up the LC_CTYPE locale, so we can obtain
209 the locale's charset without having to switch
210 locales. */
211 setlocale(LC_CTYPE, "");
Martin v. Löwisd1cd4d42007-08-11 14:02:14 +0000212#endif
213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
215 Py_DebugFlag = add_flag(Py_DebugFlag, p);
216 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
217 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
218 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
219 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
220 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
221 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100222 /* The variable is only tested for existence here; _PyRandom_Init will
223 check its value further. */
224 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
225 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
226
227 _PyRandom_Init();
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000228
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000229 interp = PyInterpreterState_New();
230 if (interp == NULL)
231 Py_FatalError("Py_Initialize: can't make first interpreter");
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 tstate = PyThreadState_New(interp);
234 if (tstate == NULL)
235 Py_FatalError("Py_Initialize: can't make first thread");
236 (void) PyThreadState_Swap(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000237
Victor Stinner6961bd62010-08-17 22:26:51 +0000238#ifdef WITH_THREAD
Antoine Pitroub0b384b2010-09-20 20:13:48 +0000239 /* We can't call _PyEval_FiniThreads() in Py_Finalize because
240 destroying the GIL might fail when it is being referenced from
241 another running thread (see issue #9901).
242 Instead we destroy the previously created GIL here, which ensures
243 that we can call Py_Initialize / Py_Finalize multiple times. */
244 _PyEval_FiniThreads();
245
246 /* Auto-thread-state API */
Victor Stinner6961bd62010-08-17 22:26:51 +0000247 _PyGILState_Init(interp, tstate);
248#endif /* WITH_THREAD */
249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 _Py_ReadyTypes();
Guido van Rossum528b7eb2001-08-07 17:24:28 +0000251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 if (!_PyFrame_Init())
253 Py_FatalError("Py_Initialize: can't init frames");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 if (!_PyLong_Init())
256 Py_FatalError("Py_Initialize: can't init longs");
Neal Norwitzc91ed402002-12-30 22:29:22 +0000257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 if (!PyByteArray_Init())
259 Py_FatalError("Py_Initialize: can't init bytearray");
Neal Norwitz6968b052007-02-27 19:02:19 +0000260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 _PyFloat_Init();
Michael W. Hudsonba283e22005-05-27 15:23:20 +0000262
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 interp->modules = PyDict_New();
264 if (interp->modules == NULL)
265 Py_FatalError("Py_Initialize: can't make modules dictionary");
266 interp->modules_reloading = PyDict_New();
267 if (interp->modules_reloading == NULL)
268 Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
Guido van Rossuma027efa1997-05-05 20:56:21 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 /* Init Unicode implementation; relies on the codec registry */
Victor Stinner3a50e702011-10-18 21:21:00 +0200271 if (_PyUnicode_Init() < 0)
272 Py_FatalError("Py_Initialize: can't initialize unicode");
Guido van Rossumc94044c2000-03-10 23:03:54 +0000273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 bimod = _PyBuiltin_Init();
275 if (bimod == NULL)
276 Py_FatalError("Py_Initialize: can't initialize builtins modules");
Victor Stinner49d3f252010-10-17 01:24:53 +0000277 _PyImport_FixupBuiltin(bimod, "builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 interp->builtins = PyModule_GetDict(bimod);
279 if (interp->builtins == NULL)
280 Py_FatalError("Py_Initialize: can't initialize builtins dict");
281 Py_INCREF(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 /* initialize builtin exceptions */
284 _PyExc_Init();
Christian Heimes9a68f8c2007-11-14 00:16:07 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 sysmod = _PySys_Init();
287 if (sysmod == NULL)
288 Py_FatalError("Py_Initialize: can't initialize sys");
289 interp->sysdict = PyModule_GetDict(sysmod);
290 if (interp->sysdict == NULL)
291 Py_FatalError("Py_Initialize: can't initialize sys dict");
292 Py_INCREF(interp->sysdict);
Victor Stinner49d3f252010-10-17 01:24:53 +0000293 _PyImport_FixupBuiltin(sysmod, "sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 PySys_SetPath(Py_GetPath());
295 PyDict_SetItemString(interp->sysdict, "modules",
296 interp->modules);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 /* Set up a preliminary stderr printer until we have enough
299 infrastructure for the io module in place. */
300 pstderr = PyFile_NewStdPrinter(fileno(stderr));
301 if (pstderr == NULL)
302 Py_FatalError("Py_Initialize: can't set preliminary stderr");
303 PySys_SetObject("stderr", pstderr);
304 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000305 Py_DECREF(pstderr);
Guido van Rossum826d8972007-10-30 18:34:07 +0000306
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 _PyImport_Init();
Guido van Rossum7c85ab81999-07-08 17:26:56 +0000308
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 _PyImportHooks_Init();
Just van Rossum52e14d62002-12-30 22:08:05 +0000310
Victor Stinner024e37a2011-03-31 01:31:06 +0200311 /* initialize the faulthandler module */
312 if (_PyFaulthandler_Init())
313 Py_FatalError("Py_Initialize: can't initialize faulthandler");
314
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000315 /* Initialize _warnings. */
316 _PyWarnings_Init();
317
Alexander Belopolsky6fc4ade2010-08-05 17:34:27 +0000318 _PyTime_Init();
319
Victor Stinner793b5312011-04-27 00:24:21 +0200320 if (initfsencoding(interp) < 0)
321 Py_FatalError("Py_Initialize: unable to load the file system codec");
Martin v. Löwis011e8422009-05-05 04:43:17 +0000322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 if (install_sigs)
324 initsigs(); /* Signal handling stuff, including initintr() */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 initmain(); /* Module __main__ */
327 if (initstdio() < 0)
328 Py_FatalError(
329 "Py_Initialize: can't initialize sys standard streams");
330
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000331 /* Initialize warnings. */
332 if (PySys_HasWarnOptions()) {
333 PyObject *warnings_module = PyImport_ImportModule("warnings");
334 if (warnings_module == NULL) {
335 fprintf(stderr, "'import warnings' failed; traceback:\n");
336 PyErr_Print();
337 }
338 Py_XDECREF(warnings_module);
339 }
340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 if (!Py_NoSiteFlag)
342 initsite(); /* Module site */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000343}
344
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000345void
346Py_Initialize(void)
347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 Py_InitializeEx(1);
Martin v. Löwis336e85f2004-08-19 11:31:58 +0000349}
350
351
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000352#ifdef COUNT_ALLOCS
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000353extern void dump_counts(FILE*);
Guido van Rossum2edcf0d1998-12-15 16:12:00 +0000354#endif
355
Guido van Rossume8432ac2007-07-09 15:04:50 +0000356/* Flush stdout and stderr */
357
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100358static int
359file_is_closed(PyObject *fobj)
360{
361 int r;
362 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
363 if (tmp == NULL) {
364 PyErr_Clear();
365 return 0;
366 }
367 r = PyObject_IsTrue(tmp);
368 Py_DECREF(tmp);
369 if (r < 0)
370 PyErr_Clear();
371 return r > 0;
372}
373
Neal Norwitz2bad9702007-08-27 06:19:22 +0000374static void
Guido van Rossum1bd21222007-07-10 20:14:13 +0000375flush_std_files(void)
Guido van Rossume8432ac2007-07-09 15:04:50 +0000376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 PyObject *fout = PySys_GetObject("stdout");
378 PyObject *ferr = PySys_GetObject("stderr");
379 PyObject *tmp;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200380 _Py_IDENTIFIER(flush);
Guido van Rossume8432ac2007-07-09 15:04:50 +0000381
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100382 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200383 tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 if (tmp == NULL)
Antoine Pitroubddc9fe2010-08-08 20:46:42 +0000385 PyErr_WriteUnraisable(fout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 else
387 Py_DECREF(tmp);
388 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000389
Antoine Pitroud7c8fbf2011-11-26 21:59:36 +0100390 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200391 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 if (tmp == NULL)
393 PyErr_Clear();
394 else
395 Py_DECREF(tmp);
396 }
Guido van Rossume8432ac2007-07-09 15:04:50 +0000397}
398
Guido van Rossum25ce5661997-08-02 03:10:38 +0000399/* Undo the effect of Py_Initialize().
400
401 Beware: if multiple interpreter and/or thread states exist, these
402 are not wiped out; only the current thread and interpreter state
403 are deleted. But since everything else is deleted, those other
404 interpreter and thread states should no longer be used.
405
406 (XXX We should do better, e.g. wipe out all interpreters and
407 threads.)
408
409 Locking: as above.
410
411*/
412
413void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000414Py_Finalize(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 PyInterpreterState *interp;
417 PyThreadState *tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (!initialized)
420 return;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 wait_for_thread_shutdown();
Antoine Pitrou011bd622009-10-20 21:52:47 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 /* The interpreter is still entirely intact at this point, and the
425 * exit funcs may be relying on that. In particular, if some thread
426 * or exit func is still waiting to do an import, the import machinery
427 * expects Py_IsInitialized() to return true. So don't say the
428 * interpreter is uninitialized until after the exit funcs have run.
429 * Note that Threading.py uses an exit func to do a join on all the
430 * threads created thru it, so this also protects pending imports in
431 * the threads created via Threading.
432 */
433 call_py_exitfuncs();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 /* Get current thread state and interpreter pointer */
436 tstate = PyThreadState_GET();
437 interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000438
Antoine Pitrou0d5e52d2011-05-04 20:02:30 +0200439 /* Remaining threads (e.g. daemon threads) will automatically exit
440 after taking the GIL (in PyEval_RestoreThread()). */
441 _Py_Finalizing = tstate;
442 initialized = 0;
443
444 /* Flush stdout+stderr */
445 flush_std_files();
446
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 /* Disable signal handling */
448 PyOS_FiniInterrupts();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 /* Clear type lookup cache */
451 PyType_ClearCache();
Christian Heimes26855632008-01-27 23:50:43 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 /* Collect garbage. This may call finalizers; it's nice to call these
454 * before all modules are destroyed.
455 * XXX If a __del__ or weakref callback is triggered here, and tries to
456 * XXX import a module, bad things can happen, because Python no
457 * XXX longer believes it's initialized.
458 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
459 * XXX is easy to provoke that way. I've also seen, e.g.,
460 * XXX Exception exceptions.ImportError: 'No module named sha'
461 * XXX in <function callback at 0x008F5718> ignored
462 * XXX but I'm unclear on exactly how that one happens. In any case,
463 * XXX I haven't seen a real-life report of either of these.
464 */
465 PyGC_Collect();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000466#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 /* With COUNT_ALLOCS, it helps to run GC multiple times:
468 each collection might release some types from the type
469 list, so they become garbage. */
470 while (PyGC_Collect() > 0)
471 /* nothing */;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000472#endif
Antoine Pitrou696e0352010-08-08 22:18:46 +0000473 /* We run this while most interpreter state is still alive, so that
474 debug information can be printed out */
475 _PyGC_Fini();
Guido van Rossume13ddc92003-04-17 17:29:22 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 /* Destroy all modules */
478 PyImport_Cleanup();
Guido van Rossum3a44e1b1997-11-03 21:58:47 +0000479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 /* Flush stdout+stderr (again, in case more was printed) */
481 flush_std_files();
Guido van Rossume8432ac2007-07-09 15:04:50 +0000482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 /* Collect final garbage. This disposes of cycles created by
Florent Xiclunaaa6c1d22011-12-12 18:54:29 +0100484 * class definitions, for example.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 * XXX This is disabled because it caused too many problems. If
486 * XXX a __del__ or weakref callback triggers here, Python code has
487 * XXX a hard time running, because even the sys module has been
488 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
489 * XXX One symptom is a sequence of information-free messages
490 * XXX coming from threads (if a __del__ or callback is invoked,
491 * XXX other threads can execute too, and any exception they encounter
492 * XXX triggers a comedy of errors as subsystem after subsystem
493 * XXX fails to find what it *expects* to find in sys to help report
494 * XXX the exception and consequent unexpected failures). I've also
495 * XXX seen segfaults then, after adding print statements to the
496 * XXX Python code getting called.
497 */
Tim Peters1d7323e2003-12-01 21:35:27 +0000498#if 0
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 PyGC_Collect();
Tim Peters1d7323e2003-12-01 21:35:27 +0000500#endif
Guido van Rossume13ddc92003-04-17 17:29:22 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
503 _PyImport_Fini();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000504
Victor Stinner024e37a2011-03-31 01:31:06 +0200505 /* unload faulthandler module */
506 _PyFaulthandler_Fini();
507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 /* Debugging stuff */
Guido van Rossum1707aad1997-12-08 23:43:45 +0000509#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 dump_counts(stdout);
Guido van Rossum1707aad1997-12-08 23:43:45 +0000511#endif
512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 PRINT_TOTAL_REFS();
Guido van Rossum1707aad1997-12-08 23:43:45 +0000514
Tim Peters9cf25ce2003-04-17 15:21:01 +0000515#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 /* Display all objects still alive -- this can invoke arbitrary
517 * __repr__ overrides, so requires a mostly-intact interpreter.
518 * Alas, a lot of stuff may still be alive now that will be cleaned
519 * up later.
520 */
521 if (Py_GETENV("PYTHONDUMPREFS"))
522 _Py_PrintReferences(stderr);
Tim Peters9cf25ce2003-04-17 15:21:01 +0000523#endif /* Py_TRACE_REFS */
524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 /* Clear interpreter state */
526 PyInterpreterState_Clear(interp);
Guido van Rossumd922fa42003-04-15 14:10:09 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 /* Now we decref the exception classes. After this point nothing
529 can raise an exception. That's okay, because each Fini() method
530 below has been checked to make sure no exceptions are ever
531 raised.
532 */
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 _PyExc_Fini();
Anthony Baxter12b6f6c2005-03-29 13:36:16 +0000535
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 /* Cleanup auto-thread-state */
Christian Heimes7d2ff882007-11-30 14:35:04 +0000537#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 _PyGILState_Fini();
Christian Heimes7d2ff882007-11-30 14:35:04 +0000539#endif /* WITH_THREAD */
540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 /* Delete current thread */
542 PyThreadState_Swap(NULL);
543 PyInterpreterState_Delete(interp);
Barry Warsawf242aa02000-05-25 23:09:49 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 /* Sundry finalizers */
546 PyMethod_Fini();
547 PyFrame_Fini();
548 PyCFunction_Fini();
549 PyTuple_Fini();
550 PyList_Fini();
551 PySet_Fini();
552 PyBytes_Fini();
553 PyByteArray_Fini();
554 PyLong_Fini();
555 PyFloat_Fini();
556 PyDict_Fini();
Antoine Pitrouf34a0cd2011-11-18 20:14:34 +0100557 PySlice_Fini();
Guido van Rossumcc283f51997-08-05 02:22:03 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 /* Cleanup Unicode implementation */
560 _PyUnicode_Fini();
Marc-André Lemburg95de5c12002-04-08 08:19:36 +0000561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 /* reset file system default encoding */
Victor Stinnerb744ba12010-05-15 12:27:16 +0000563 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 free((char*)Py_FileSystemDefaultEncoding);
565 Py_FileSystemDefaultEncoding = NULL;
566 }
Christian Heimesc8967002007-11-30 10:18:26 +0000567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 /* XXX Still allocated:
569 - various static ad-hoc pointers to interned strings
570 - int and float free list blocks
571 - whatever various modules and libraries allocate
572 */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
Guido van Rossumcc283f51997-08-05 02:22:03 +0000575
Tim Peters269b2a62003-04-17 19:52:29 +0000576#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 /* Display addresses (& refcnts) of all objects still alive.
578 * An address can be used to find the repr of the object, printed
579 * above by _Py_PrintReferences.
580 */
581 if (Py_GETENV("PYTHONDUMPREFS"))
582 _Py_PrintReferenceAddresses(stderr);
Tim Peters269b2a62003-04-17 19:52:29 +0000583#endif /* Py_TRACE_REFS */
Tim Peters0e871182002-04-13 08:29:14 +0000584#ifdef PYMALLOC_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 if (Py_GETENV("PYTHONMALLOCSTATS"))
586 _PyObject_DebugMallocStats();
Tim Peters0e871182002-04-13 08:29:14 +0000587#endif
588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 call_ll_exitfuncs();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000590}
591
592/* Create and initialize a new interpreter and thread, and return the
593 new thread. This requires that Py_Initialize() has been called
594 first.
595
596 Unsuccessful initialization yields a NULL pointer. Note that *no*
597 exception information is available even in this case -- the
598 exception information is held in the thread, and there is no
599 thread.
600
601 Locking: as above.
602
603*/
604
605PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000606Py_NewInterpreter(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 PyInterpreterState *interp;
609 PyThreadState *tstate, *save_tstate;
610 PyObject *bimod, *sysmod;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (!initialized)
613 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 interp = PyInterpreterState_New();
616 if (interp == NULL)
617 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 tstate = PyThreadState_New(interp);
620 if (tstate == NULL) {
621 PyInterpreterState_Delete(interp);
622 return NULL;
623 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 save_tstate = PyThreadState_Swap(tstate);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 /* XXX The following is lax in error checking */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000628
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 interp->modules = PyDict_New();
630 interp->modules_reloading = PyDict_New();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000631
Victor Stinner49d3f252010-10-17 01:24:53 +0000632 bimod = _PyImport_FindBuiltin("builtins");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 if (bimod != NULL) {
634 interp->builtins = PyModule_GetDict(bimod);
635 if (interp->builtins == NULL)
636 goto handle_error;
637 Py_INCREF(interp->builtins);
638 }
Christian Heimes6a27efa2008-10-30 21:48:26 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 /* initialize builtin exceptions */
641 _PyExc_Init();
Christian Heimes6a27efa2008-10-30 21:48:26 +0000642
Victor Stinner49d3f252010-10-17 01:24:53 +0000643 sysmod = _PyImport_FindBuiltin("sys");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if (bimod != NULL && sysmod != NULL) {
645 PyObject *pstderr;
646 interp->sysdict = PyModule_GetDict(sysmod);
647 if (interp->sysdict == NULL)
648 goto handle_error;
649 Py_INCREF(interp->sysdict);
650 PySys_SetPath(Py_GetPath());
651 PyDict_SetItemString(interp->sysdict, "modules",
652 interp->modules);
653 /* Set up a preliminary stderr printer until we have enough
654 infrastructure for the io module in place. */
655 pstderr = PyFile_NewStdPrinter(fileno(stderr));
656 if (pstderr == NULL)
657 Py_FatalError("Py_Initialize: can't set preliminary stderr");
658 PySys_SetObject("stderr", pstderr);
659 PySys_SetObject("__stderr__", pstderr);
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +0000660 Py_DECREF(pstderr);
Christian Heimes6a27efa2008-10-30 21:48:26 +0000661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000662 _PyImportHooks_Init();
Victor Stinner793b5312011-04-27 00:24:21 +0200663
664 if (initfsencoding(interp) < 0)
665 goto handle_error;
666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 if (initstdio() < 0)
668 Py_FatalError(
669 "Py_Initialize: can't initialize sys standard streams");
670 initmain();
671 if (!Py_NoSiteFlag)
672 initsite();
673 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000674
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 if (!PyErr_Occurred())
676 return tstate;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000677
Thomas Wouters89f507f2006-12-13 04:49:30 +0000678handle_error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 /* Oops, it didn't work. Undo it all. */
Guido van Rossum25ce5661997-08-02 03:10:38 +0000680
Victor Stinnerc40a3502011-04-27 00:20:27 +0200681 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000682 PyThreadState_Clear(tstate);
683 PyThreadState_Swap(save_tstate);
684 PyThreadState_Delete(tstate);
685 PyInterpreterState_Delete(interp);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000686
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000688}
689
690/* Delete an interpreter and its last thread. This requires that the
691 given thread state is current, that the thread has no remaining
692 frames, and that it is its interpreter's only remaining thread.
693 It is a fatal error to violate these constraints.
694
695 (Py_Finalize() doesn't have these constraints -- it zaps
696 everything, regardless.)
697
698 Locking: as above.
699
700*/
701
702void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000703Py_EndInterpreter(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 PyInterpreterState *interp = tstate->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (tstate != PyThreadState_GET())
708 Py_FatalError("Py_EndInterpreter: thread is not current");
709 if (tstate->frame != NULL)
710 Py_FatalError("Py_EndInterpreter: thread still has a frame");
711 if (tstate != interp->tstate_head || tstate->next != NULL)
712 Py_FatalError("Py_EndInterpreter: not the last thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 PyImport_Cleanup();
715 PyInterpreterState_Clear(interp);
716 PyThreadState_Swap(NULL);
717 PyInterpreterState_Delete(interp);
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000718}
719
Martin v. Löwis790465f2008-04-05 20:41:37 +0000720static wchar_t *progname = L"python";
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000721
722void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000723Py_SetProgramName(wchar_t *pn)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 if (pn && *pn)
726 progname = pn;
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000727}
728
Martin v. Löwis790465f2008-04-05 20:41:37 +0000729wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000730Py_GetProgramName(void)
Guido van Rossumad6dfda1997-07-19 19:17:22 +0000731{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 return progname;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000733}
734
Martin v. Löwis790465f2008-04-05 20:41:37 +0000735static wchar_t *default_home = NULL;
736static wchar_t env_home[PATH_MAX+1];
Guido van Rossuma61691e1998-02-06 22:27:24 +0000737
738void
Martin v. Löwis790465f2008-04-05 20:41:37 +0000739Py_SetPythonHome(wchar_t *home)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 default_home = home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000742}
743
Martin v. Löwis790465f2008-04-05 20:41:37 +0000744wchar_t *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000745Py_GetPythonHome(void)
Guido van Rossuma61691e1998-02-06 22:27:24 +0000746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 wchar_t *home = default_home;
748 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
749 char* chome = Py_GETENV("PYTHONHOME");
750 if (chome) {
751 size_t r = mbstowcs(env_home, chome, PATH_MAX+1);
752 if (r != (size_t)-1 && r <= PATH_MAX)
753 home = env_home;
754 }
Martin v. Löwis790465f2008-04-05 20:41:37 +0000755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 }
757 return home;
Guido van Rossuma61691e1998-02-06 22:27:24 +0000758}
759
Guido van Rossum6135a871995-01-09 17:53:26 +0000760/* Create __main__ module */
761
762static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000763initmain(void)
Guido van Rossum6135a871995-01-09 17:53:26 +0000764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 PyObject *m, *d;
766 m = PyImport_AddModule("__main__");
767 if (m == NULL)
768 Py_FatalError("can't create __main__ module");
769 d = PyModule_GetDict(m);
770 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
771 PyObject *bimod = PyImport_ImportModule("builtins");
772 if (bimod == NULL ||
773 PyDict_SetItemString(d, "__builtins__", bimod) != 0)
774 Py_FatalError("can't add __builtins__ to __main__");
775 Py_DECREF(bimod);
776 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000777}
778
Victor Stinner793b5312011-04-27 00:24:21 +0200779static int
780initfsencoding(PyInterpreterState *interp)
Victor Stinnerb744ba12010-05-15 12:27:16 +0000781{
782 PyObject *codec;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000783
Victor Stinnerd64e8a72011-07-04 13:48:30 +0200784 if (Py_FileSystemDefaultEncoding == NULL)
785 {
786 Py_FileSystemDefaultEncoding = get_locale_encoding();
787 if (Py_FileSystemDefaultEncoding == NULL)
Victor Stinnere4743092010-10-19 00:05:51 +0000788 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
Victor Stinnerb744ba12010-05-15 12:27:16 +0000789
Victor Stinnere4743092010-10-19 00:05:51 +0000790 Py_HasFileSystemDefaultEncoding = 0;
Victor Stinner793b5312011-04-27 00:24:21 +0200791 interp->fscodec_initialized = 1;
792 return 0;
Victor Stinner7f84ab52010-06-11 00:36:33 +0000793 }
Victor Stinnerb744ba12010-05-15 12:27:16 +0000794
795 /* the encoding is mbcs, utf-8 or ascii */
796 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
797 if (!codec) {
798 /* Such error can only occurs in critical situations: no more
799 * memory, import a module of the standard library failed,
800 * etc. */
Victor Stinner793b5312011-04-27 00:24:21 +0200801 return -1;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000802 }
Victor Stinner793b5312011-04-27 00:24:21 +0200803 Py_DECREF(codec);
804 interp->fscodec_initialized = 1;
805 return 0;
Victor Stinnerb744ba12010-05-15 12:27:16 +0000806}
807
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000808/* Import the site module (not into __main__ though) */
809
810static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000811initsite(void)
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 PyObject *m;
814 m = PyImport_ImportModule("site");
815 if (m == NULL) {
816 PyErr_Print();
817 Py_Finalize();
818 exit(1);
819 }
820 else {
821 Py_DECREF(m);
822 }
Guido van Rossumdcc0c131997-08-29 22:32:42 +0000823}
824
Antoine Pitrou05608432009-01-09 18:53:14 +0000825static PyObject*
826create_stdio(PyObject* io,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 int fd, int write_mode, char* name,
828 char* encoding, char* errors)
Antoine Pitrou05608432009-01-09 18:53:14 +0000829{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
831 const char* mode;
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000832 const char* newline;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 PyObject *line_buffering;
834 int buffering, isatty;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200835 _Py_IDENTIFIER(open);
836 _Py_IDENTIFIER(isatty);
837 _Py_IDENTIFIER(TextIOWrapper);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200838 _Py_IDENTIFIER(name);
839 _Py_IDENTIFIER(mode);
Antoine Pitrou05608432009-01-09 18:53:14 +0000840
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 /* stdin is always opened in buffered mode, first because it shouldn't
842 make a difference in common use cases, second because TextIOWrapper
843 depends on the presence of a read1() method which only exists on
844 buffered streams.
845 */
846 if (Py_UnbufferedStdioFlag && write_mode)
847 buffering = 0;
848 else
849 buffering = -1;
850 if (write_mode)
851 mode = "wb";
852 else
853 mode = "rb";
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200854 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
855 fd, mode, buffering,
856 Py_None, Py_None, Py_None, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 if (buf == NULL)
858 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000859
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 if (buffering) {
Martin v. Löwisbd928fe2011-10-14 10:20:37 +0200861 _Py_IDENTIFIER(raw);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200862 raw = _PyObject_GetAttrId(buf, &PyId_raw);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 if (raw == NULL)
864 goto error;
865 }
866 else {
867 raw = buf;
868 Py_INCREF(raw);
869 }
Antoine Pitrou05608432009-01-09 18:53:14 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 text = PyUnicode_FromString(name);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200872 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 goto error;
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200874 res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 if (res == NULL)
876 goto error;
877 isatty = PyObject_IsTrue(res);
878 Py_DECREF(res);
879 if (isatty == -1)
880 goto error;
881 if (isatty || Py_UnbufferedStdioFlag)
882 line_buffering = Py_True;
883 else
884 line_buffering = Py_False;
Antoine Pitrou91696412009-01-09 22:12:30 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 Py_CLEAR(raw);
887 Py_CLEAR(text);
Antoine Pitrou91696412009-01-09 22:12:30 +0000888
Victor Stinnerc0f1a1a2011-02-23 12:07:37 +0000889 newline = "\n";
890#ifdef MS_WINDOWS
891 if (!write_mode) {
892 /* translate \r\n to \n for sys.stdin on Windows */
893 newline = NULL;
894 }
895#endif
896
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200897 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
898 buf, encoding, errors,
899 newline, line_buffering);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 Py_CLEAR(buf);
901 if (stream == NULL)
902 goto error;
Antoine Pitrou05608432009-01-09 18:53:14 +0000903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 if (write_mode)
905 mode = "w";
906 else
907 mode = "r";
908 text = PyUnicode_FromString(mode);
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200909 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 goto error;
911 Py_CLEAR(text);
912 return stream;
Antoine Pitrou05608432009-01-09 18:53:14 +0000913
914error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 Py_XDECREF(buf);
916 Py_XDECREF(stream);
917 Py_XDECREF(text);
918 Py_XDECREF(raw);
919 return NULL;
Antoine Pitrou05608432009-01-09 18:53:14 +0000920}
921
Antoine Pitrou11942a52011-11-28 19:08:36 +0100922static int
923is_valid_fd(int fd)
924{
925 int dummy_fd;
926 if (fd < 0 || !_PyVerify_fd(fd))
927 return 0;
928 dummy_fd = dup(fd);
929 if (dummy_fd < 0)
930 return 0;
931 close(dummy_fd);
932 return 1;
933}
934
Georg Brandl1a3284e2007-12-02 09:40:06 +0000935/* Initialize sys.stdin, stdout, stderr and builtins.open */
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000936static int
937initstdio(void)
938{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 PyObject *iomod = NULL, *wrapper;
940 PyObject *bimod = NULL;
941 PyObject *m;
942 PyObject *std = NULL;
943 int status = 0, fd;
944 PyObject * encoding_attr;
945 char *encoding = NULL, *errors;
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 /* Hack to avoid a nasty recursion issue when Python is invoked
948 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
949 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
950 goto error;
951 }
952 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000953
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
955 goto error;
956 }
957 Py_DECREF(m);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000958
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959 if (!(bimod = PyImport_ImportModule("builtins"))) {
960 goto error;
961 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 if (!(iomod = PyImport_ImportModule("io"))) {
964 goto error;
965 }
966 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
967 goto error;
968 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* Set builtins.open */
971 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000972 Py_DECREF(wrapper);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 goto error;
974 }
Antoine Pitrou5a96b522010-11-20 19:50:57 +0000975 Py_DECREF(wrapper);
Guido van Rossumce3a72a2007-10-19 23:16:50 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 encoding = Py_GETENV("PYTHONIOENCODING");
978 errors = NULL;
979 if (encoding) {
980 encoding = strdup(encoding);
981 errors = strchr(encoding, ':');
982 if (errors) {
983 *errors = '\0';
984 errors++;
985 }
986 }
Martin v. Löwis0f599892008-06-02 11:13:03 +0000987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 /* Set sys.stdin */
989 fd = fileno(stdin);
990 /* Under some conditions stdin, stdout and stderr may not be connected
991 * and fileno() may point to an invalid file descriptor. For example
992 * GUI apps don't have valid standard streams by default.
993 */
Antoine Pitrou11942a52011-11-28 19:08:36 +0100994 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 std = Py_None;
996 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 }
998 else {
999 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1000 if (std == NULL)
1001 goto error;
1002 } /* if (fd < 0) */
1003 PySys_SetObject("__stdin__", std);
1004 PySys_SetObject("stdin", std);
1005 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 /* Set sys.stdout */
1008 fd = fileno(stdout);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001009 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 std = Py_None;
1011 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 }
1013 else {
1014 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1015 if (std == NULL)
1016 goto error;
1017 } /* if (fd < 0) */
1018 PySys_SetObject("__stdout__", std);
1019 PySys_SetObject("stdout", std);
1020 Py_DECREF(std);
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001021
Guido van Rossum98297ee2007-11-06 21:34:58 +00001022#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 /* Set sys.stderr, replaces the preliminary stderr */
1024 fd = fileno(stderr);
Antoine Pitrou11942a52011-11-28 19:08:36 +01001025 if (!is_valid_fd(fd)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 std = Py_None;
1027 Py_INCREF(std);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 }
1029 else {
1030 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1031 if (std == NULL)
1032 goto error;
1033 } /* if (fd < 0) */
Trent Nelson39e307e2008-03-19 06:45:48 +00001034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 /* Same as hack above, pre-import stderr's codec to avoid recursion
1036 when import.c tries to write to stderr in verbose mode. */
1037 encoding_attr = PyObject_GetAttrString(std, "encoding");
1038 if (encoding_attr != NULL) {
1039 const char * encoding;
1040 encoding = _PyUnicode_AsString(encoding_attr);
1041 if (encoding != NULL) {
Antoine Pitrou2fabfac2012-01-18 15:14:46 +01001042 PyObject *codec_info = _PyCodec_Lookup(encoding);
1043 Py_XDECREF(codec_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 }
Hirokazu Yamamotodaf83ac2010-10-30 15:08:15 +00001045 Py_DECREF(encoding_attr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 }
1047 PyErr_Clear(); /* Not a fatal error if codec isn't available */
Trent Nelson39e307e2008-03-19 06:45:48 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 PySys_SetObject("__stderr__", std);
1050 PySys_SetObject("stderr", std);
1051 Py_DECREF(std);
Guido van Rossum98297ee2007-11-06 21:34:58 +00001052#endif
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 if (0) {
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001055 error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 status = -1;
1057 }
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 if (encoding)
1060 free(encoding);
1061 Py_XDECREF(bimod);
1062 Py_XDECREF(iomod);
1063 return status;
Guido van Rossumce3a72a2007-10-19 23:16:50 +00001064}
1065
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001066/* Parse input from a file and execute it */
1067
1068int
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001069PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 if (filename == NULL)
1073 filename = "???";
1074 if (Py_FdIsInteractive(fp, filename)) {
1075 int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
1076 if (closeit)
1077 fclose(fp);
1078 return err;
1079 }
1080 else
1081 return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001082}
1083
1084int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001085PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 PyObject *v;
1088 int ret;
1089 PyCompilerFlags local_flags;
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 if (flags == NULL) {
1092 flags = &local_flags;
1093 local_flags.cf_flags = 0;
1094 }
1095 v = PySys_GetObject("ps1");
1096 if (v == NULL) {
1097 PySys_SetObject("ps1", v = PyUnicode_FromString(">>> "));
1098 Py_XDECREF(v);
1099 }
1100 v = PySys_GetObject("ps2");
1101 if (v == NULL) {
1102 PySys_SetObject("ps2", v = PyUnicode_FromString("... "));
1103 Py_XDECREF(v);
1104 }
1105 for (;;) {
1106 ret = PyRun_InteractiveOneFlags(fp, filename, flags);
1107 PRINT_TOTAL_REFS();
1108 if (ret == E_EOF)
1109 return 0;
1110 /*
1111 if (ret == E_NOMEM)
1112 return -1;
1113 */
1114 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001115}
1116
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001117/* compute parser flags based on compiler flags */
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001118static int PARSER_FLAGS(PyCompilerFlags *flags)
1119{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001120 int parser_flags = 0;
1121 if (!flags)
1122 return 0;
1123 if (flags->cf_flags & PyCF_DONT_IMPLY_DEDENT)
1124 parser_flags |= PyPARSE_DONT_IMPLY_DEDENT;
1125 if (flags->cf_flags & PyCF_IGNORE_COOKIE)
1126 parser_flags |= PyPARSE_IGNORE_COOKIE;
1127 if (flags->cf_flags & CO_FUTURE_BARRY_AS_BDFL)
1128 parser_flags |= PyPARSE_BARRY_AS_BDFL;
1129 return parser_flags;
Benjamin Petersonf5b52242009-03-02 23:31:26 +00001130}
Neil Schemenauerc24ea082002-03-22 23:53:36 +00001131
Thomas Wouters89f507f2006-12-13 04:49:30 +00001132#if 0
1133/* Keep an example of flags with future keyword support. */
1134#define PARSER_FLAGS(flags) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
1136 PyPARSE_DONT_IMPLY_DEDENT : 0) \
1137 | ((flags)->cf_flags & CO_FUTURE_WITH_STATEMENT ? \
1138 PyPARSE_WITH_IS_KEYWORD : 0)) : 0)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001139#endif
1140
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001141int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001142PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Jeremy Hylton9f324e92001-03-01 22:59:14 +00001143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 PyObject *m, *d, *v, *w, *oenc = NULL;
1145 mod_ty mod;
1146 PyArena *arena;
1147 char *ps1 = "", *ps2 = "", *enc = NULL;
1148 int errcode = 0;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001149 _Py_IDENTIFIER(encoding);
Tim Petersfe2127d2001-07-16 05:37:24 +00001150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 if (fp == stdin) {
1152 /* Fetch encoding from sys.stdin */
1153 v = PySys_GetObject("stdin");
1154 if (v == NULL || v == Py_None)
1155 return -1;
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001156 oenc = _PyObject_GetAttrId(v, &PyId_encoding);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 if (!oenc)
1158 return -1;
1159 enc = _PyUnicode_AsString(oenc);
Victor Stinner386fe712010-05-19 00:34:15 +00001160 if (enc == NULL)
1161 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 }
1163 v = PySys_GetObject("ps1");
1164 if (v != NULL) {
1165 v = PyObject_Str(v);
1166 if (v == NULL)
1167 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001168 else if (PyUnicode_Check(v)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 ps1 = _PyUnicode_AsString(v);
Victor Stinner386fe712010-05-19 00:34:15 +00001170 if (ps1 == NULL) {
1171 PyErr_Clear();
1172 ps1 = "";
1173 }
1174 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 }
1176 w = PySys_GetObject("ps2");
1177 if (w != NULL) {
1178 w = PyObject_Str(w);
1179 if (w == NULL)
1180 PyErr_Clear();
Victor Stinner386fe712010-05-19 00:34:15 +00001181 else if (PyUnicode_Check(w)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 ps2 = _PyUnicode_AsString(w);
Victor Stinner386fe712010-05-19 00:34:15 +00001183 if (ps2 == NULL) {
1184 PyErr_Clear();
1185 ps2 = "";
1186 }
1187 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 }
1189 arena = PyArena_New();
1190 if (arena == NULL) {
1191 Py_XDECREF(v);
1192 Py_XDECREF(w);
1193 Py_XDECREF(oenc);
1194 return -1;
1195 }
1196 mod = PyParser_ASTFromFile(fp, filename, enc,
1197 Py_single_input, ps1, ps2,
1198 flags, &errcode, arena);
1199 Py_XDECREF(v);
1200 Py_XDECREF(w);
1201 Py_XDECREF(oenc);
1202 if (mod == NULL) {
1203 PyArena_Free(arena);
1204 if (errcode == E_EOF) {
1205 PyErr_Clear();
1206 return E_EOF;
1207 }
1208 PyErr_Print();
1209 return -1;
1210 }
1211 m = PyImport_AddModule("__main__");
1212 if (m == NULL) {
1213 PyArena_Free(arena);
1214 return -1;
1215 }
1216 d = PyModule_GetDict(m);
1217 v = run_mod(mod, filename, d, d, flags, arena);
1218 PyArena_Free(arena);
1219 flush_io();
1220 if (v == NULL) {
1221 PyErr_Print();
1222 return -1;
1223 }
1224 Py_DECREF(v);
1225 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001226}
1227
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001228/* Check whether a file maybe a pyc file: Look at the extension,
1229 the file type, and, if we may close it, at the first few bytes. */
1230
1231static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001232maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
1235 return 1;
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 /* Only look into the file if we are allowed to close it, since
1238 it then should also be seekable. */
1239 if (closeit) {
1240 /* Read only two bytes of the magic. If the file was opened in
1241 text mode, the bytes 3 and 4 of the magic (\r\n) might not
1242 be read as they are on disk. */
1243 unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
1244 unsigned char buf[2];
1245 /* Mess: In case of -x, the stream is NOT at its start now,
1246 and ungetc() was used to push back the first newline,
1247 which makes the current stream position formally undefined,
1248 and a x-platform nightmare.
1249 Unfortunately, we have no direct way to know whether -x
1250 was specified. So we use a terrible hack: if the current
1251 stream position is not 0, we assume -x was specified, and
1252 give up. Bug 132850 on SourceForge spells out the
1253 hopelessness of trying anything else (fseek and ftell
1254 don't work predictably x-platform for text-mode files).
1255 */
1256 int ispyc = 0;
1257 if (ftell(fp) == 0) {
1258 if (fread(buf, 1, 2, fp) == 2 &&
1259 ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
1260 ispyc = 1;
1261 rewind(fp);
1262 }
1263 return ispyc;
1264 }
1265 return 0;
Tim Petersd08e3822003-04-17 15:24:21 +00001266}
Martin v. Löwisbe4c0f52001-01-04 20:30:56 +00001267
Guido van Rossum0df002c2000-08-27 19:21:52 +00001268int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001269PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 PyObject *m, *d, *v;
1273 const char *ext;
Victor Stinner0fcab4a2011-01-04 12:59:15 +00001274 int set_file_name = 0, ret;
1275 size_t len;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001277 m = PyImport_AddModule("__main__");
1278 if (m == NULL)
1279 return -1;
1280 d = PyModule_GetDict(m);
1281 if (PyDict_GetItemString(d, "__file__") == NULL) {
1282 PyObject *f;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00001283 f = PyUnicode_DecodeFSDefault(filename);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (f == NULL)
1285 return -1;
1286 if (PyDict_SetItemString(d, "__file__", f) < 0) {
1287 Py_DECREF(f);
1288 return -1;
1289 }
Barry Warsaw916048d2011-09-20 14:45:44 -04001290 if (PyDict_SetItemString(d, "__cached__", Py_None) < 0) {
1291 Py_DECREF(f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 return -1;
Barry Warsaw916048d2011-09-20 14:45:44 -04001293 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 set_file_name = 1;
1295 Py_DECREF(f);
1296 }
1297 len = strlen(filename);
1298 ext = filename + len - (len > 4 ? 4 : 0);
1299 if (maybe_pyc_file(fp, filename, ext, closeit)) {
1300 /* Try to run a pyc file. First, re-open in binary */
1301 if (closeit)
1302 fclose(fp);
1303 if ((fp = fopen(filename, "rb")) == NULL) {
1304 fprintf(stderr, "python: Can't reopen .pyc file\n");
1305 ret = -1;
1306 goto done;
1307 }
1308 /* Turn on optimization if a .pyo file is given */
1309 if (strcmp(ext, ".pyo") == 0)
1310 Py_OptimizeFlag = 1;
1311 v = run_pyc_file(fp, filename, d, d, flags);
1312 } else {
1313 v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
1314 closeit, flags);
1315 }
1316 flush_io();
1317 if (v == NULL) {
1318 PyErr_Print();
1319 ret = -1;
1320 goto done;
1321 }
1322 Py_DECREF(v);
1323 ret = 0;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001324 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 if (set_file_name && PyDict_DelItemString(d, "__file__"))
1326 PyErr_Clear();
1327 return ret;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001328}
1329
1330int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001331PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
Guido van Rossum393661d2001-08-31 17:40:15 +00001332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001333 PyObject *m, *d, *v;
1334 m = PyImport_AddModule("__main__");
1335 if (m == NULL)
1336 return -1;
1337 d = PyModule_GetDict(m);
1338 v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
1339 if (v == NULL) {
1340 PyErr_Print();
1341 return -1;
1342 }
1343 Py_DECREF(v);
1344 return 0;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001345}
1346
Barry Warsaw035574d1997-08-29 22:07:17 +00001347static int
Martin v. Löwis95292d62002-12-11 14:04:59 +00001348parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 int *lineno, int *offset, const char **text)
Barry Warsaw035574d1997-08-29 22:07:17 +00001350{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 long hold;
1352 PyObject *v;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001353 _Py_IDENTIFIER(msg);
1354 _Py_IDENTIFIER(filename);
1355 _Py_IDENTIFIER(lineno);
1356 _Py_IDENTIFIER(offset);
1357 _Py_IDENTIFIER(text);
Barry Warsaw035574d1997-08-29 22:07:17 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 /* new style errors. `err' is an instance */
Barry Warsaw035574d1997-08-29 22:07:17 +00001360
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001361 if (! (v = _PyObject_GetAttrId(err, &PyId_msg)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 goto finally;
1363 *message = v;
Barry Warsaw035574d1997-08-29 22:07:17 +00001364
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001365 if (!(v = _PyObject_GetAttrId(err, &PyId_filename)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 goto finally;
1367 if (v == Py_None)
1368 *filename = NULL;
1369 else if (! (*filename = _PyUnicode_AsString(v)))
1370 goto finally;
Barry Warsaw035574d1997-08-29 22:07:17 +00001371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001372 Py_DECREF(v);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001373 if (!(v = _PyObject_GetAttrId(err, &PyId_lineno)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 goto finally;
1375 hold = PyLong_AsLong(v);
1376 Py_DECREF(v);
1377 v = NULL;
1378 if (hold < 0 && PyErr_Occurred())
1379 goto finally;
1380 *lineno = (int)hold;
Barry Warsaw035574d1997-08-29 22:07:17 +00001381
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001382 if (!(v = _PyObject_GetAttrId(err, &PyId_offset)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 goto finally;
1384 if (v == Py_None) {
1385 *offset = -1;
1386 Py_DECREF(v);
1387 v = NULL;
1388 } else {
1389 hold = PyLong_AsLong(v);
1390 Py_DECREF(v);
1391 v = NULL;
1392 if (hold < 0 && PyErr_Occurred())
1393 goto finally;
1394 *offset = (int)hold;
1395 }
Barry Warsaw035574d1997-08-29 22:07:17 +00001396
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001397 if (!(v = _PyObject_GetAttrId(err, &PyId_text)))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 goto finally;
1399 if (v == Py_None)
1400 *text = NULL;
1401 else if (!PyUnicode_Check(v) ||
1402 !(*text = _PyUnicode_AsString(v)))
1403 goto finally;
1404 Py_DECREF(v);
1405 return 1;
Barry Warsaw035574d1997-08-29 22:07:17 +00001406
1407finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 Py_XDECREF(v);
1409 return 0;
Barry Warsaw035574d1997-08-29 22:07:17 +00001410}
1411
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001412void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001413PyErr_Print(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 PyErr_PrintEx(1);
Guido van Rossuma61691e1998-02-06 22:27:24 +00001416}
1417
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001418static void
Martin v. Löwis95292d62002-12-11 14:04:59 +00001419print_error_text(PyObject *f, int offset, const char *text)
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 char *nl;
1422 if (offset >= 0) {
Benjamin Petersona95e9772010-10-29 03:28:14 +00001423 if (offset > 0 && offset == strlen(text) && text[offset - 1] == '\n')
1424 offset--;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 for (;;) {
1426 nl = strchr(text, '\n');
1427 if (nl == NULL || nl-text >= offset)
1428 break;
1429 offset -= (int)(nl+1-text);
1430 text = nl+1;
1431 }
1432 while (*text == ' ' || *text == '\t') {
1433 text++;
1434 offset--;
1435 }
1436 }
1437 PyFile_WriteString(" ", f);
1438 PyFile_WriteString(text, f);
1439 if (*text == '\0' || text[strlen(text)-1] != '\n')
1440 PyFile_WriteString("\n", f);
1441 if (offset == -1)
1442 return;
1443 PyFile_WriteString(" ", f);
Benjamin Petersona95e9772010-10-29 03:28:14 +00001444 while (--offset > 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 PyFile_WriteString(" ", f);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 PyFile_WriteString("^\n", f);
Jeremy Hylton9f1b9932001-02-28 07:07:43 +00001447}
1448
Guido van Rossum66e8e862001-03-23 17:54:43 +00001449static void
1450handle_system_exit(void)
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001451{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 PyObject *exception, *value, *tb;
1453 int exitcode = 0;
Tim Peterscf615b52003-04-19 18:47:02 +00001454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 if (Py_InspectFlag)
1456 /* Don't exit if -i flag was given. This flag is set to 0
1457 * when entering interactive mode for inspecting. */
1458 return;
Guido van Rossumd8faa362007-04-27 19:54:29 +00001459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 PyErr_Fetch(&exception, &value, &tb);
1461 fflush(stdout);
1462 if (value == NULL || value == Py_None)
1463 goto done;
1464 if (PyExceptionInstance_Check(value)) {
1465 /* The error code should be in the `code' attribute. */
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001466 _Py_IDENTIFIER(code);
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001467 PyObject *code = _PyObject_GetAttrId(value, &PyId_code);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 if (code) {
1469 Py_DECREF(value);
1470 value = code;
1471 if (value == Py_None)
1472 goto done;
1473 }
1474 /* If we failed to dig out the 'code' attribute,
1475 just let the else clause below print the error. */
1476 }
1477 if (PyLong_Check(value))
1478 exitcode = (int)PyLong_AsLong(value);
1479 else {
Victor Stinnere9fb3192010-05-17 08:58:51 +00001480 PyObject *sys_stderr = PySys_GetObject("stderr");
Victor Stinner7126dbc2010-05-21 23:45:42 +00001481 if (sys_stderr != NULL && sys_stderr != Py_None) {
1482 PyFile_WriteObject(value, sys_stderr, Py_PRINT_RAW);
1483 } else {
1484 PyObject_Print(value, stderr, Py_PRINT_RAW);
1485 fflush(stderr);
1486 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 PySys_WriteStderr("\n");
1488 exitcode = 1;
1489 }
Tim Peterscf615b52003-04-19 18:47:02 +00001490 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001491 /* Restore and clear the exception info, in order to properly decref
1492 * the exception, value, and traceback. If we just exit instead,
1493 * these leak, which confuses PYTHONDUMPREFS output, and may prevent
1494 * some finalizers from running.
1495 */
1496 PyErr_Restore(exception, value, tb);
1497 PyErr_Clear();
1498 Py_Exit(exitcode);
1499 /* NOTREACHED */
Ka-Ping Yee26fabb02001-03-23 15:36:41 +00001500}
1501
1502void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001503PyErr_PrintEx(int set_sys_last_vars)
Guido van Rossuma61691e1998-02-06 22:27:24 +00001504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 PyObject *exception, *v, *tb, *hook;
Guido van Rossum66e8e862001-03-23 17:54:43 +00001506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1508 handle_system_exit();
1509 }
1510 PyErr_Fetch(&exception, &v, &tb);
1511 if (exception == NULL)
1512 return;
1513 PyErr_NormalizeException(&exception, &v, &tb);
1514 if (tb == NULL) {
1515 tb = Py_None;
1516 Py_INCREF(tb);
1517 }
1518 PyException_SetTraceback(v, tb);
1519 if (exception == NULL)
1520 return;
1521 /* Now we know v != NULL too */
1522 if (set_sys_last_vars) {
1523 PySys_SetObject("last_type", exception);
1524 PySys_SetObject("last_value", v);
1525 PySys_SetObject("last_traceback", tb);
1526 }
1527 hook = PySys_GetObject("excepthook");
1528 if (hook) {
1529 PyObject *args = PyTuple_Pack(3, exception, v, tb);
1530 PyObject *result = PyEval_CallObject(hook, args);
1531 if (result == NULL) {
1532 PyObject *exception2, *v2, *tb2;
1533 if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
1534 handle_system_exit();
1535 }
1536 PyErr_Fetch(&exception2, &v2, &tb2);
1537 PyErr_NormalizeException(&exception2, &v2, &tb2);
1538 /* It should not be possible for exception2 or v2
1539 to be NULL. However PyErr_Display() can't
1540 tolerate NULLs, so just be safe. */
1541 if (exception2 == NULL) {
1542 exception2 = Py_None;
1543 Py_INCREF(exception2);
1544 }
1545 if (v2 == NULL) {
1546 v2 = Py_None;
1547 Py_INCREF(v2);
1548 }
1549 fflush(stdout);
1550 PySys_WriteStderr("Error in sys.excepthook:\n");
1551 PyErr_Display(exception2, v2, tb2);
1552 PySys_WriteStderr("\nOriginal exception was:\n");
1553 PyErr_Display(exception, v, tb);
1554 Py_DECREF(exception2);
1555 Py_DECREF(v2);
1556 Py_XDECREF(tb2);
1557 }
1558 Py_XDECREF(result);
1559 Py_XDECREF(args);
1560 } else {
1561 PySys_WriteStderr("sys.excepthook is missing\n");
1562 PyErr_Display(exception, v, tb);
1563 }
1564 Py_XDECREF(exception);
1565 Py_XDECREF(v);
1566 Py_XDECREF(tb);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001567}
1568
Benjamin Petersone6528212008-07-15 15:32:09 +00001569static void
1570print_exception(PyObject *f, PyObject *value)
1571{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 int err = 0;
1573 PyObject *type, *tb;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001574 _Py_IDENTIFIER(print_file_and_line);
Benjamin Petersone6528212008-07-15 15:32:09 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 if (!PyExceptionInstance_Check(value)) {
1577 PyFile_WriteString("TypeError: print_exception(): Exception expected for value, ", f);
1578 PyFile_WriteString(Py_TYPE(value)->tp_name, f);
1579 PyFile_WriteString(" found\n", f);
1580 return;
1581 }
Benjamin Peterson26582602008-08-23 20:08:07 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 Py_INCREF(value);
1584 fflush(stdout);
1585 type = (PyObject *) Py_TYPE(value);
1586 tb = PyException_GetTraceback(value);
1587 if (tb && tb != Py_None)
1588 err = PyTraceBack_Print(tb, f);
1589 if (err == 0 &&
Martin v. Löwis1c67dd92011-10-14 15:16:45 +02001590 _PyObject_HasAttrId(value, &PyId_print_file_and_line))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 {
1592 PyObject *message;
1593 const char *filename, *text;
1594 int lineno, offset;
1595 if (!parse_syntax_error(value, &message, &filename,
1596 &lineno, &offset, &text))
1597 PyErr_Clear();
1598 else {
1599 char buf[10];
1600 PyFile_WriteString(" File \"", f);
1601 if (filename == NULL)
1602 PyFile_WriteString("<string>", f);
1603 else
1604 PyFile_WriteString(filename, f);
1605 PyFile_WriteString("\", line ", f);
1606 PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
1607 PyFile_WriteString(buf, f);
1608 PyFile_WriteString("\n", f);
1609 if (text != NULL)
1610 print_error_text(f, offset, text);
1611 Py_DECREF(value);
1612 value = message;
1613 /* Can't be bothered to check all those
1614 PyFile_WriteString() calls */
1615 if (PyErr_Occurred())
1616 err = -1;
1617 }
1618 }
1619 if (err) {
1620 /* Don't do anything else */
1621 }
1622 else {
1623 PyObject* moduleName;
1624 char* className;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001625 _Py_IDENTIFIER(__module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 assert(PyExceptionClass_Check(type));
1627 className = PyExceptionClass_Name(type);
1628 if (className != NULL) {
1629 char *dot = strrchr(className, '.');
1630 if (dot != NULL)
1631 className = dot+1;
1632 }
Benjamin Petersone6528212008-07-15 15:32:09 +00001633
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02001634 moduleName = _PyObject_GetAttrId(type, &PyId___module__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 if (moduleName == NULL || !PyUnicode_Check(moduleName))
1636 {
Victor Stinner13b21bd2011-05-26 14:25:13 +02001637 Py_XDECREF(moduleName);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 err = PyFile_WriteString("<unknown>", f);
1639 }
1640 else {
1641 char* modstr = _PyUnicode_AsString(moduleName);
1642 if (modstr && strcmp(modstr, "builtins"))
1643 {
1644 err = PyFile_WriteString(modstr, f);
1645 err += PyFile_WriteString(".", f);
1646 }
1647 Py_DECREF(moduleName);
1648 }
1649 if (err == 0) {
1650 if (className == NULL)
1651 err = PyFile_WriteString("<unknown>", f);
1652 else
1653 err = PyFile_WriteString(className, f);
1654 }
1655 }
1656 if (err == 0 && (value != Py_None)) {
1657 PyObject *s = PyObject_Str(value);
1658 /* only print colon if the str() of the
1659 object is not the empty string
1660 */
1661 if (s == NULL)
1662 err = -1;
1663 else if (!PyUnicode_Check(s) ||
Victor Stinnere251d6d2011-11-20 19:20:00 +01001664 PyUnicode_GetLength(s) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 err = PyFile_WriteString(": ", f);
1666 if (err == 0)
1667 err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
1668 Py_XDECREF(s);
1669 }
1670 /* try to write a newline in any case */
1671 err += PyFile_WriteString("\n", f);
1672 Py_XDECREF(tb);
1673 Py_DECREF(value);
1674 /* If an error happened here, don't show it.
1675 XXX This is wrong, but too many callers rely on this behavior. */
1676 if (err != 0)
1677 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001678}
1679
1680static const char *cause_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 "\nThe above exception was the direct cause "
1682 "of the following exception:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001683
1684static const char *context_message =
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 "\nDuring handling of the above exception, "
1686 "another exception occurred:\n\n";
Benjamin Petersone6528212008-07-15 15:32:09 +00001687
1688static void
1689print_exception_recursive(PyObject *f, PyObject *value, PyObject *seen)
1690{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 int err = 0, res;
1692 PyObject *cause, *context;
Benjamin Petersone6528212008-07-15 15:32:09 +00001693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 if (seen != NULL) {
1695 /* Exception chaining */
1696 if (PySet_Add(seen, value) == -1)
1697 PyErr_Clear();
1698 else if (PyExceptionInstance_Check(value)) {
1699 cause = PyException_GetCause(value);
1700 context = PyException_GetContext(value);
Nick Coghlanab7bf212012-02-26 17:49:52 +10001701 if (cause && cause == Py_None) {
1702 /* print neither cause nor context */
1703 ;
1704 }
1705 else if (cause) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 res = PySet_Contains(seen, cause);
1707 if (res == -1)
1708 PyErr_Clear();
1709 if (res == 0) {
1710 print_exception_recursive(
1711 f, cause, seen);
1712 err |= PyFile_WriteString(
1713 cause_message, f);
1714 }
1715 }
1716 else if (context) {
1717 res = PySet_Contains(seen, context);
1718 if (res == -1)
1719 PyErr_Clear();
1720 if (res == 0) {
1721 print_exception_recursive(
1722 f, context, seen);
1723 err |= PyFile_WriteString(
1724 context_message, f);
1725 }
1726 }
1727 Py_XDECREF(context);
1728 Py_XDECREF(cause);
1729 }
1730 }
1731 print_exception(f, value);
1732 if (err != 0)
1733 PyErr_Clear();
Benjamin Petersone6528212008-07-15 15:32:09 +00001734}
1735
Thomas Wouters477c8d52006-05-27 19:21:47 +00001736void
1737PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 PyObject *seen;
1740 PyObject *f = PySys_GetObject("stderr");
1741 if (f == Py_None) {
1742 /* pass */
1743 }
1744 else if (f == NULL) {
1745 _PyObject_Dump(value);
1746 fprintf(stderr, "lost sys.stderr\n");
1747 }
1748 else {
1749 /* We choose to ignore seen being possibly NULL, and report
1750 at least the main exception (it could be a MemoryError).
1751 */
1752 seen = PySet_New(NULL);
1753 if (seen == NULL)
1754 PyErr_Clear();
1755 print_exception_recursive(f, value, seen);
1756 Py_XDECREF(seen);
1757 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001758}
1759
Guido van Rossum82598051997-03-05 00:20:32 +00001760PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001761PyRun_StringFlags(const char *str, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 PyObject *ret = NULL;
1765 mod_ty mod;
1766 PyArena *arena = PyArena_New();
1767 if (arena == NULL)
1768 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
1771 if (mod != NULL)
1772 ret = run_mod(mod, "<string>", globals, locals, flags, arena);
1773 PyArena_Free(arena);
1774 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001775}
1776
1777PyObject *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001778PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 PyObject *locals, int closeit, PyCompilerFlags *flags)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 PyObject *ret;
1782 mod_ty mod;
1783 PyArena *arena = PyArena_New();
1784 if (arena == NULL)
1785 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 mod = PyParser_ASTFromFile(fp, filename, NULL, start, 0, 0,
1788 flags, NULL, arena);
1789 if (closeit)
1790 fclose(fp);
1791 if (mod == NULL) {
1792 PyArena_Free(arena);
1793 return NULL;
1794 }
1795 ret = run_mod(mod, filename, globals, locals, flags, arena);
1796 PyArena_Free(arena);
1797 return ret;
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001798}
1799
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001800static void
1801flush_io(void)
1802{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 PyObject *f, *r;
1804 PyObject *type, *value, *traceback;
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02001805 _Py_IDENTIFIER(flush);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 /* Save the current exception */
1808 PyErr_Fetch(&type, &value, &traceback);
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 f = PySys_GetObject("stderr");
1811 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001812 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 if (r)
1814 Py_DECREF(r);
1815 else
1816 PyErr_Clear();
1817 }
1818 f = PySys_GetObject("stdout");
1819 if (f != NULL) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02001820 r = _PyObject_CallMethodId(f, &PyId_flush, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 if (r)
1822 Py_DECREF(r);
1823 else
1824 PyErr_Clear();
1825 }
Amaury Forgeot d'Arc9ed77352008-04-04 23:25:27 +00001826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 PyErr_Restore(type, value, traceback);
Guido van Rossum6c193fa2007-12-05 05:14:58 +00001828}
1829
Guido van Rossum82598051997-03-05 00:20:32 +00001830static PyObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001831run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 PyCompilerFlags *flags, PyArena *arena)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 PyCodeObject *co;
1835 PyObject *v;
1836 co = PyAST_Compile(mod, filename, flags, arena);
1837 if (co == NULL)
1838 return NULL;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001839 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 Py_DECREF(co);
1841 return v;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001842}
1843
Guido van Rossum82598051997-03-05 00:20:32 +00001844static PyObject *
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001845run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 PyObject *locals, PyCompilerFlags *flags)
Guido van Rossumfdef2711994-09-14 13:31:04 +00001847{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 PyCodeObject *co;
1849 PyObject *v;
1850 long magic;
1851 long PyImport_GetMagicNumber(void);
Guido van Rossumfdef2711994-09-14 13:31:04 +00001852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 magic = PyMarshal_ReadLongFromFile(fp);
1854 if (magic != PyImport_GetMagicNumber()) {
1855 PyErr_SetString(PyExc_RuntimeError,
1856 "Bad magic number in .pyc file");
1857 return NULL;
1858 }
Antoine Pitrou5136ac02012-01-13 18:52:16 +01001859 /* Skip mtime and size */
1860 (void) PyMarshal_ReadLongFromFile(fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 (void) PyMarshal_ReadLongFromFile(fp);
1862 v = PyMarshal_ReadLastObjectFromFile(fp);
1863 fclose(fp);
1864 if (v == NULL || !PyCode_Check(v)) {
1865 Py_XDECREF(v);
1866 PyErr_SetString(PyExc_RuntimeError,
1867 "Bad code object in .pyc file");
1868 return NULL;
1869 }
1870 co = (PyCodeObject *)v;
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001871 v = PyEval_EvalCode((PyObject*)co, globals, locals);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 if (v && flags)
1873 flags->cf_flags |= (co->co_flags & PyCF_MASK);
1874 Py_DECREF(co);
1875 return v;
Guido van Rossumfdef2711994-09-14 13:31:04 +00001876}
1877
Guido van Rossum82598051997-03-05 00:20:32 +00001878PyObject *
Georg Brandl8334fd92010-12-04 10:26:46 +00001879Py_CompileStringExFlags(const char *str, const char *filename, int start,
1880 PyCompilerFlags *flags, int optimize)
Jeremy Hyltonbc320242001-03-22 02:47:58 +00001881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 PyCodeObject *co;
1883 mod_ty mod;
1884 PyArena *arena = PyArena_New();
1885 if (arena == NULL)
1886 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 mod = PyParser_ASTFromString(str, filename, start, flags, arena);
1889 if (mod == NULL) {
1890 PyArena_Free(arena);
1891 return NULL;
1892 }
1893 if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
1894 PyObject *result = PyAST_mod2obj(mod);
1895 PyArena_Free(arena);
1896 return result;
1897 }
Georg Brandl8334fd92010-12-04 10:26:46 +00001898 co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 PyArena_Free(arena);
1900 return (PyObject *)co;
Guido van Rossum5b722181993-03-30 17:46:03 +00001901}
1902
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001903/* For use in Py_LIMITED_API */
1904#undef Py_CompileString
1905PyObject *
1906PyCompileString(const char *str, const char *filename, int start)
1907{
1908 return Py_CompileStringFlags(str, filename, start, NULL);
1909}
1910
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001911struct symtable *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001912Py_SymtableString(const char *str, const char *filename, int start)
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 struct symtable *st;
1915 mod_ty mod;
1916 PyCompilerFlags flags;
1917 PyArena *arena = PyArena_New();
1918 if (arena == NULL)
1919 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 flags.cf_flags = 0;
1922 mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
1923 if (mod == NULL) {
1924 PyArena_Free(arena);
1925 return NULL;
1926 }
1927 st = PySymtable_Build(mod, filename, 0);
1928 PyArena_Free(arena);
1929 return st;
Jeremy Hylton4b38da62001-02-02 18:19:15 +00001930}
1931
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001932/* Preferred access to parser is through AST. */
1933mod_ty
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001934PyParser_ASTFromString(const char *s, const char *filename, int start,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 PyCompilerFlags *flags, PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001936{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 mod_ty mod;
1938 PyCompilerFlags localflags;
1939 perrdetail err;
1940 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
1943 &_PyParser_Grammar, start, &err,
1944 &iflags);
1945 if (flags == NULL) {
1946 localflags.cf_flags = 0;
1947 flags = &localflags;
1948 }
1949 if (n) {
1950 flags->cf_flags |= iflags & PyCF_MASK;
1951 mod = PyAST_FromNode(n, flags, filename, arena);
1952 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 }
1954 else {
1955 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02001956 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001958 err_free(&err);
1959 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001960}
1961
1962mod_ty
Martin v. Löwis85bcc662007-09-04 09:18:06 +00001963PyParser_ASTFromFile(FILE *fp, const char *filename, const char* enc,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 int start, char *ps1,
1965 char *ps2, PyCompilerFlags *flags, int *errcode,
1966 PyArena *arena)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001967{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 mod_ty mod;
1969 PyCompilerFlags localflags;
1970 perrdetail err;
1971 int iflags = PARSER_FLAGS(flags);
Christian Heimes4d6ec852008-03-26 22:34:47 +00001972
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 node *n = PyParser_ParseFileFlagsEx(fp, filename, enc,
1974 &_PyParser_Grammar,
1975 start, ps1, ps2, &err, &iflags);
1976 if (flags == NULL) {
1977 localflags.cf_flags = 0;
1978 flags = &localflags;
1979 }
1980 if (n) {
1981 flags->cf_flags |= iflags & PyCF_MASK;
1982 mod = PyAST_FromNode(n, flags, filename, arena);
1983 PyNode_Free(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 }
1985 else {
1986 err_input(&err);
1987 if (errcode)
1988 *errcode = err.error;
Victor Stinner7f2fee32011-04-05 00:39:01 +02001989 mod = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02001991 err_free(&err);
1992 return mod;
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001993}
1994
Guido van Rossuma110aa61994-08-29 12:50:44 +00001995/* Simplified interface to parsefile -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001996
Guido van Rossuma110aa61994-08-29 12:50:44 +00001997node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00001998PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 perrdetail err;
2001 node *n = PyParser_ParseFileFlags(fp, filename, NULL,
2002 &_PyParser_Grammar,
2003 start, NULL, NULL, &err, flags);
2004 if (n == NULL)
2005 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002006 err_free(&err);
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 return n;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002009}
2010
Guido van Rossuma110aa61994-08-29 12:50:44 +00002011/* Simplified interface to parsestring -- return node or set exception */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002012
Guido van Rossuma110aa61994-08-29 12:50:44 +00002013node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002014PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
Tim Petersfe2127d2001-07-16 05:37:24 +00002015{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 perrdetail err;
2017 node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
2018 start, &err, flags);
2019 if (n == NULL)
2020 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002021 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 return n;
Tim Petersfe2127d2001-07-16 05:37:24 +00002023}
2024
2025node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002026PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 int start, int flags)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002028{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 perrdetail err;
2030 node *n = PyParser_ParseStringFlagsFilename(str, filename,
2031 &_PyParser_Grammar, start, &err, flags);
2032 if (n == NULL)
2033 err_input(&err);
Victor Stinner7f2fee32011-04-05 00:39:01 +02002034 err_free(&err);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 return n;
Thomas Heller6b17abf2002-07-09 09:23:27 +00002036}
2037
2038node *
Martin v. Löwis95292d62002-12-11 14:04:59 +00002039PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
Thomas Heller6b17abf2002-07-09 09:23:27 +00002040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
Thomas Heller6b17abf2002-07-09 09:23:27 +00002042}
2043
Guido van Rossum66ebd912003-04-17 16:02:26 +00002044/* May want to move a more generalized form of this to parsetok.c or
2045 even parser modules. */
2046
2047void
Victor Stinner7f2fee32011-04-05 00:39:01 +02002048PyParser_ClearError(perrdetail *err)
2049{
2050 err_free(err);
2051}
2052
2053void
Guido van Rossum66ebd912003-04-17 16:02:26 +00002054PyParser_SetError(perrdetail *err)
2055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 err_input(err);
Guido van Rossum66ebd912003-04-17 16:02:26 +00002057}
2058
Victor Stinner7f2fee32011-04-05 00:39:01 +02002059static void
2060err_free(perrdetail *err)
2061{
2062 Py_CLEAR(err->filename);
2063}
2064
Guido van Rossuma110aa61994-08-29 12:50:44 +00002065/* Set the error appropriate to the given input error code (see errcode.h) */
2066
2067static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002068err_input(perrdetail *err)
Guido van Rossuma110aa61994-08-29 12:50:44 +00002069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 PyObject *v, *w, *errtype, *errtext;
2071 PyObject *msg_obj = NULL;
2072 char *msg = NULL;
Victor Stinner4c7c8c32010-10-16 13:14:10 +00002073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 errtype = PyExc_SyntaxError;
2075 switch (err->error) {
2076 case E_ERROR:
2077 return;
2078 case E_SYNTAX:
2079 errtype = PyExc_IndentationError;
2080 if (err->expected == INDENT)
2081 msg = "expected an indented block";
2082 else if (err->token == INDENT)
2083 msg = "unexpected indent";
2084 else if (err->token == DEDENT)
2085 msg = "unexpected unindent";
2086 else {
2087 errtype = PyExc_SyntaxError;
2088 msg = "invalid syntax";
2089 }
2090 break;
2091 case E_TOKEN:
2092 msg = "invalid token";
2093 break;
2094 case E_EOFS:
2095 msg = "EOF while scanning triple-quoted string literal";
2096 break;
2097 case E_EOLS:
2098 msg = "EOL while scanning string literal";
2099 break;
2100 case E_INTR:
2101 if (!PyErr_Occurred())
2102 PyErr_SetNone(PyExc_KeyboardInterrupt);
2103 goto cleanup;
2104 case E_NOMEM:
2105 PyErr_NoMemory();
2106 goto cleanup;
2107 case E_EOF:
2108 msg = "unexpected EOF while parsing";
2109 break;
2110 case E_TABSPACE:
2111 errtype = PyExc_TabError;
2112 msg = "inconsistent use of tabs and spaces in indentation";
2113 break;
2114 case E_OVERFLOW:
2115 msg = "expression too long";
2116 break;
2117 case E_DEDENT:
2118 errtype = PyExc_IndentationError;
2119 msg = "unindent does not match any outer indentation level";
2120 break;
2121 case E_TOODEEP:
2122 errtype = PyExc_IndentationError;
2123 msg = "too many levels of indentation";
2124 break;
2125 case E_DECODE: {
2126 PyObject *type, *value, *tb;
2127 PyErr_Fetch(&type, &value, &tb);
2128 msg = "unknown decode error";
2129 if (value != NULL)
2130 msg_obj = PyObject_Str(value);
2131 Py_XDECREF(type);
2132 Py_XDECREF(value);
2133 Py_XDECREF(tb);
2134 break;
2135 }
2136 case E_LINECONT:
2137 msg = "unexpected character after line continuation character";
2138 break;
Martin v. Löwis47383402007-08-15 07:32:56 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 case E_IDENTIFIER:
2141 msg = "invalid character in identifier";
2142 break;
Meador Ingefa21bf02012-01-19 01:08:41 -06002143 case E_BADSINGLE:
2144 msg = "multiple statements found while compiling a single statement";
2145 break;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 default:
2147 fprintf(stderr, "error=%d\n", err->error);
2148 msg = "unknown parsing error";
2149 break;
2150 }
2151 /* err->text may not be UTF-8 in case of decoding errors.
2152 Explicitly convert to an object. */
2153 if (!err->text) {
2154 errtext = Py_None;
2155 Py_INCREF(Py_None);
2156 } else {
2157 errtext = PyUnicode_DecodeUTF8(err->text, strlen(err->text),
2158 "replace");
2159 }
Victor Stinner7f2fee32011-04-05 00:39:01 +02002160 v = Py_BuildValue("(OiiN)", err->filename,
2161 err->lineno, err->offset, errtext);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 if (v != NULL) {
2163 if (msg_obj)
2164 w = Py_BuildValue("(OO)", msg_obj, v);
2165 else
2166 w = Py_BuildValue("(sO)", msg, v);
2167 } else
2168 w = NULL;
2169 Py_XDECREF(v);
2170 PyErr_SetObject(errtype, w);
2171 Py_XDECREF(w);
Georg Brandl3dbca812008-07-23 16:10:53 +00002172cleanup:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 Py_XDECREF(msg_obj);
2174 if (err->text != NULL) {
2175 PyObject_FREE(err->text);
2176 err->text = NULL;
2177 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002178}
2179
2180/* Print fatal error message and abort */
2181
2182void
Tim Peters7c321a82002-07-09 02:57:01 +00002183Py_FatalError(const char *msg)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002184{
Victor Stinner024e37a2011-03-31 01:31:06 +02002185 const int fd = fileno(stderr);
2186 PyThreadState *tstate;
2187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002188 fprintf(stderr, "Fatal Python error: %s\n", msg);
2189 fflush(stderr); /* it helps in Windows debug build */
2190 if (PyErr_Occurred()) {
Victor Stinner55a5c782010-06-08 21:00:13 +00002191 PyErr_PrintEx(0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 }
Victor Stinner024e37a2011-03-31 01:31:06 +02002193 else {
2194 tstate = _Py_atomic_load_relaxed(&_PyThreadState_Current);
2195 if (tstate != NULL) {
2196 fputc('\n', stderr);
2197 fflush(stderr);
Victor Stinner7bba62f2011-05-07 12:43:00 +02002198 _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
Victor Stinner024e37a2011-03-31 01:31:06 +02002199 }
Victor Stinnerd727e232011-04-01 12:13:55 +02002200 _PyFaulthandler_Fini();
Victor Stinner024e37a2011-03-31 01:31:06 +02002201 }
2202
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002203#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 {
2205 size_t len = strlen(msg);
2206 WCHAR* buffer;
2207 size_t i;
Martin v. Löwis5c88d812009-01-02 20:47:48 +00002208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 /* Convert the message to wchar_t. This uses a simple one-to-one
2210 conversion, assuming that the this error message actually uses ASCII
2211 only. If this ceases to be true, we will have to convert. */
2212 buffer = alloca( (len+1) * (sizeof *buffer));
2213 for( i=0; i<=len; ++i)
2214 buffer[i] = msg[i];
2215 OutputDebugStringW(L"Fatal Python error: ");
2216 OutputDebugStringW(buffer);
2217 OutputDebugStringW(L"\n");
2218 }
Guido van Rossum0ba35361998-08-13 13:33:16 +00002219#ifdef _DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 DebugBreak();
Guido van Rossuma44823b1995-03-14 15:01:17 +00002221#endif
Martin v. Löwis6238d2b2002-06-30 15:26:10 +00002222#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 abort();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002224}
2225
2226/* Clean up and exit */
2227
Guido van Rossuma110aa61994-08-29 12:50:44 +00002228#ifdef WITH_THREAD
Guido van Rossum49b56061998-10-01 20:42:43 +00002229#include "pythread.h"
Guido van Rossumf9f2e821992-08-17 08:59:08 +00002230#endif
2231
Collin Winter670e6922007-03-21 02:57:17 +00002232static void (*pyexitfunc)(void) = NULL;
2233/* For the atexit module. */
2234void _Py_PyAtExit(void (*func)(void))
2235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 pyexitfunc = func;
Collin Winter670e6922007-03-21 02:57:17 +00002237}
2238
2239static void
2240call_py_exitfuncs(void)
2241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 if (pyexitfunc == NULL)
2243 return;
Collin Winter670e6922007-03-21 02:57:17 +00002244
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 (*pyexitfunc)();
2246 PyErr_Clear();
Collin Winter670e6922007-03-21 02:57:17 +00002247}
2248
Antoine Pitrou011bd622009-10-20 21:52:47 +00002249/* Wait until threading._shutdown completes, provided
2250 the threading module was imported in the first place.
2251 The shutdown routine will wait until all non-daemon
2252 "threading" threads have completed. */
2253static void
2254wait_for_thread_shutdown(void)
2255{
2256#ifdef WITH_THREAD
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002257 _Py_IDENTIFIER(_shutdown);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002258 PyObject *result;
2259 PyThreadState *tstate = PyThreadState_GET();
2260 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
2261 "threading");
2262 if (threading == NULL) {
2263 /* threading not imported */
2264 PyErr_Clear();
2265 return;
2266 }
Martin v. Löwisafe55bb2011-10-09 10:38:36 +02002267 result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002268 if (result == NULL) {
2269 PyErr_WriteUnraisable(threading);
2270 }
2271 else {
2272 Py_DECREF(result);
2273 }
2274 Py_DECREF(threading);
Antoine Pitrou011bd622009-10-20 21:52:47 +00002275#endif
2276}
2277
Guido van Rossum2dcfc961998-10-01 16:01:57 +00002278#define NEXITFUNCS 32
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002279static void (*exitfuncs[NEXITFUNCS])(void);
Guido van Rossum1662dd51994-09-07 14:38:28 +00002280static int nexitfuncs = 0;
2281
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002282int Py_AtExit(void (*func)(void))
Guido van Rossum1662dd51994-09-07 14:38:28 +00002283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002284 if (nexitfuncs >= NEXITFUNCS)
2285 return -1;
2286 exitfuncs[nexitfuncs++] = func;
2287 return 0;
Guido van Rossum1662dd51994-09-07 14:38:28 +00002288}
2289
Guido van Rossumcc283f51997-08-05 02:22:03 +00002290static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002291call_ll_exitfuncs(void)
Guido van Rossumcc283f51997-08-05 02:22:03 +00002292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002293 while (nexitfuncs > 0)
2294 (*exitfuncs[--nexitfuncs])();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 fflush(stdout);
2297 fflush(stderr);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002298}
2299
2300void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002301Py_Exit(int sts)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 Py_Finalize();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002304
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 exit(sts);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00002306}
2307
Guido van Rossumf1dc5661993-07-05 10:31:29 +00002308static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002309initsigs(void)
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002310{
Guido van Rossuma110aa61994-08-29 12:50:44 +00002311#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 PyOS_setsig(SIGPIPE, SIG_IGN);
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002313#endif
Guido van Rossum70d893a2001-08-16 08:21:42 +00002314#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 PyOS_setsig(SIGXFZ, SIG_IGN);
Guido van Rossum70d893a2001-08-16 08:21:42 +00002316#endif
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002317#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 PyOS_setsig(SIGXFSZ, SIG_IGN);
Jeremy Hylton1b0bf9b2002-04-23 20:31:01 +00002319#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 PyOS_InitInterrupts(); /* May imply initsignal() */
Guido van Rossuma9e7dc11992-10-18 18:53:57 +00002321}
2322
Guido van Rossum7433b121997-02-14 19:45:36 +00002323
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002324/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2325 *
2326 * All of the code in this function must only use async-signal-safe functions,
2327 * listed at `man 7 signal` or
2328 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2329 */
2330void
2331_Py_RestoreSignals(void)
2332{
2333#ifdef SIGPIPE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 PyOS_setsig(SIGPIPE, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002335#endif
2336#ifdef SIGXFZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 PyOS_setsig(SIGXFZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002338#endif
2339#ifdef SIGXFSZ
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 PyOS_setsig(SIGXFSZ, SIG_DFL);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002341#endif
2342}
2343
2344
Guido van Rossum7433b121997-02-14 19:45:36 +00002345/*
2346 * The file descriptor fd is considered ``interactive'' if either
2347 * a) isatty(fd) is TRUE, or
2348 * b) the -i flag was given, and the filename associated with
2349 * the descriptor is NULL or "<stdin>" or "???".
2350 */
2351int
Martin v. Löwis95292d62002-12-11 14:04:59 +00002352Py_FdIsInteractive(FILE *fp, const char *filename)
Guido van Rossum7433b121997-02-14 19:45:36 +00002353{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 if (isatty((int)fileno(fp)))
2355 return 1;
2356 if (!Py_InteractiveFlag)
2357 return 0;
2358 return (filename == NULL) ||
2359 (strcmp(filename, "<stdin>") == 0) ||
2360 (strcmp(filename, "???") == 0);
Guido van Rossum7433b121997-02-14 19:45:36 +00002361}
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002362
2363
Tim Petersd08e3822003-04-17 15:24:21 +00002364#if defined(USE_STACKCHECK)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002365#if defined(WIN32) && defined(_MSC_VER)
2366
2367/* Stack checking for Microsoft C */
2368
2369#include <malloc.h>
2370#include <excpt.h>
2371
Fred Drakee8de31c2000-08-31 05:38:39 +00002372/*
2373 * Return non-zero when we run out of memory on the stack; zero otherwise.
2374 */
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002375int
Fred Drake399739f2000-08-31 05:52:44 +00002376PyOS_CheckStack(void)
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 __try {
2379 /* alloca throws a stack overflow exception if there's
2380 not enough space left on the stack */
2381 alloca(PYOS_STACK_MARGIN * sizeof(void*));
2382 return 0;
2383 } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
2384 EXCEPTION_EXECUTE_HANDLER :
2385 EXCEPTION_CONTINUE_SEARCH) {
2386 int errcode = _resetstkoflw();
2387 if (errcode == 0)
2388 {
2389 Py_FatalError("Could not reset the stack!");
2390 }
2391 }
2392 return 1;
Fredrik Lundh2f15b252000-08-27 19:15:31 +00002393}
2394
2395#endif /* WIN32 && _MSC_VER */
2396
2397/* Alternate implementations can be added here... */
2398
2399#endif /* USE_STACKCHECK */
Guido van Rossum6f256182000-09-16 16:32:19 +00002400
2401
2402/* Wrappers around sigaction() or signal(). */
2403
2404PyOS_sighandler_t
2405PyOS_getsig(int sig)
2406{
2407#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 struct sigaction context;
2409 if (sigaction(sig, NULL, &context) == -1)
2410 return SIG_ERR;
2411 return context.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002412#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 PyOS_sighandler_t handler;
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002414/* Special signal handling for the secure CRT in Visual Studio 2005 */
2415#if defined(_MSC_VER) && _MSC_VER >= 1400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 switch (sig) {
2417 /* Only these signals are valid */
2418 case SIGINT:
2419 case SIGILL:
2420 case SIGFPE:
2421 case SIGSEGV:
2422 case SIGTERM:
2423 case SIGBREAK:
2424 case SIGABRT:
2425 break;
2426 /* Don't call signal() with other values or it will assert */
2427 default:
2428 return SIG_ERR;
2429 }
Martin v. Löwisb45b3152005-11-28 17:34:23 +00002430#endif /* _MSC_VER && _MSC_VER >= 1400 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 handler = signal(sig, SIG_IGN);
2432 if (handler != SIG_ERR)
2433 signal(sig, handler);
2434 return handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002435#endif
2436}
2437
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002438/*
2439 * All of the code in this function must only use async-signal-safe functions,
2440 * listed at `man 7 signal` or
2441 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2442 */
Guido van Rossum6f256182000-09-16 16:32:19 +00002443PyOS_sighandler_t
2444PyOS_setsig(int sig, PyOS_sighandler_t handler)
2445{
2446#ifdef HAVE_SIGACTION
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 /* Some code in Modules/signalmodule.c depends on sigaction() being
2448 * used here if HAVE_SIGACTION is defined. Fix that if this code
2449 * changes to invalidate that assumption.
2450 */
2451 struct sigaction context, ocontext;
2452 context.sa_handler = handler;
2453 sigemptyset(&context.sa_mask);
2454 context.sa_flags = 0;
2455 if (sigaction(sig, &context, &ocontext) == -1)
2456 return SIG_ERR;
2457 return ocontext.sa_handler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002458#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 PyOS_sighandler_t oldhandler;
2460 oldhandler = signal(sig, handler);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002461#ifdef HAVE_SIGINTERRUPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 siginterrupt(sig, 1);
Anthony Baxter9ceaa722004-10-13 14:48:50 +00002463#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 return oldhandler;
Guido van Rossum6f256182000-09-16 16:32:19 +00002465#endif
2466}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002467
2468/* Deprecated C API functions still provided for binary compatiblity */
2469
2470#undef PyParser_SimpleParseFile
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002471PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002472PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
2473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002475}
2476
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002477#undef PyParser_SimpleParseString
2478PyAPI_FUNC(node *)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002479PyParser_SimpleParseString(const char *str, int start)
2480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 return PyParser_SimpleParseStringFlags(str, start, 0);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00002482}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002483
2484#undef PyRun_AnyFile
2485PyAPI_FUNC(int)
2486PyRun_AnyFile(FILE *fp, const char *name)
2487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 return PyRun_AnyFileExFlags(fp, name, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002489}
2490
2491#undef PyRun_AnyFileEx
2492PyAPI_FUNC(int)
2493PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
2494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002496}
2497
2498#undef PyRun_AnyFileFlags
2499PyAPI_FUNC(int)
2500PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
2501{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 return PyRun_AnyFileExFlags(fp, name, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002503}
2504
2505#undef PyRun_File
2506PyAPI_FUNC(PyObject *)
2507PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
2508{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002510}
2511
2512#undef PyRun_FileEx
2513PyAPI_FUNC(PyObject *)
2514PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
2515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002517}
2518
2519#undef PyRun_FileFlags
2520PyAPI_FUNC(PyObject *)
2521PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 PyCompilerFlags *flags)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002525}
2526
2527#undef PyRun_SimpleFile
2528PyAPI_FUNC(int)
2529PyRun_SimpleFile(FILE *f, const char *p)
2530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 return PyRun_SimpleFileExFlags(f, p, 0, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002532}
2533
2534#undef PyRun_SimpleFileEx
2535PyAPI_FUNC(int)
2536PyRun_SimpleFileEx(FILE *f, const char *p, int c)
2537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 return PyRun_SimpleFileExFlags(f, p, c, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002539}
2540
2541
2542#undef PyRun_String
2543PyAPI_FUNC(PyObject *)
2544PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
2545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 return PyRun_StringFlags(str, s, g, l, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002547}
2548
2549#undef PyRun_SimpleString
2550PyAPI_FUNC(int)
2551PyRun_SimpleString(const char *s)
2552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 return PyRun_SimpleStringFlags(s, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002554}
2555
2556#undef Py_CompileString
2557PyAPI_FUNC(PyObject *)
2558Py_CompileString(const char *str, const char *p, int s)
2559{
Georg Brandl8334fd92010-12-04 10:26:46 +00002560 return Py_CompileStringExFlags(str, p, s, NULL, -1);
2561}
2562
2563#undef Py_CompileStringFlags
2564PyAPI_FUNC(PyObject *)
2565Py_CompileStringFlags(const char *str, const char *p, int s,
2566 PyCompilerFlags *flags)
2567{
2568 return Py_CompileStringExFlags(str, p, s, flags, -1);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002569}
2570
2571#undef PyRun_InteractiveOne
2572PyAPI_FUNC(int)
2573PyRun_InteractiveOne(FILE *f, const char *p)
2574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 return PyRun_InteractiveOneFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002576}
2577
2578#undef PyRun_InteractiveLoop
2579PyAPI_FUNC(int)
2580PyRun_InteractiveLoop(FILE *f, const char *p)
2581{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 return PyRun_InteractiveLoopFlags(f, p, NULL);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002583}
2584
2585#ifdef __cplusplus
2586}
2587#endif